/*
 * @Author: ChenYaJin
 * @Date: 2023-04-10 10:20:16
 * @LastEditors: wuwei
 * @LastEditTime: 2024-01-08 10:04:18
 * @Description: 
 */
import 'package:intl/intl.dart';
import 'dart:convert';
import 'package:get/get.dart';
import 'package:app_package/src/api/employee.dart';
import 'package:app_package/src/models/community_picker.dart';
import 'package:task_package/src/models/task_inventory_model.dart';
import 'package:task_package/src/models/task_operation_node_list.dart';
import 'package:task_package/src/models/task_detail.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:task_package/src/impl/task_service_impl.dart';
import 'package:table_calendar/table_calendar.dart';
import '../../src/models/task_statistic_model.dart';
import '../../src/models/record_abnormal_model.dart';
import '../models/task_inventory_tree_model.dart';

class WorkStatisticStore extends GetxController {
  /// 作业统计
  final workScrViewKey = GlobalKey<WisScrollViewState>();
  var taskItemList = <TaskInventoryModel>[].obs;
  var communityList = <CommunityPickerModel>[].obs;
  var statisticList = [
    {'code': 'no_open', 'filed': 'noOpenCount', 'name': '未开始', 'total': 0},
    {'code': '', 'filed': 'taskTotal', 'name': '任务总数', 'total': 0},
    {'code': 'doing', 'filed': 'doingCount', 'name': '进行中', 'total': 0},
    {'code': 'finished', 'filed': 'finishedCount', 'name': '已完成', 'total': 0},
    {'code': 'overdue', 'filed': 'overdueCount', 'name': '已逾期', 'total': 0},
    {'code': 'outTime', 'filed': 'timeoutCount', 'name': '已超时', 'total': 0},
  ].obs;
  var communityIds = [].obs;
  var community = CommunityPickerModel().obs;
  var communityIName = ''.obs;
  var month = ''.obs;
  var year = ''.obs;
  var isPoint = true.obs;

  var isPointLast = false.obs;
  var isPointLoading = false.obs;
  var isPointEmpty = false.obs;
  var isAreaLast = false.obs;
  var isAreaLoading = false.obs;
  var isAreaEmpty = false.obs;

  // 接口参数
  var statusCode = ''.obs;
  var findType = 'up_to_now'.obs;
  var timePeriod = ''.obs; // 年/月
  var communityId = ''.obs;
  var organIds = [].obs;

  // 页面参数
  var findTypePra = 'up_to_now'.obs;
  var communityIdsPra = [].obs;
  var organIdsPra = [].obs;
  var monthPra = ''.obs;
  var yearPra = ''.obs;

  get isFilterStatus => true;

  var timeList = [
    {'code': 'up_to_now', 'name': '截止当前'},
    {'code': 'seven_days', 'name': '最近七日'},
    {'code': 'month', 'name': '上月'},
    {'code': 'year', 'name': '今年'},
  ];

  /// 滚动位置
  late double scrollHeight = 0;
  ScrollController outerController = new ScrollController();

  scrollToTop() {
    if (scrollHeight > 110) {
      outerController.animateTo(0.pt,
          duration: Duration(milliseconds: 200), curve: Curves.ease);
    }
  }

  onInit() async {
    super.onInit();
    getAsyncCommunityList();
    onGetTaskListItem();
    onGetOrganTree();
    outerController.addListener(() {
      scrollHeight = outerController.offset;
    });
  }

  /// 任务类型
  var inventoryFirstId = ''.obs;
  var inventoryIds = [].obs;
  var inventoryItem = TaskInventoryTreeModel().obs;

  var taskItemListTree = [].obs;
  var taskItemSecondList = [].obs;

  onGetTaskListTreeItem() async {
    var res =
        await TaskServiceImpl.instance!.getTaskInventoryTree({"preset": null});
    // var res =
    //     await TaskServiceImpl.instance!.getInventoryList({"preset": null});

    taskItemListTree.value = res.data ?? [];
    taskItemListTree.refresh();

    res.data?.forEach((element) {
      if (element.children != null) {
        element.children?.forEach((item) {
          if (item.id == statusCode.value) {
            setInventoryFirstItem(element);
            changeFirstInventoryValue(element.id!);
            setInventorySecondList(element.children);
          }
        });
      }
    });
    inventoryFirstId.refresh();
    inventoryItem.refresh();
  }

