/*
 * @Author: XianKaiQun
 * @Date: 2020-07-07 09:22:05
 * @LastEditors: wuwei
 * @LastEditTime: 2024-04-29 16:31:42
 * @Description: 
 */

import 'dart:io';

import 'package:app_package/src/api/message.dart';
import 'package:app_package/src/api/root.dart';
import 'package:app_package/src/models/dynamic_statistics.dart';
import 'package:app_package/src/models/hgj_menu.dart';
import 'package:app_package/src/models/notice_statistics.dart';
import 'package:app_package/src/models/person.dart';
import 'package:app_package/src/models/repair_report.dart';
import 'package:app_package/src/models/task_fee.dart';
import 'package:app_package/src/models/task_statistics.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';
import 'package:intl/intl.dart' show DateFormat;

import '../common/route2business.dart';
import '../constants/config.dart';
import '../stores/app.dart';
import '../stores/auth.dart';
import '../stores/community.dart';

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

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

  PersonModel? person;

  /// 无个性化设置 所有授权菜单列表
  List<HgjMenuModel>? menuList = [];

  /// 快捷菜单列表
  List<HgjMenuModel>? fastMenuList;

  /// 顶部菜单长度
  int? get menuLength => allMenuList.length;

  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();

  /// 是否显示收费管理组件
  bool get isShowFee =>
      currentCommunity?.id == null ? false : isContainRoutes('bill/index');

  /// 是否显示抄表管理组件
  bool get isShowMeter =>
      currentCommunity?.id == null ? false : isContainRoutes('metered/index');

  /// 是否显示智能设备组件
  bool get isShowDevices => currentCommunity?.id == null
      ? false
      : isContainRoutes('smart_devices/index');

  /// 是否显示任务工单组件
  bool get isShowTask => isContainRoutes('task/index');

  /// 是否显示报事报修组件
  bool get isShowRepair => currentCommunity?.id == null
      ? false
      : (isContainRoutes('service_center/index') ||
          isContainRoutes('repair/index') ||
          isContainRoutes("report/index"));

  /// 是否显示通知公告组件
  bool get isShowNotice =>
      currentCommunity?.id == null ? false : isContainRoutes('notice/index');

  /// 是否显示服务动态组件
  bool get isShowDynamic =>
      currentCommunity?.id == null ? false : isContainRoutes('dynamic/index');

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

  ///去选择小区
  toCommunityPick() async {
    await Navigator.pushNamed(context, 'community');
    if (currentCommunity?.id == null) return;
    dynamicCardList = [];
    taskCardList = [];
    notifyListeners();
    await initWidget();
    await setList();
  }

  int dynamicCardIndex = 0;

  int taskCardIndex = 0;

  /// 报事报修统计小组件卡片 选择第几项
  onSelectTab(index) async {
    dynamicCardIndex = index;
    initDynamicCard(index);
    notifyListeners();
  }

  onSelectWorkTab(index) async {
    taskCardIndex = index;
    notifyListeners();
  }

  /// 首页初始化
  onInit() async {
    await Future.wait([
      // getFastMenuList(),
      // getSettingMenuList(),
      getMenuList(),
      getNoticeList(),
      // communityGlobalStore.getShowNoticeDot(currentCommunity?.id)
    ]);
  }

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

  /// 本地缓存的卡片组件顺序
  List get localWidgetList =>
      WisStorageUtil.get(key: 'widget-index-list') ?? [];

  /// 存放卡片组件
  List widgetList = [];

  /// 设置组件顺序
  Future<void> setList() async {
    widgetList = [];

    if (localWidgetList.length > 0) {
      widgetList = localWidgetList;
    }

    /// 任务
    if (isShowTask) {
      if (taskCardList.length > 1) {
        if (widgetList.contains('TaskTabs') != true) {
          widgetList.add('TaskTabs');
        }
      } else {
        widgetList.remove('TaskTabs');
      }
      if (taskCardList.length == 1) {
        if (widgetList.contains('WorkCard') != true) {
          widgetList.add('WorkCard');
        }
      } else {
        widgetList.remove('WorkCard');
      }
      if (widgetList.contains('TaskCard') != true) {
        widgetList.add('TaskCard');
      }
    } else {
      widgetList.remove('TaskTabs');
      widgetList.remove('WorkCard');
      widgetList.remove('TaskCard');
    }

    /// 收费员
    if (isContainRoutes('bill/index')) {
      if (widgetList.contains('FeeWidget') != true) {
        widgetList.add(
          'FeeWidget',
        );
      }
    } else {
      widgetList.remove('FeeWidget');
    }

    /// 报事报修、服务动态、通知公告
    if (((isContainRoutes('service_center/index') ||
          isContainRoutes('repair/index') ||
          isContainRoutes("report/index")) ||
            isContainRoutes('notice/index') ||
            isContainRoutes('dynamic/index')) &&
        dynamicCardList.length > 0) {
      if (widgetList.contains('NoticeTabs') != true) {
        widgetList.add('NoticeTabs');
      }
    } else {
      widgetList.remove('NoticeTabs');
    }

    /// 工程
    if ((isContainRoutes('metered/index') ||
        isContainRoutes('smart_devices/index'))) {
      if (widgetList.contains('EngineerWidget') != true) {
        widgetList.add('EngineerWidget');
      }
    } else {
      widgetList.remove('EngineerWidget');
    }

    widgetList = widgetList;
    notifyListeners();

    await WisStorageUtil.set(key: 'widget-index-list', data: widgetList);
  }

  onReorderStarted(int index) async {
    if (currentCommunity?.id == null) {
      WToastUtil.show('请先选择小区');
      return;
    }
  }

  /// 首页小组件排序
  Future<void> orderList(oldIndex, newIndex) async {
    final data = widgetList.removeAt(oldIndex);
    widgetList.insert(newIndex, data);
    notifyListeners();
    await WisStorageUtil.set(key: 'widget-index-list', data: widgetList);
  }

  /// 服务动态卡片 标签列表
  List dynamicCardList = [];

  /// 任务卡片标签列表
  List taskCardList = [];

  /// 初始化所有组件卡片数据
  Future<void> initWidget() async {
    if (isShowFee) {
      getFee();
    }

    if (isShowMeter) {
      getMeters();
    }

    if (isShowDevices) {
      getSmartDevice();
    }
    if (isShowRepair) {
      dynamicCardList.add({'value': 'repair', 'name': '报事报修'});
    }
    if (isShowNotice) {
      dynamicCardList.add({'value': 'notice', 'name': '通知公告'});
    }
    if (isShowDynamic) {
      dynamicCardList.add({'value': 'dynamic', 'name': '服务动态'});
    }
    print(dynamicCardList);
    if (isShowTask) {
      await getTaskStatistic();
      await getTaskFee();
      await getTaskList();
    }
    dynamicCardIndex = 0;
    taskCardIndex = 0;
    onSelectWorkTab(0);
    await initDynamicCard(dynamicCardIndex);
    notifyListeners();
  }

  /// 初始化 报事报修、通知公告、服务动态卡片
  Future<void> initDynamicCard(index) async {
    if (dynamicCardList.length == 0) return;
    switch (dynamicCardList[index]['value']) {
      case 'repair':
        getRepairStatistic();
        break;
      case 'notice':
        getNoticeStatistic();
        break;
      case 'dynamic':
        getDynamicStatistic();
        break;
      default:
    }
  }

  /// 个性化设置所有菜单列表 树状结构
  List? pageMenuList;

  /// 非个性化设置下所有授权菜单 排序
  List allMenuList = [];

  List get menuOrderList =>
      (WisStorageUtil.get(key: 'order-menu-list-$entCode-$account') ?? [])
          .map((item) => HgjMenuModel.fromJson(item))
          .toList();

  /// 个性化设置详情
  var pageDetail;

  // bool get isNewNotice => pushGlobalStore.isNewNotice;

  ///获取未读消息数
  Future getMsgcount() async {
    await MessageApi.getMsgCount();
    notifyListeners();
  }

  ///跳转我的消息
  Future route2notice() async {
    // pushGlobalStore.setIsNewNotice(false);
    await Navigator.pushNamed(
      context,
      'notice',
    );
    getMsgcount();
  }

  /// 个性化菜单
  // Future getSettingMenuList() async {
  //   var res = await appGlobalStore.getPageSetting('512672712577089538');
  //   pageMenuList = res?.groupData ?? [];
  //   await initWidget();
  //   pageDetail = res;
  //   notifyListeners();
  // }

  ///获取菜单
  Future getMenuList() async {
    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 ?? [];

    if (Platform.isIOS) {
      list = list.where((v) => v.exist).toList();
    }
    menuList = list;
    notifyListeners();
    
    // 处理工作台菜单
    list.forEach((item) {
      if (item.ownershipPage == 'informationCentre' ||
          item.ownershipPage == 'worktable') {
        allMenuList.add(item);
      }
    });

    await WisStorageUtil.set(key: 'all-menu-list', data: allMenuList);

    // 获取本地缓存的菜单列表
    List cachedMenuList = [];
    if (WisStorageUtil.get(key: 'order-menu-list-$entCode-$account') != null) {
      cachedMenuList =
          WisStorageUtil.get(key: 'order-menu-list-$entCode-$account')
              .map((item) => HgjMenuModel.fromJson(item))
              .toList();
    }
    
    // 处理菜单项 - 修改逻辑
    if (cachedMenuList.isNotEmpty) {
      // 只保留缓存中的菜单项，并用新获取的数据更新它们
      List<HgjMenuModel> updatedMenuList = [];

      // 遍历缓存菜单，只保留那些在新菜单中仍然存在的项（或特殊项如scan）
      for (var cachedItem in cachedMenuList) {
        // 检查缓存的菜单项是否仍然存在于新获取的菜单中
        bool stillExists =
            allMenuList.any((newItem) => newItem.route == cachedItem.route) ||
                (cachedItem.route == 'scan');
        if (stillExists) {
          // 找到新菜单中对应的项（可能有更新）
          var updatedItem = allMenuList.firstWhere(
            (newItem) => newItem.route == cachedItem.route,
            orElse: () => cachedItem,
          );
          updatedMenuList.add(updatedItem);
        }
      }
      
      // 更新 allMenuList 为处理后的列表（只包含缓存中存在的项）
      allMenuList = updatedMenuList;
      
      // 保存更新后的菜单列表到本地缓存
      await WisStorageUtil.set(
          key: 'order-menu-list-$entCode-$account', data: updatedMenuList);
    } else {
      // 如果本地没有缓存，则保存所有菜单
      await WisStorageUtil.set(
          key: 'order-menu-list-$entCode-$account', data: allMenuList);
    }

    dynamicCardList = [];
    taskCardList = [];
    notifyListeners();
    await initWidget();
    await setList();
  }

  @override
  String toString() {
    return menuList!.map((e) => e.toJson()).toString();
  }

  List noticeList = [];

  /// 获取公告列表
  Future getNoticeList() async {
    var res = await RootApi.getNoticeList({
      "pageNum": 1,
      "pageSize": 5,
    });
    noticeList = res.data?.list ?? [];
    notifyListeners();
  }

  /// 跳转公告列表
  toNoticeList() async {
    await Navigator.pushNamed(
      context,
      'notice_index',
      arguments: {'isList': true},
    );
    getNoticeList();
  }

  /// 跳转公告详情
  routeToDetail(item) async {
    await Navigator.pushNamed(
      context,
      'notice_detail',
      arguments: {
        'isList': false,
        'id': item.id,
      },
    );
    getNoticeList();
  }

  /// 跳转到排序页面
  void toOrder() async {
    await WNavUtil.instance!.pushNamed('menu_order');
    notifyListeners();
  }

  /// 路由跳转
  toRoutes(item, type) {
    switch (type) {
      // case 'oa':
      //   break;
      case 'menu':
        toMenuDetail(item);
        break;
      case 'intelligentForm':
        appGlobalStore.toFormDetail(item);
        break;
    }
  }

  Future<void> toMenuDetail(item) async {
    ///判断未开通
    if (!item.exist) {
      return WToastUtil.show('正在建设中...');
    }
    if (item.relationCommunity == true) {
      var boolean = await intent;
      notifyListeners();
      if (boolean) {
        if (item.route == 'qrcode/clean' || item.route == 'qrcode/security') {
          final context = WNavUtil.instance!.context;
          await Route2business.scan2page(
            context: context!,
            scene: item.route == 'qrcode/clean'
                ? ScanScene.clean
                : ScanScene.security,
          );
          notifyListeners();
        } else if (item.route == 'qrcode/register') {
          final context = WNavUtil.instance!.context;
          await Route2business.scan2page(
            context: context!,
            scene: ScanScene.qrRegister,
          );
        } else if (item.route == 'scan') {
          // 扫一扫
          await Future.delayed(Duration(milliseconds: 300));
          await Route2business.scan2page(
            context: context,
            scene: ScanScene.mainEntrance,
          );
        } else {
          await WNavUtil.instance!
              .pushNamed(item?.route, arguments: {'appBarTitle': item?.name});
          notifyListeners();
        }
      }
    } else if (item.route == 'qrcode/clean' ||
        item.route == 'qrcode/security') {
      final context = WNavUtil.instance!.context;
      await Route2business.scan2page(
        context: context!,
        scene:
            item.route == 'qrcode/clean' ? ScanScene.clean : ScanScene.security,
      );
      notifyListeners();
    } else {
      await WNavUtil.instance!
          .pushNamed(item?.route, arguments: {'appBarTitle': item?.name});
      notifyListeners();
    }
  }

  /// 跳转选择小区 返回是否获取到小区
  Future<bool> get intent async {
    if (currentCommunity?.id == null) {
      await toCommunityPick();
      if (currentCommunity?.id == null) {
        await WToastUtil.show('无法确认您工作小区');
      }
    }
    return currentCommunity?.id != null;
  }

  /// 服务动态统计
  DynamicStatisticsModel? dynamicStatistics;

  /// 获取服务动态统计
  Future<void> getDynamicStatistic() async {
    var res = await RootApi.getDynamicStatistics(
        {'communityId': currentCommunity?.id});
    dynamicStatistics = res.data!;
    notifyListeners();
  }

  /// 报事报修统计
  RepairReportModel? repairStatistics;

  /// 获取报事报修统计
  Future<void> getRepairStatistic() async {
    var res =
        await RootApi.getRepairReport({'communityId': currentCommunity?.id});
    repairStatistics = res.data!;
    notifyListeners();
  }

  /// 通知公告统计
  NoticeStatisticsModel? noticeStatistics;

  /// 获取通知公告统计
  Future<void> getNoticeStatistic() async {
    var res = await RootApi.getNoticeStatistics(
        {'communityId': currentCommunity?.id});
    noticeStatistics = res.data!;
    notifyListeners();
  }

  ///任务统计
  TaskStatisticsModel? taskStatistics;

  /// 获取任务统计
  Future<void> getTaskStatistic() async {
    var res = await RootApi.getTaskStatistics();
    taskStatistics = res.data!;
    notifyListeners();
  }

  /// 任务列表
  List taskIconList = [];

  bool isMultiCard = false;

  ///获取任务列表
  Future<void> getTaskList() async {
    var res = await RootApi.getTaskList();
    taskCardList = [];
    res.data!.forEach((item) {
      if (item.undoneCount! > 0) {
        isMultiCard = true;
      }
      // 安保巡逻
      if (item.inventoryId == '451357265515982848' && item.undoneCount! > 0) {
        taskCardList.add(item);
        taskIconList.add({
          'select': 'lib/assets/main/anjian_h.png',
          'unSelect': 'lib/assets/main/anjian.png'
        });
      }
      ;
      // 保洁清洁
      if (item.inventoryId == '522832327887884288' && item.undoneCount! > 0) {
        taskCardList.add(item);
        taskIconList.add({
          'select': 'lib/assets/main/baojie_h.png',
          'unSelect': 'lib/assets/main/baojie.png'
        });
      }
      ;

      //  设备保养
      if (item.inventoryId == '451357265520177153' && item.undoneCount! > 0) {
        taskCardList.add(item);
        taskIconList.add({
          'select': 'lib/assets/main/sbwx_h.png',
          'unSelect': 'lib/assets/main/sbwx.png'
        });
      }
      ;
      //   设备巡检
      if (item.inventoryId == '451357265520177152' && item.undoneCount! > 0) {
        taskCardList.add(item);
        taskIconList.add({
          'select': 'lib/assets/main/sbxj_h.png',
          'unSelect': 'lib/assets/main/sbxj.png'
        });
      }
      ;
      //  养护绿化
      if (item.inventoryId == '525361915470270464' && item.undoneCount! > 0) {
        taskCardList.add(item);
        taskIconList.add({
          'select': 'lib/assets/main/lvhua_h.png',
          'unSelect': 'lib/assets/main/lvhua1.png'
        });
      }
      ;
      //  品质巡查
      if (item.inventoryId == '718505360034664448' && item.undoneCount! > 0) {
        taskCardList.add(item);
        taskIconList.add({
          'select': 'lib/assets/main/pzxc_h.png',
          'unSelect': 'lib/assets/main/pzxc1.png'
        });
      }
      ;
    });
    notifyListeners();
  }

  /// 罚金
  TaskFeeModel? taskFee;

  /// 获取罚金
  Future<void> getTaskFee() async {
    var res = await RootApi.getTaskFee({
      'companyId': authGlobalStore.info?.companyId,
    });
    taskFee = res.data;
    notifyListeners();
  }

  List deviceStatistics = [];

  /// 获取智能设备列表
  Future<void> getSmartDevice() async {
    var res = await RootApi.getSmartDeviceStatistics(
        {'communityId': currentCommunity?.id});
    deviceStatistics = res.data!;
    notifyListeners();
  }

  var meterStatistics;

  /// 获取抄表统计
  Future<void> getMeters() async {
    var res =
        await RootApi.getMeterStatistics({'communityId': currentCommunity?.id});
    meterStatistics = res.data;
    notifyListeners();
  }

  var feeStatistics;
  bool billStatisticIsThisMonth = true;

  /// 获取收费卡片数据(应收、欠费、实收、今日已收、收费率)
  Future<void> getFee() async {
    feeStatistics = null;
    notifyListeners();
    billStatisticIsThisMonth =
        WisStorageUtil.get(key: 'bill_statistic_is_this_month') ?? true;
    var current = DateFormat('yyyy-MM').format(DateTime.now());
    var last = DateFormat("yyyy-MM")
        .format(DateTime(DateTime.now().year, DateTime.now().month - 1));
    var res = await RootApi.getFeeStatistics({
      'communityId': currentCommunity?.id,
      'chargeYearMonth': billStatisticIsThisMonth == true ? current : last
    });
    feeStatistics = res.data;
    notifyListeners();
  }

  String get billStatisticIsMonthText =>
      billStatisticIsThisMonth == true ? '本期' : '上期';

  /// 跳转收费管理
  void toFee() {
    WNavUtil.instance!.pushNamed('bill/index');
  }

  /// 跳转任务统计
  void toTaskStatistics() {
    WNavUtil.instance!.pushNamed('task/statistic');
  }

  /// 跳转智能设备
  void toDevices() async {
    WNavUtil.instance!.pushNamed('smart_devices/index');
  }

  /// 跳转手机抄表
  void toMeters() async {
    WNavUtil.instance!.pushNamed('metered/index');
  }

  void toRepairIndex() async {
    WNavUtil.instance!.pushNamed('repair/index');
  }

  void toReportIndex() async {
    WNavUtil.instance!.pushNamed('report/index');
  }

  /// 跳转客服工作台
  void toRepair() async {
    WNavUtil.instance!
        .pushNamed('service/index', arguments: {'appBarTitle': '客服工作台'});
  }

  /// 跳转通知公告
  void toNotice() async {
    WNavUtil.instance!.pushNamed('notice/add');
  }

  /// 跳转服务动态
  void toDynamic() async {
    WNavUtil.instance!.pushNamed('dynamic/edit');
  }

  /// 跳转任务工单待领取列表
  void toWaitTask() async {
    await WNavUtil.instance!.pushNamed(
      'task/hall',
    );
  }

  /// 跳转未开始任务列表
  void toNoOpenTask() async {
    await WNavUtil.instance!.pushNamed('task/index', arguments: {
      'appBarTitle': '任务工单',
      'status': 'isNoOpen',
    });
  }

  /// 跳转进行中任务列表
  void toDoingTask() async {
    await WNavUtil.instance!.pushNamed('task/index', arguments: {
      'appBarTitle': '任务工单',
      'status': 'isDoing',
    });
  }

  /// 带任务类型跳转任务列表
  void toTask(data) async {
    await WNavUtil.instance!.pushNamed('task/index', arguments: {
      'appBarTitle': '任务工单',
      'type': data.inventoryId,
    });
  }

  /// 跳转任务详情 item：任务项
  Future<void> toTaskDetail(item) async {
    await Navigator.pushNamed(
      context,
      'task/detail',
      arguments: {
        'id': item.id,
        'isChild': false,
      },
    );
  }
}
