/*
 * @Author       : WuWei
 * @LastEditors: ChenYaJin
 * @Date         : 2021-04-27 15:50:32
 * @LastEditTime: 2023-08-16 10:03:02
 * @FilePath     : /wisdom-huiguanjia-app/task_package/lib/src/view_models/statistic_store.dart
 * @Description  : 任务统计逻辑
 */
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:intl/intl.dart';
import 'package:get/get.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../../src/impl/task_service_impl.dart';
import '../../src/models/task_inventory_stat_model.dart';
import '../../src/models/task_statistic_model.dart';
import '../../src/pages/statistic/index.dart';
import '../models/task_emp_infos.dart';
import '../models/task_organ_stat.dart';

part 'statistic_store.g.dart';

class StatisticStore = _StatisticStore with _$StatisticStore, ChangeNotifier;

abstract class _StatisticStore with Store {
  ///上下文（请勿修改）

  final BuildContext context1;

  ///路由参数（请勿修改）
  StatisticPageArguments get arguments =>
      StatisticPageArguments.fromRouteArguments(context1);

  _StatisticStore(this.context1) {
    ///可在此处理进入页面前的操作，比如响应路由的传参进行赋值。
  }

  /// 我的任务
  final mineScrViewKey = GlobalKey<WisScrollViewState>();

  /// 我的创建
  final departScrViewKey = GlobalKey<WisScrollViewState>();

  /// 我的抄送
  final peopleScrViewKey = GlobalKey<WisScrollViewState>();

  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();
  EmployeesInfoModel? get currentEmployeesInfo => authGlobalStore.info;

  /// 我的任务
  @observable
  bool isMyTask = true;
  @action
  Future<void> onSetMyTask(bool flag) async {
    isMyTask = flag;
    onInitData();
  }

  @observable
  bool isToday = false;
  @action
  Future<void> onSetToday() async {
    isToday = !isToday;
    isYesterday = false;
    if (isToday == false) {
      onInitTime();
    }
    onInitData();
  }

  @observable
  bool isYesterday = false;
  @action
  Future<void> onSetYesterday() async {
    isYesterday = !isYesterday;
    isToday = false;
    if (isYesterday == false) {
      onInitTime();
    }
    onInitData();
  }

  /// 顶部tab 当前位置
  @observable
  int tabIndex = 0;
  @action
  Future<void> onSetTabIndex(index) async {
    tabIndex = index;
    isStatShow = false;
    allParams = {
      'createdAtStart': '',
      'createdAtEnd': '',
      'operatorId': '',
      'organIdList': '',
    };
    onInitTime();
    if (index == 0) {
      onInitData();
    }
    if (index == 1) {
      onGetDepartList();
    }
    if (index == 2) {
      onGetEmployeeList();
    }
  }

  /// 选择日期
  @observable
  String? createdAtStart;
  @action
  onPickBillStartDate(date) {
    createdAtStart = date;
  }

  @observable
  String? createdAtEnd;
  @action
  onPickBillEndDate(date) {
    createdAtEnd = date;
  }

  getDateRange() {
    final start = allParams['createdAtStart'] ?? '';
    final end = allParams['createdAtEnd'] ?? '当前';
    final range = (start == '') ? '截止 ' + end : start + ' 至 ' + end;
    return range;
  }

  /// ============================================= 筛选页 start
  /// 跳转筛选
  onSetFilterShow() async {
    Get.toNamed('task/statistic/filter', arguments: {
      'createdAtStart': allParams['createdAtStart'],
      'createdAtEnd': allParams['createdAtEnd'],
    })!
        .then((res) {
      //插入新发布的通知
      if (res is Map) {
        allParams['createdAtStart'] = res['createdAtStart'];
        allParams['createdAtEnd'] = res['createdAtEnd'];
        onInitData();
      }
    });
  }

  /// 筛选重置
  onResetInner() {
    Get.back(result: {
      'createdAtStart': null,
      'createdAtEnd': null,
    });
  }

  /// 确认筛选
  submit() {
    Get.back(result: {
      'createdAtStart': createdAtStart,
      'createdAtEnd': createdAtEnd,
    });
  }

  onInit() {
    createdAtStart = Get.arguments['createdAtStart'];
    createdAtEnd = Get.arguments['createdAtEnd'];
  }

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

  /// 查看统计（选择部门、人员之后）
  void toTaskStatistic() {
    switch (tabIndex) {
      case 1:
        toDepartStat();
        break;
      case 2:
        toPeopleStat();
        break;
      default:
    }
  }

  /// isStatShow:true 显示统计；isStatShow:false;显示人员或部门选择
  /// 查看人员统计
  @observable
  bool isStatShow = false;
  @action
  void toPeopleStat() {
    isStatShow = !isStatShow;
    onInitData();
  }

  /// 查看部门统计
  @action
  void toDepartStat() {
    allParams['operatorId'] = '';
    allParams['organIdList'] = onFilterSelectDepart().join(',');
    isStatShow = !isStatShow;
    onInitData();
  }

  ///最近九十天
  onInitTime() {
    DateFormat outputFormat = DateFormat("yyyy-MM-dd");
    var now = DateTime.now();
    allParams['createdAtEnd'] = outputFormat.format(now);
    var ninetyDaysAgo = now.subtract(new Duration(days: 90));
    allParams['createdAtStart'] = outputFormat.format(ninetyDaysAgo);
  }