  void setInventoryFirstItem(item) {
    inventoryItem.value = item;
  }

  /// 选择任务类型
  void changeFirstInventoryValue(String code) {
    inventoryFirstId.value = code;
  }

  void changeSecondInventoryValue(String code) {
    onSelectInventor(code);
  }

  void setInventorySecondList(list) {
    taskItemSecondList.value = list;
    if (list.length == 0) {
      statusCode.value = '';
    }
    // inventoryIds.value = list.map((i) => i.id).toList();
    // inventoryIds.refresh();
    taskItemSecondList.refresh();
  }

  /// 获取任务统计
  Future getTaskStatisticTotal() async {
    var params = {
      'inventoryId': statusCode.value,
      'organIds': organIds.join(','),
      'findType': findType.value,
      'timePeriod': getPeriod(),
    };
    final res = await TaskServiceImpl.instance!.getWorkStatisticTotal(params);
    TaskStatisticModel _data = res.data!;
    statisticList[0]['total'] = _data.noOpenCount as Object;
    statisticList[1]['total'] = _data.taskTotal as Object;
    statisticList[2]['total'] = _data.doingCount as Object;
    statisticList[3]['total'] = _data.finishedCount as Object;
    statisticList[4]['total'] = _data.overdueCount as Object;
    statisticList[5]['total'] = _data.timeoutCount as Object;
    statisticList.refresh();
  }

  /// 获取部门树
  var organTree = [].obs;
  Future<List> getOrganList() async => organTree;

  onGetOrganTree() async {
    if (organTree.length != 0) {
      return;
    }
    final res = await TaskServiceImpl.instance!
        .getEployeeOransStat({'organName': null});
    organTree.value = jsonDecode(jsonEncode(res.data)) ?? [];
    organTree.refresh();
  }

  /// 获取预设清单列表
  onGetTaskListItem() async {
    var res =
        await TaskServiceImpl.instance!.getInventoryList({"preset": true});
    taskItemList.value = res.data ?? [];
    taskItemList.refresh();
    final lastId = taskItemList.last.id ?? null;
    onSelectInventor(lastId!);
  }

  /// 选择预设清单
  onSelectInventor(String id) async {
    statusCode.value = id;
    statusCode.refresh();
    if (isDateType.isTrue == true) {
      getRecordIdsByMonth(init: true);
    } else {
      initStatisticRankList();
    }
  }

  ///获取用户管辖的小区列表
  Future<List<CommunityPickerModel>> getCommunityList() async => communityList;
  getAsyncCommunityList() async {
    if (communityList.length != 0) {
      return;
    }
    var res = await EmployeeApi.getDomainCommunityListToPicker();
    communityList.value = res.data ?? [];
    communityList.refresh();
  }

  // 重置排名列表空页/最后一页 标识
  resetRankListPra() {
    isPointEmpty.value = false;
    isPointLast.value = false;
    isAreaEmpty.value = false;
    isAreaLast.value = false;
    pointAbnormalPrs['pageNum'] = 1;
    areaAbnormalPrs['pageNum'] = 1;
  }

  Future refreshRankList() async {
    scrollToTop();
    resetRankListPra();
    workScrViewKey.currentState?.initTrigger();
  }

  Future updateRankList({bool isLoad = true}) async {
    if (statusCode.isEmpty) {
      return;
    }
    scrollToTop();
    if (isDateType.isTrue == true) {
      if (isLoad == true) {
        getRecordListByCalendar(isLoad: isLoad);
      }
      if (isLoad == false && hasRequestCalendarData.value == false) {
        getRecordIdsByMonth(init: true);
      }
    } else {
      if (isPoint.isTrue == true) {
        getRecordListByPoint(isLoad: isLoad);
      } else {
        getRecordListByArea(isLoad: isLoad);
      }
    }
  }

