/*
 * @Author: XianKaiQun
 * @Date: 2020-07-07 09:22:05
 * @LastEditors: wuwei
 * @LastEditTime: 2024-04-29 11:26:47
 * @Description: 
 */

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/person.dart';
// import 'package:app_package/src/stores/push.dart';
// import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class MenuDragListStore with ChangeNotifier {
  final BuildContext context;
  MenuDragListStore(this.context);

  final appGlobalStore = GetIt.I.get<AppGlobalStore>();

  PersonModel? person;

  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();
  // final pushGlobalStore = GetIt.I.get<PushGlobalStore>();

  /// 小区信息
  final communityGlobalStore = GetIt.I.get<CommunityGlobalStore>();

  final scrollViewKey = GlobalKey<WisScrollViewState>();
  final scrollViewKeyReoder = GlobalKey();

  final ScrollController reorderscrollController = ScrollController();

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

  ScrollController mainController = new ScrollController();
  ScrollController mainController1 = new ScrollController();

  /// 首页初始化
  onInit() async {
    await Future.wait([
      getMenuList(),
    ]);
  }

  /// 判断是否包含路由
  bool isContainRoutes(route) {
    return allMenuList.map((item) => item.route).toList().contains(route);
  }

  Map get localInfo => WisStorageUtil.get(key: 'storage-loginInfo') ?? {};
  get entCode => localInfo['entCode'] ?? '';
  get account => localInfo['account'] ?? '';

  List orderNewList = [];
  List get orderRouteList => orderNewList.map((item) => item.id).toList();

  /// 功能菜单排序
  Future<void> orderMenuList(list, oldIndex, newIndex) async {
    orderNewList = list;
    final data = orderNewList.removeAt(oldIndex);
    orderNewList.insert(newIndex, data);
    notifyListeners();
  }

  /// 确认功能排序顺序 并返回
  Future<void> onConfirmOrder() async {
    if (orderNewList.length > 0) {
      await WisStorageUtil.set(
          key: 'order-menu-list-$entCode-$account', data: orderNewList);
    }
    Navigator.pop(context);
  }

  /// 移除首页功能
  Future<void> removeHomeFunc(item, index) async {
    orderNewList.removeAt(index);
    notifyListeners();
  }

  /// 添加首页功能
  Future<void> addHomeFunc(item) async {
    orderNewList.add(item);
    notifyListeners();
  }

  List allMenuList = [];
  HgjMenuModel scanItem = HgjMenuModel(
    id: 'scan',
    route: 'scan',
    name: '扫一扫',
    icon:
        'https://wy.huiguanjia.cn/9ad134a361f8d778/file/images/642699921123110912',
    applicationType: 'app',
    ownershipPage: 'worktable',
    relationCommunity: true,
  );

  HgjMenuModel formItem = HgjMenuModel(
    id: 'message_index',
    route: 'message_index',
    name: '智能填表',
    icon:
        'https://wy.huiguanjia.cn/9ad134a361f8d778/file/images/814911552159289344',
    applicationType: 'app',
    ownershipPage: 'worktable',
    relationCommunity: true,
  );

  /// 文档地址： https://huiguanjia21.yuque.com/staff-skcq9k/gq9nbb/stnx8o7d6md0gz2y?singleDoc
  /// 通用组菜单
  /// 【 扫一扫、作业管理	task/work_statistic/index、管家服务	service/index、任务管理	task/index、超期工单	overdue/index、文件柜	cabinet/index、协同办公	oa/index、 智能填表、考勤打卡	attendance/signIn/index】
  List generalRouteList = [
    HgjMenuModel(
      id: 'scan',
      route: 'scan',
      name: '扫一扫',
      icon:
          'https://wy.huiguanjia.cn/9ad134a361f8d778/file/images/642699921123110912',
      applicationType: 'app',
      ownershipPage: 'worktable',
      relationCommunity: true,
    ),
    HgjMenuModel(
      id: 'message_index',
      route: 'message_index',
      name: '智能填表',
      icon:
          'https://wy.huiguanjia.cn/9ad134a361f8d778/file/images/814911552159289344',
      applicationType: 'app',
      ownershipPage: 'worktable',
      relationCommunity: true,
    ),
  ];
  List allGeneralRouteList = [
    "scan",
    "task/work_statistic/index",
    "service/index",
    "task/index",
    "overdue/index",
    "cabinet/index",
    "oa/index",
    "message_index",
    "attendance/signIn/index",
  ];

  /// 收费组菜单 【 收银台 bill/index、手机收单 receipt/index、车场收单 car_receipt/index、缴费记录 paylist/index 】
  List feeRouteList = [];
  List allFeeRouteList = [
    "bill/index",
    "receipt/index",
    "car_receipt/index",
    "paylist/index",
  ];

  /// 客服组菜单 【 小区通知 notice/index、服务动态 dynamic/index、通行证管理	face/index、客服中心	service_center/index 】
  List customRouteList = [];
  List allCustomRouteList = [
    "notice/index",
    "dynamic/index",
    "face/index",
    "service_center/index",
  ];

  /// 房管组菜单 【 小区清单	community/index、房管动态	statistics/filter、档案查询	search/index、二维码登记	qrcode/register 】
  List houseRouteList = [];
  List allHouseRouteList = [
    "community/index",
    "statistics/filter",
    "search/index",
    "qrcode/register",
  ];

  /// 工程组菜单 【 抄表管理	metered/index、智能表管理	intelligent/index、智能设备	smart_devices/index、养护检修】
  List engineerRouteList = [];
  List allEngineerRouteList = [
    "qrcode/repair",
    "metered/index",
    "intelligent/index",
    "smart_devices/index",
  ];

  HgjMenuModel? scurityItem;
  HgjMenuModel? cleanItem;
  HgjMenuModel greenItem = HgjMenuModel(
    id: 'green',
    route: 'scan',
    name: '环境绿化',
    icon:
        'https://wy.huiguanjia.cn/9ad134a361f8d778/file/images/815173433377755136',
    applicationType: 'app',
    ownershipPage: 'worktable',
    relationCommunity: true,
  );

  ///获取菜单
  Future getMenuList() async {
    print(WisStorageUtil.get(key: 'order-menu-list-$entCode-$account'));
    allMenuList = [];
    var params = {
      'isLogOn': 'yes',
      'applicationType': 'app',
      'ownershipPage': 'worktable',
    };
    var version = await AppPackageInfo.instance.getPackageInfoVersion();
    Platform.isAndroid
        ? params['androidMinimumVersion'] = version
        : params['iosMinimumVersion'] = version;
    var res = await RootApi.getMenuList(params);
    List<HgjMenuModel> list = res.data ?? [];
    print(list);
    if (Platform.isIOS) {
      list = list.where((v) => v.exist).toList();
    }
    list.forEach((item) {
      if (item.ownershipPage == 'informationCentre' ||
          item.ownershipPage == 'worktable') {
        allMenuList.add(item);
      }
      ;
      if (item.route == 'qrcode/security') {
        scurityItem = item;
      }
      ;
      if (item.route == 'qrcode/clean') {
        cleanItem = item;
      }
      ;
      // if (item.route == 'qrcode/repair')
      //   {
      //   },
      if (allGeneralRouteList.contains(item.route)) {
        generalRouteList.add(item);
      }
      ;
      if (allFeeRouteList.contains(item.route)) {
        feeRouteList.add(item);
      }
      ;
      if (allCustomRouteList.contains(item.route)) {
        customRouteList.add(item);
      }
      ;
      if (allHouseRouteList.contains(item.route)) {
        houseRouteList.add(item);
      }
      ;
      if (allEngineerRouteList.contains(item.route)) {
        engineerRouteList.add(item);
      }
      ;
    });

    /// 按文档给定顺序排序
    generalRouteList.sort((a, b) => allGeneralRouteList
        .indexOf(a.route)
        .compareTo(allGeneralRouteList.indexOf(b.route)));
    if (feeRouteList.length > 0) {
      feeRouteList.sort((a, b) => allFeeRouteList
          .indexOf(a.route)
          .compareTo(allFeeRouteList.indexOf(b.route)));
    }
    if (customRouteList.length > 0) {
      customRouteList.sort((a, b) => allCustomRouteList
          .indexOf(a.route)
          .compareTo(allCustomRouteList.indexOf(b.route)));
    }
    if (houseRouteList.length > 0) {
      houseRouteList.sort((a, b) => allHouseRouteList
          .indexOf(a.route)
          .compareTo(allHouseRouteList.indexOf(b.route)));
    }
    if (engineerRouteList.length > 0) {
      engineerRouteList.sort((a, b) => allEngineerRouteList
          .indexOf(a.route)
          .compareTo(allEngineerRouteList.indexOf(b.route)));
    }

    allMenuList = allMenuList;
    generalRouteList = generalRouteList;
    feeRouteList = feeRouteList;
    customRouteList = customRouteList;
    houseRouteList = houseRouteList;
    engineerRouteList = engineerRouteList;
    notifyListeners();
    await WisStorageUtil.set(key: 'all-menu-list', data: allMenuList);

    List olist =
        (WisStorageUtil.get(key: 'order-menu-list-$entCode-$account') ?? [])
            .map((item) => HgjMenuModel.fromJson(item))
            .toList();
            print(olist);
    if (olist.length == 0) {
      await WisStorageUtil.set(
          key: 'order-menu-list-$entCode-$account', data: allMenuList);
      allMenuList.add(scanItem);
      allMenuList.add(formItem);
      print(allMenuList);
      orderNewList = allMenuList;
    } else {
      print(olist);
      orderNewList = olist;
    }

    notifyListeners();
  }
}