  /// 初始化
  Future onInitData() async {
    await Future.wait([onGetAllStat(), onGetListStat()]);
  }

  /// 跳转任务列表页
  onToTaskList({String status = '', String inventoryId = ''}) async {
    await Navigator.pushNamed(
      context1,
      'task/work_statistic/task_list',
      arguments: {
        'status': status,
        'inventoryId': inventoryId,
        'createdAtStart': allParams['createdAtStart'],
        'createdAtEnd': allParams['createdAtEnd'],
        'type': isMyTask ? 'to_me' : 'transfer'
      },
    );
  }

  @observable
  var allParams = {
    'createdAtStart': '',
    'createdAtEnd': '',
    'operatorId': '',
    'organIdList': '',
  };

  setDateRange() {
    var params = {};
    DateFormat outputFormat = DateFormat("yyyy-MM-dd");
    if (tabIndex == 0) {
      params['operatorId'] = isMyTask ? currentEmployeesInfo!.id! : '';
      params['mailTo'] = isMyTask ? '' : currentEmployeesInfo!.id!;
      params['createdAtStart'] = isToday
          ? outputFormat.format(DateTime.now())
          : isYesterday
              ? outputFormat.format(DateTime.now().subtract(Duration(days: 1)))
              : allParams['createdAtStart'];
      params['createdAtEnd'] = isToday
          ? outputFormat.format(DateTime.now())
          : isYesterday
              ? outputFormat.format(DateTime.now().subtract(Duration(days: 1)))
              : allParams['createdAtEnd'];
      allParams = {...allParams, ...params};
    }
  }

  /// 全部任务统计
  @observable
  TaskStatisticModel? allStat;
  Future onGetAllStat() async {
    setDateRange();
    final res = await TaskServiceImpl.instance!.getTaskStatictis(allParams);
    allStat = (res.data ?? {}) as TaskStatisticModel?;
  }

  /// 任务类型统计
  @observable
  ObservableList<TaskInventoryStatModel> statList = ObservableList.of([]);
  Future onGetListStat() async {
    setDateRange();
    final res = await TaskServiceImpl.instance!.getTaskInventoryStat(allParams);
    statList = ObservableList.of(res.data ?? []);
  }

  /// 部门名称
  @observable
  String? organName;
  @action
  onSearchDepart(v) {
    organName = v;
    onGetDepartList();
  }

  /// 当前角色管理部门
  @observable
  ObservableList<TaskOrganStat> departmentList = ObservableList.of([]);
  @action
  Future onGetDepartList() async {
    WLoadingUtil.show();
    // if (!isListFresh) return;
    try {
      final res = await TaskServiceImpl.instance!
          .getEployeeOransStat({'organName': organName});
      if (res.data != null && res.data!.isNotEmpty) {
        res.data!.forEach((element) {
          element.isSelect = false;
        });
        departmentList = ObservableList.of(res.data ?? []);
      } else {
        departmentList = ObservableList.of([]);
      }
    } finally {
      WLoadingUtil.hide();
    }
  }

  /// 选择部门
  @action
  onSelectOrganItem(index) {
    List<TaskOrganStat> list = [];
    for (int i = 0; i < departmentList.length; i++) {
      if (index == i) {
        departmentList[i].isSelect =
            departmentList[i].isSelect == true ? false : true;
      }
      list.add(departmentList[i]);
    }

    departmentList = ObservableList.of([]);
    departmentList = ObservableList.of(list);
  }

  /// 选择查看人员
  @action
  onSelectPeopleItem(index) {
    List<TaskEmpInfos> list = [];
    for (var i = 0; i < employeeList.length; i++) {
      if (index == i) {
        employeeList[i].isSelect = true;
      } else {
        employeeList[i].isSelect = false;
      }
      list.add(employeeList[i]);
    }
    employeeList = ObservableList.of([]);
    employeeList = ObservableList.of(list);
    allParams['operatorId'] = employeeList[index].id ?? '';
  }

  ///是否已经选中？
  ///判断唯一值
  bool isSelected(v) {
    return departmentList.indexWhere((e) => e.selectUnique == v.selectUnique) !=
        -1;
  }

  /// 返回选中部门ids
  List onFilterSelectDepart() {
    List arr = departmentList
        .where((item) => item.isSelect == true ? true : false)
        .toList();
    List departIds = [];
    arr.forEach((element) {
      departIds.add(element.id);
    });
    return departIds;
  }

  /// 角色管理的人员名称
  @observable
  String? employeeName;
  @action
  onSearchEmployee(v) {
    employeeName = v;
    employeeList = ObservableList.of([]);
    onGetEmployeeList();
  }

  ///当前角色管理的人员
  @observable
  ObservableList<TaskEmpInfos> employeeList = ObservableList.of([]);
  @action
  Future onGetEmployeeList() async {
    WLoadingUtil.show();
    try {
      final res = await TaskServiceImpl.instance!
          .getEmployeeEmpInfos({'employeeName': employeeName});
      if (res.data?.length != null && res.data!.length > 0) {
        res.data!.forEach((element) {
          element.isSelect = false;
        });
      }
      employeeList = ObservableList.of(res.data ?? []);
    } finally {
      WLoadingUtil.hide();
    }
  }
}