  refreshCalendarData() {
    getRecordIdsByMonth(init: true);
  }

  /// 获取点位异常排名列表
  Map<String, dynamic> pointAbnormalPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };
  var pointList = <RecordAbnormalModel>[].obs;
  Future getRecordListByPoint({bool isLoad = true}) async {
    if (isLoad) pointAbnormalPrs['pageNum']++;
    isPointLoading.value = true;
    var params = {
      'inventoryId': statusCode.value,
      'organIds': organIds.join(','),
      'findType': findType.value,
      'timePeriod': getPeriod(),
      'communityIds': communityId.value,
      'groupType': 'relation_id',
      'isPage': true,
      ...pointAbnormalPrs,
    };
    final res = await TaskServiceImpl.instance!.getRecordAbnormalRank(params);
    final _data = res.data;
    var key = 0;
    if (_data?.list != null && _data!.list!.length > 0) {
      _data.list!.forEach((value) {
            key = _data.list!.indexOf(value);
            _data.list![key].abnormalRank = (pointAbnormalPrs['pageNum'] - 1) *
                    pointAbnormalPrs['pageSize'] +
                key +
                1;
          });
    }
    pointAbnormalPrs['pageNum'] == 1
        ? pointList.value = _data?.list ?? []
        : pointList.addAll(_data?.list ?? []);
    if ((_data?.total ?? 0) == 0) {
      isPointEmpty.value = true;
      workScrViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      isPointEmpty.value = true;
      workScrViewKey.currentState?.isLast();
    }
    pointList.refresh();
  }

  /// 获取区域异常排名列表
  ///
  Map<String, dynamic> areaAbnormalPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };
  var areaRankList = <RecordAbnormalModel>[].obs;
  getRecordListByArea({bool isLoad = true}) async {
    if (isLoad) areaAbnormalPrs['pageNum']++;
    var params = {
      'inventoryId': statusCode.value,
      'organIds': organIds.join(','),
      'findType': findType.value,
      'timePeriod': getPeriod(),
      'communityIds': communityId.value,
      'groupType': 'community_area_id',
      'isPage': true,
      ...areaAbnormalPrs,
    };
    final res = await TaskServiceImpl.instance!.getRecordAbnormalRank(params);
    final _data = res.data;
    var key = 0;
    if (_data!.list!.length > 0) {
      _data.list!.forEach((value) {
            key = _data.list!.indexOf(value);
            _data.list![key].abnormalRank =
                (areaAbnormalPrs['pageNum'] - 1) * areaAbnormalPrs['pageSize'] +
                    key +
                    1;
          });
    }
    areaAbnormalPrs['pageNum'] == 1
        ? areaRankList.value = _data.list ?? []
        : areaRankList.addAll(_data.list ?? []);
    if ((_data.total ?? 0) == 0) {
      isAreaEmpty.value = true;
      workScrViewKey.currentState?.isEmpty();
    } else if ((_data.pages ?? 0) <= (_data.pageNum ?? 0)) {
      isAreaLast.value = true;
      workScrViewKey.currentState?.isLast();
    }
    areaRankList.refresh();
  }

  /// 点位/区域
  setIsPoint(bool value) {
    isPoint.value = value;
    isPoint.refresh();
    scrollToTop();
    if (isPoint.isTrue == true &&
        (isPointEmpty.isTrue == true || isPointLast.isTrue == true)) {
      return;
    }
    if (isPoint.isTrue == false &&
        (isAreaEmpty.isTrue == true || isAreaLast.isTrue == true)) {
      return;
    }
    workScrViewKey.currentState?.initTrigger();
  }

  /// 跳转任务列表页
  onToTaskList(String status) async {
    await Get.toNamed('task/work_statistic/task_list', arguments: {
      'status': status,
      'inventoryId': statusCode.value,
      'organIdList': organIds.isEmpty
          ? organTree.map((item) => item['id']).join(',')
          : organIds.join(','),
      'createdAtStart': getStartTime(),
      'createdAtEnd': getEndTime(),
    });
  }

  /// 跳转筛选页
  toFilterPage() async {
    if (isDateType.isTrue == true) {
      await Get.toNamed('task/work_statistic/work_filter',
          arguments: {'isDate': true});
    } else {
      await Get.toNamed('task/work_statistic/work_filter',
          arguments: {'isDate': false});
    }
  }

  /// start ================================ 筛选页
  ///
  bool get isDate => isDateType.isTrue;
  getStartTime() {
    var startTime = '';
    final now = new DateTime.now();
    switch (findType.value) {
      case 'up_to_now':
        startTime = '';
        break;
      case 'seven_days':
        final pewSeven = now.subtract(new Duration(days: 7));
        startTime = DateFormat('yyyy-MM-dd').format(pewSeven);
        break;
      case 'month':
        final resMonth =
            month.isNotEmpty ? int.parse(month.value) : now.month - 1;
        final mothFirst = new DateTime(now.year, resMonth, 1);
        startTime = DateFormat('yyyy-MM-dd').format(mothFirst);
        break;
      case 'year':
        final resYear = year.isNotEmpty ? int.parse(year.value) : now.year;
        final currentYearFirst = new DateTime(resYear, 1, 1);
        startTime = DateFormat('yyyy-MM-dd').format(currentYearFirst);
        break;
      default:
    }
    return startTime;
  }

  getEndTime() {
    var endTime = '';
    final now = new DateTime.now();
    switch (findType.value) {
      case 'up_to_now':
        endTime = DateFormat('yyyy-MM-dd').format(now);
        break;
      case 'seven_days':
        endTime = DateFormat('yyyy-MM-dd').format(now);
        break;
      case 'month':
        final resMonth =
            month.isNotEmpty ? int.parse(month.value) : now.month - 1;
        final mothLast = new DateTime(now.year, resMonth + 1, 1)
            .subtract(new Duration(days: 1));
        endTime = DateFormat('yyyy-MM-dd').format(mothLast);
        break;
      case 'year':
        final resMonth = year.isNotEmpty ? int.parse(year.value) : now.year;
        final currentYearDay = new DateTime(resMonth, 12, 31);
        endTime = DateFormat('yyyy-MM-dd').format(currentYearDay);
        break;
      default:
    }
    return endTime;
  }

  getPeriod() {
    var resYear = year.value;
    var resMonth = month.value;
    var res = '';
    if (month.isNotEmpty && year.isEmpty) {
      var now = new DateTime.now();
      resYear = now.year.toString();
      res = resYear + '-' + resMonth;
    }
    if (month.isNotEmpty && year.isNotEmpty) {
      res = resYear + '-' + resMonth;
    }
    if (month.isEmpty && year.isNotEmpty) {
      res = resYear;
    }
    return month.isEmpty && year.isEmpty ? null : res;
  }

  getShowDateRange() {
    final start = getStartTime();
    return start != null && start != ''
        ? getStartTime() + ' 至 ' + getEndTime()
        : '截止 ' + getEndTime();
  }

  /// 选择月份
  onChooseMonth(DateTime value) {
    findTypePra.value = '';
    monthPra.value = DateFormat('MM').format(value);
  }

  /// 选择年份
  onChooseYear(DateTime value) {
    findTypePra.value = '';
    yearPra.value = DateFormat('yyyy').format(value);
  }

  /// 选择小区
  onChooseCommunity(List<CommunityPickerModel> res) {
    communityIdsPra.value = res.map((e) => e.id).toList();
    communityIName.value = res[0].name!;
    if (res.length > 1) {
      communityIName.value += '（和${res.length - 1}个小区）';
    }
  }

  /// 选择部门
  var organNames = ''.obs;
  onChooseOrganIds(ids) {
    organIdsPra.value = ids;
    organIdsPra.refresh();
    final names = organTree
        .where((item) => ids.contains(item['id']))
        .map((item) => item['name']);
    organNames.value = names.first ?? '';
    if (ids.length > 1) {
      final rest = ids.length - 1;
      organNames.value += '（和$rest个部门）';
    }
    organNames.refresh();
  }

  changeTimeValue(String code) {
    findTypePra.value = code;
    monthPra.value = '';
    yearPra.value = '';
  }

  back() {
    Get.back();
  }

  onResetInner() {
    findTypePra.value = 'up_to_now';
    communityIdsPra.value = [];
    communityIName.value = '';
    organIdsPra.value = [];
    monthPra.value = '';
    yearPra.value = '';
    organNames.value = '';
    submit();
  }

  submit() {
    findType.value = yearPra.isNotEmpty && monthPra.isEmpty
        ? 'year'
        : monthPra.isNotEmpty || (yearPra.isNotEmpty && monthPra.isNotEmpty)
            ? 'month'
            : findTypePra.value;
    communityId.value = communityIdsPra.join(',');
    organIds.value = organIdsPra;
    if (yearPra.isEmpty && monthPra.isNotEmpty) {
      var now = new DateTime.now();
      yearPra.value = now.year.toString();
    }
    month.value = monthPra.value;
    year.value = yearPra.value;
    Get.back();
    initStatisticRankList();
  }

  initStatisticRankList() {
    getTaskStatisticTotal();
    refreshRankList();
  }

  /// end ================================= 筛选页

  /// start ================================ 异常记录列表页
  var abnormalKeyword = ''.obs;
  var abnormalScrollViewListKey = GlobalKey<WisScrollViewState>();
  Map<String, dynamic> abnormalParams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  var abnormalList = <RecordAbnormalModel>[].obs;

  Future onSearchAbnormalList(String value) async {
    abnormalKeyword.value = value;
    abnormalParams['pageNum'] = 1;
    abnormalList.value = [];
    getAbnormalList(isLoad: false);
  }

  Future getAbnormalList({bool isLoad = true}) async {
    if (isLoad) abnormalParams['pageNum']++;
    var params = {
      ...abnormalParams,
      'isPage': true,
      'type': statusCode.value,
      'relationId': isPoint.isTrue == true ? relationId.value : null,
      'communityAreaId': isPoint.isTrue == true ? null : communityAreaId.value,
      'resultAbnormal': true,
      'startTime': getStartTime(),
      'endTime': getEndTime(),
      'relationName': abnormalKeyword.value,
    };
    final res = await TaskServiceImpl.instance!.getRecordList(params);
    final _data = res.data;
    abnormalParams['pageNum'] == 1
        ? abnormalList.value = _data?.list ?? []
        : abnormalList.addAll(_data?.list ?? []);
    if ((_data?.total ?? 0) == 0) {
      abnormalScrollViewListKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      abnormalScrollViewListKey.currentState?.isLast();
    }
    abnormalList.refresh();
  }

  resetAbnormalData() {
    abnormalParams = {
      'pageNum': 1,
      'pageSize': 20,
    };
    abnormalKeyword.value = '';
    abnormalList.value = [];
    abnormalList.refresh();
  }

  var relationId = ''.obs;
  var communityAreaId = ''.obs;
  onToAbnormalList(RecordAbnormalModel item) async {
    relationId.value = item.relationId!;
    communityAreaId.value = item.communityAreaId!;
    relationId.refresh();
    await Get.toNamed('task/work_statistic/record_list');
    resetAbnormalData();
  }

  /// end ================================ 异常记录列表页
  ///
  ///   ==================================== 日历相关 start
  var isDateType = true.obs;
  var isDateRankLast = true.obs;
  var isDateRankEmpty = true.obs;
  // 用于筛选/判断
  var focusedDay = DateFormat("yyyy-MM-dd").format(DateTime.now()).obs;
  // 用于页面显示
  var showFocusedDay = DateTime.now();
  var calendarAbnormalKeyword = ''.obs;
  var calendarAbnormalScrollViewListKey = GlobalKey<WisScrollViewState>();
  var calendarAbnormalIds = [].obs;
  Map<String, dynamic> calendarAbnormalParams = {
    'pageNum': 1,
    'pageSize': 20,
  };
  var calendarAbnormalList = <RecordAbnormalModel>[].obs;
  var currentMonth = DateFormat("yyyy-MM").format(DateTime.now()).obs;
  setIsDateType(bool value) {
    isDateType.value = value;
    scrollToTop();
    final hasRequestData = (isDateType.isTrue == true &&
            (isDateRankEmpty.isTrue == true ||
                isDateRankLast.isTrue == true)) ||
        (isDateType.isTrue == false &&
            (isPointEmpty.isTrue == true || isPointLast.isTrue == true));
    if (hasRequestData) {
      return;
    }
    if (isDateType.isTrue == false) {
      initStatisticRankList();
    }
  }

