/*
 * @Author: XianKaiQun
 * @Date: 2020-07-16 18:09:39
 * @LastEditors: wuwei
 * @LastEditTime: 2024-01-11 15:16:37
 * @Description: 
 */
import 'dart:convert';
import 'dart:io';

import 'package:app_package/app_package.dart';
import 'package:app_package/src/api/root.dart';
import 'package:app_package/src/models/hgj_menu.dart';
import 'package:app_package/src/models/menu_detail.dart';
import 'package:app_package/src/models/menu_list.dart';
import 'package:app_package/src/models/person.dart';
import 'package:app_package/src/models/state_menu.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class PrivateMessageStore with ChangeNotifier {
  late final BuildContext context, providerContext;
  late var routingArgs;
  PrivateMessageStore(this.context, this.providerContext) {
    routingArgs = ModalRoute.of(context)!.settings.arguments;
  }
  late final appGlobalStore = GetIt.I.get<AppGlobalStore>();

  late final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  late PersonModel person;
  List<HgjMenuModel> menuList = [];

  ///从储存中取出的当前小区 拿出来可能是空
  CommunityModel? get currentCommunity => communityGlobalStore.data;

  final scrollViewKey = GlobalKey<WisScrollViewState>();

  final entCode = WisStorageUtil.get(key: 'storage-user-entCode');

  String title = '表单';

  ///去选择小区
  toCommunityPick() async {
    await Navigator.pushNamed(context, 'community');
    scrollViewKey.currentState?.initTrigger();
    notifyListeners();
  }

  ///去业务路由
  toBusinessPackage(routes) async {
    if (currentCommunity!.id == null && routes == 'search/index') {
      toCommunityPick();
      return;
    }
    await Navigator.pushNamed(context, routes);
    notifyListeners();
  }

  /// 菜单
  onInit() async {
    await Future.wait([
      getMenuList(),
      getStateMenuList(),
    ]);
  }

  toAddForm(title) async {
    await Navigator.pushNamed(
      context,
      'message_add',
      arguments: {
        'appBarTitle': title ?? '新建填表',
        'id': routingArgs!['item']?.formIdentification,
      },
    );
    onInitList();
  }

  toEditForm() async {
    await Navigator.pushNamed(
      context,
      'message_add',
      arguments: {
        'appBarTitle': detail.title ?? '新建填表',
        'id': detail.formIdentification,
        'fid': detail.id,
        'formValue': detail.fillContent,
        'formHtml': detail.formHtml,
        'detail': detail,
      },
    );
    onGetFormDetail();
  }

  List? pageMenuList;
  var pageDetail;

  Future getSettingMenuList() async {
    var res = await appGlobalStore.getPageSetting('512672712577089537');
    pageMenuList = res?.groupData ?? [];
    pageDetail = res;
    notifyListeners();
  }

  /// 智能填表详情初始化
  onInitDetail() async {
    title = routingArgs!['appBarTitle'] ?? '详情';
    await onGetFormDetail();
  }

  /// 智能填表列表初始化
  onInitList() async {
    await getAuth();
    await onGetFormList(false);
  }

  /// 授权列表
  List authList = [];

  /// 是否有填报权限
  bool hasFillAuth = false;

  ///获取填报权限
  Future getAuth() async {
    String id = routingArgs!['item'].formIdentification;
    final res = await RootApi.getAuthList();
    authList = res.data ?? [];

    // 判断是否有权限
    if (res.data != null && res.data!.length > 0) {
      res.data?.forEach((item) {
        if (item.forms!.length > 0) {
          item.forms!.forEach((form) {
            if (form.formIdentification == id) {
              hasFillAuth = true;
              notifyListeners();
            }
            ;
          });
        }
        ;
      });
    }

    notifyListeners();
  }

  ///获取常用信息菜单
  Future getMenuList() async {
    late Map<String, dynamic> params = {
      'isLogOn': 'yes',
      'applicationType': 'app',
      'ownershipPage': 'informationCentre',
    };
    var version = await AppPackageInfo.instance.getPackageInfoVersion();
    Platform.isAndroid
        ? params['androidMinimumVersion'] = version
        : params['iosMinimumVersion'] = version;
    var res = await RootApi.getMenuList(params);
    if (res.data != null && res.data!.length > 0) {
      res.data!.forEach((element) {
        element.mtype = 'static';
      });
      var list = res.data ?? [];
      if (Platform.isIOS) {
        list = list.where((v) => v.exist).toList();
      }
      menuList = list;
      notifyListeners();
    }
  }

  late List<WMenuItem> stateMenuList = [];
  late List<StateMenu> stateMenuAllList = [];
  late List stateMenuSearchList = [];

  /// 获取可查看表单列表
  Future getStateMenuList() async {
    var res = await RootApi.getStateMenuList();
    if (res.data != null && res.data!.length > 0) {
      res.data!.forEach((item) {
        item.forms!.forEach(
          (ele) {
            ele.mtype = 'state';
          },
        );
        stateMenuList.addAll(item.forms!);
      });
      stateMenuAllList = res.data ?? [];
      notifyListeners();
    }
  }

  String? searchValue = '';

  /// 搜索菜单
  onNameInput(data) {
    List tempList = [];
    stateMenuSearchList = [];
    notifyListeners();
    menuList.forEach((element) {
      if (element.name!.indexOf(data) != -1) {
        tempList.add(element);
      }
      ;
    });
    stateMenuList.forEach((element) {
      if (element.name!.indexOf(data) != -1) {
        tempList.add(element);
      }
      ;
    });
    stateMenuSearchList = tempList;
    searchValue = data;
    notifyListeners();
  }

  /// 智能填表 路由跳转
  Future toRoutes(item, type) async {
    /// 固定菜单
    if (item.mtype != 'state') {
      await Route2business.route2business(item);
    } else {
      if (item.type == 'community' && (currentCommunity!.id == null)) {
        WToastUtil.show('请先选择小区');
        await Future.delayed(Duration(milliseconds: 300));
        await toCommunityPick();
        if (currentCommunity != null && currentCommunity!.id != null) {
          handleRoute(item);
        }
      } else {
        handleRoute(item);
      }
    }
  }

  handleRoute(item) async {
    /// 单次填报表单
    if (item.fillPeriodType == 'single') {
      Map<String, dynamic> params = {
        'isPage': false,
        'formIdentification': item.formIdentification,
      };

      // params['communityId'] =
      //     currentCommunity != null && currentCommunity.id != null
      //         ? currentCommunity.id
      //         : null;
      var res = await RootApi.getMenuFormList(params);
      if (res.data != null && res.data!.length > 0) {
        toDetail(res.data![0], res.data![0].title);
      } else {
        toList(item);
      }
    } else {
      toList(item);
    }
  }

  /// 跳转详情
  toDetail(item, title) async {
    await Navigator.pushNamed(
      context,
      'message_detail',
      arguments: {
        'appBarTitle': title,
        'item': item,
      },
    );
  }

  /// 跳转填报列表
  toList(item) async {
    await Navigator.pushNamed(
      context,
      'message_list',
      arguments: {
        'appBarTitle': item?.name,
        'item': item,
      },
    );
  }

  List<MenuList> formHisList = [];
  List<MenuList> allHisList = [];
  int pageNum = 1;
  // Future onGetFormList(isLoad) async {
  //   if (isLoad == false) {
  //     Map<String, dynamic> params = {
  //       'isPage': false,
  //       'formIdentification': routingArgs!['item'].formIdentification,
  //     };
  //     var res = await RootApi.getMenuFormList(params);
  //     allHisList = res.data ?? [];
  //     print(allHisList.length);
  //     int _last = last > allHisList.length ? last : allHisList.length - 1;
  //     print(_last);
  //     print(first);
  //     formHisList = allHisList.getRange(first, _last).toList();

  //     first = (first + 20) > (allHisList.length - 1)
  //         ? first + 20
  //         : (allHisList.length - 1);
  //     last = first + 20;

  //     notifyListeners();
  //   } else {
  //     if (first < allHisList.length) {
  //       List _list = allHisList
  //           .getRange(
  //               first, last > allHisList.length ? last : allHisList.length - 1)
  //           .toList();
  //       formHisList = [...formHisList, ..._list];
  //       first = first + 20 > (allHisList.length - 1)
  //           ? (allHisList.length - 1)
  //           : first + 20;
  //       last = first + 20;
  //     }
  //     notifyListeners();
  //   }
  // }

  /// 获取表单记录列表
  Future onGetFormList(isLoad) async {
    Map<String, dynamic> params = {
      'pageSize': 20,
      'pageNum': pageNum,
      // 'isPage': true,
      'formIdentification': routingArgs!['item'].formIdentification,
    };

    if (!isLoad) params['pageNum'] = 1;
    var res = await RootApi.getMenuFormListPaging(params);

    final _data = res.data;
    final _list = _data?.list ?? [];
    if ((_data?.total ?? 0) == 0) {
      scrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      scrollViewKey.currentState?.isLast();
    } else {
      pageNum++;
    }
    isLoad ? formHisList.addAll(_list) : formHisList = _list;
    notifyListeners();
  }

  List formHtml = [];
  List formValue = [];
  late MenuDetail detail;

  dynamic titleItem;
  dynamic projectItem;
  dynamic periodItem;

  /// 获取表单详情
  Future onGetFormDetail() async {
    var res = await RootApi.getMenuFormDetail(routingArgs!['item']?.id);
    detail = res.data!;
    title = res.data!.title!;
    // 表单表格
    var html = jsonDecode(res.data!.formHtml!)['fields'];
    // 表单填写内容
    formValue = jsonDecode(res.data!.fillContent!);
    formValue.forEach((item) {
      /// 标题
      if (item['id'] == 1) {
        titleItem = {
          'name': '标题',
          'value': item['valueText'],
        };
      }
      ;

      /// 所属项目
      if (item['id'] == 2) {
        projectItem = {
          'name': '所属项目',
          'value': item['valueText'],
        };
      }
      ;

      /// 所属周期
      if (item['id'] == 3) {
        periodItem = {
          'name': '所属周期',
          'value': item['valueText'],
        };
      }
      ;
    });
    html.forEach((hitem) => {
          hitem['name'] = hitem['__config__']['label'] ?? '--',
          hitem['tag'] = hitem['__config__']['tag'],
          formValue.forEach((item) {
            if (item['id'] == hitem['__config__']['formId']) {
              hitem['name'] = item['name'];
              hitem['value'] = item['valueText'];
            }
          })
        });
    formHtml = html;
    notifyListeners();
  }

  void onShowImage(image) async {
    List<ImageProvider> images = [];
    images.add(CachedNetworkImageProvider(AppParseUtil.image(image)));
    WisPhotoViewUtil.show(images, 0);
  }

  /// 预览文件
  route2perview(url, name) {
    WisPreviewUtil.show(
      url: url,
      name: name,
    );
  }

  final List<String> fileArr = [
    'pdf',
    'docx',
    'xlsx',
    'xls',
    'doc',
    'pptx',
    'ppt'
  ];

  /// 是否支持查看文件类型
  isPreviewType(type) {
    if (fileArr.indexWhere((element) =>
            element == type.substring(type.lastIndexOf('.') + 1)) !=
        -1) {
      return true;
    } else {
      return false;
    }
  }

  /// 域名前缀
  final String baseUrl = APPConfig.baseURL;

  /// 附件点击查看
  onHandleFile(file) {
    /// 非图片
    if (file['type'].indexOf('image') == -1) {
      if (isPreviewType(file['name'])) {
        route2perview(
          baseUrl + 'file/download/' + file['id'],
          file['name'],
        );
      } else {
        WToastUtil.show('暂不支持此类文件预览，请使用电脑下载查看。');
      }

      /// 图片
    } else {
      onShowImage(file['id']);
    }
  }
}