// 已请求标识：用于 日历/排名 切换时，保持数据状态
  var hasRequestCalendarData = false.obs;
  getRecordIdsByMonth({init = false}) async {
    final params = {
      'month': currentMonth.value,
      'type': statusCode.value,
    };
    final res = await TaskServiceImpl.instance!.getRecordIdsByMonth(params);

    calendarAbnormalIds.value = res.data ?? [];
    calendarAbnormalIds.refresh();
    hasRequestCalendarData.value = true;
    if (init == true) {
      getRecordListByCalendar(isLoad: false);
    }
  }

  getRecordListByCalendar({bool isLoad = true}) async {
    if (isLoad) calendarAbnormalParams['pageNum']++;
    final ids = calendarAbnormalIds
        .where((e) => e.date == focusedDay.value)
        .map((e) => e.list)
        .toList();
    if (ids.isEmpty) {
      calendarAbnormalList.value = [];
      calendarAbnormalList.refresh();
      calendarAbnormalScrollViewListKey.currentState?.isEmpty();
      return;
    }
    var params = {
      'ids': ids[0].join(','),
      'isPage': true,
      ...calendarAbnormalParams,
    };
    WLoadingUtil.show();
    final res = await TaskServiceImpl.instance!.getRecordList(params);
    WLoadingUtil.hide();
    final _data = res.data;
    calendarAbnormalParams['pageNum'] == 1
        ? calendarAbnormalList.value = _data?.list ?? []
        : calendarAbnormalList.addAll(_data?.list ?? []);
    if ((_data?.total ?? 0) == 0) {
      calendarAbnormalScrollViewListKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0)) {
      calendarAbnormalScrollViewListKey.currentState?.isLast();
    }
    calendarAbnormalList.refresh();
  }

  selectedDay(day) {
    focusedDay.value = DateFormat("yyyy-MM-dd").format(day);
    focusedDay.refresh();
    showFocusedDay = day;
    getRecordListByCalendar(isLoad: false);
  }

  onMonthChange(day) {
    currentMonth.value = DateFormat("yyyy-MM").format(day);
    getRecordIdsByMonth(init: false);
  }

  isAbnormalDay(day) {
    final date = DateFormat("yyyy-MM-dd").format(day);
    final ids =
        calendarAbnormalIds.where((e) => e.date == date).map((e) => e.list);
    return ids.length > 0;
  }

  isSelectDay(day) {
    final date = DateFormat("yyyy-MM-dd").format(day);
    return date == focusedDay.value;
  }

  CalendarFormat calendarFormat = CalendarFormat.week;
  changeCalendarFormat(format) {
    calendarFormat = format;
  }

  ///   ==================================== 日历相关 end

  /// 跳转点位详情，并进行异常处理
  onToAbnormalDetail(RecordAbnormalModel item) async {
    await Get.toNamed('task/point_form', arguments: {
      'id': item.exPlatformId,
      'relationIds': item.relationId,
      'detailData': TaskDetailModel.fromJson({
        'id': item.exPlatformId,
      }),
      'isDealAbnormalSolve':
          item.resultAbnormal == true && item.status == 'untreated',
      'routeItem': TaskOperationNodeListItemList.fromJson({
        'nodeData': {'communityName': item.communityName},
        'relationName': item.relationName
      }),
      'platformId': item.excutivePlatformLinkId,
      'cid': item.excutivePlatformLinkId,
      'isHistory': true,
    });
    bool? refreshFlag = WisStorageUtil.get(key: 'abnormal_list_refresh');
    if (refreshFlag == true) {
      getRecordListByCalendar(isLoad: false);
      WisStorageUtil.set(key: 'abnormal_list_refresh', data: false);
    }
  }
}
