/*
 * @Author       : WuWei
 * @LastEditors: wuwei
 * @Date         : 2021-04-27 09:49:15
 * @LastEditTime: 2023-12-14 15:24:52
 * @FilePath: /wisdom-huiguanjia-app/task_package/lib/src/view_models/index_store.dart
 * @Description  : 任务管理列表逻辑
 */
import 'dart:convert';

import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:task_package/src/impl/qrcode_impl.dart';
import '../../src/impl/task_service_impl.dart';
import '../../src/models/task_item_model.dart';
import '../../src/pages/index/index.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
part 'index_store.g.dart';

class IndexStore = _IndexStore with _$IndexStore, ChangeNotifier;

abstract class _IndexStore with Store {
  ///上下文（请勿修改）
  final BuildContext context1;

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

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

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

  final scrollKey = GlobalKey();

  /// tab 控制器
  TabController? tabController;

  /// NestedScrollView 控制器
  ScrollController outerController = new ScrollController();

  Map get args =>
      ModalRoute.of(context1)!.settings.arguments as Map<String, dynamic>? ??
      {};

  var statusList = [
    {'code': '', 'name': '全部'},
    {'code': 'no_open', 'name': '未开始'},
    {'code': 'doing', 'name': '进行中'},
    {'code': 'finished', 'name': '已完成'},
    {'code': 'outTime', 'name': '超时'},
    {'code': 'overdue', 'name': '逾期'},
  ];
  var statusChange = {
    'isNoOpen': 'no_open',
    'isDoing': 'doing',
    'isFinished': 'finished',
    'isOverdue': 'overdue',
    'isOutTime': 'outTime',
  };

  /// 状态列表
  @observable
  ObservableMap<String, bool> taskStatus = ObservableMap.of({
    'isFinished': false,
    'isNoOpen': false,
    'isDoing': false,
    'isOutTime': false,
    'isOverdue': false,
  });

  @observable
  bool showToTopBtn = false;

  /// 滚动位置
  double? scrollHeight;
  onInit() async {
    await onGetNoticeList();
    await onGetTaskListItem();
    outerController.addListener(() {
      scrollHeight = outerController.offset;
    });
    if (args['isTimeOut'] == true) {
      chooseStatus('isOutTime');
    } else if (args['status'] != null) {
      chooseStatus(args['status']);
    } else if (args['type'] != null) {
      onChooseListItem([args['type']]);
    } else {
      onInitList(tabIndex);
    }
  }

  /// 获取任务类型
  @observable
  List taskItemList = [];
  @action
  Future onGetTaskListItem() async {
    var res =
        await TaskServiceImpl.instance!.getInventoryList({"preset": null});
    taskItemList = jsonDecode(jsonEncode(res.data)) ?? [];
  }

  @observable
  List checkListItem = [];
  // 筛选任务类型
  onChooseListItem(data) async {
    checkListItem = data;
    onInitFreshList(tabIndex);
  }

  /// 顶部tab 当前位置
  @observable
  int tabIndex = 0;
  @action
  onSetTabIndex(index) {
    FocusScope.of(context1).requestFocus(FocusNode());
    tabController?.index = index;
    tabIndex = index;
    onInitFreshList(index);
  }

  /// 筛选状态
  @action
  onSelectStatus(item, status, index) {
    item[status] = item[status] ? false : true;
    FocusScope.of(context1).requestFocus(FocusNode());
    onInitFreshList(index);
  }

  @observable
  bool isShowButtonMask = false;
  @action
  onSetShowButtonMask(flag) {
    isShowButtonMask = flag;
  }

  /// 筛选时间
  @observable
  String sortCreatedAt = 'desc';

  @action
  onTaskSortByTime() {
    sortCreatedAt = sortCreatedAt == 'desc' ? 'asc' : 'desc';
    onInitFreshList(tabIndex);
  }

  /// 是否数据最后一页
  @observable
  bool isLast = false;

  /// 是否加载中
  @observable
  bool isLoading = false;

  /// 是否数据为空
  @observable
  bool isEmpty = false;

  /// 滚动通知时间
  handleScrollEvent(ScrollNotification scroll) {
    if ((scroll.metrics.pixels / scroll.metrics.maxScrollExtent) > 0.7) {
      if (!isLast && !isLoading) {
        isLoading = true;
        onLoadMore();
      }
    }
  }

  /// 滚动到tab位置
  scrollToTop() {
    if (scrollHeight != null && scrollHeight! > 165) {
      outerController.animateTo(145.pt,
          duration: Duration(milliseconds: 200), curve: Curves.ease);
    }
  }

  onLoadMore() async {
    switch (tabIndex) {
      case 0:
        await onGetMyTaskList();
        break;
      case 1:
        await onGetMyAssignList();
        break;
      case 2:
        await onGetMyCCList();
        break;
      case 3:
        await onGetMyOrganList();
        break;
      case 4:
        await onGetTransferList();
        break;
      case 5:
        await onGetOtherList();
        break;
    }
  }

  /// 重置
  onReset() {
    taskStatuString = '';
    FocusScope.of(context1).requestFocus(FocusNode());
    taskTitle = '';
    taskStatus.forEach((key, value) {
      taskStatus[key] = false;
    });
    checkListItem = [];
    sortCreatedAt = 'desc';
    onInitFreshList(tabIndex);
  }

  /// 初始化任务列表
  onInitList(index) async {
    switch (index) {
      case 0:
        myTaskPrs['pageNum'] = 1;
        myTaskList = ObservableList.of([]);
        await onGetMyTaskList();
        scrollToTop();
        break;
      case 1:
        oprTaskPrs['pageNum'] = 1;
        taskAssignList = ObservableList.of([]);
        await onGetMyAssignList();
        scrollToTop();
        break;
      case 2:
        copyTaskPrs['pageNum'] = 1;
        taskCCList = ObservableList.of([]);
        await onGetMyCCList();
        scrollToTop();
        break;
      case 3:
        departTaskPrs['pageNum'] = 1;
        taskOrganList = ObservableList.of([]);
        await onGetMyOrganList();
        scrollToTop();
        break;
      case 4:
        transTaskPrs['pageNum'] = 1;
        taskTransferList = ObservableList.of([]);
        await onGetTransferList();
        scrollToTop();
        break;
      case 5:
        otherTaskPrs['pageNum'] = 1;
        taskOrganList = ObservableList.of([]);
        await onGetOtherList();
        scrollToTop();
        break;
      default:
    }
  }

  /// 跳转添加任务
  toTaskAdd() async {
    await Navigator.pushNamed(context1, 'task/edit', arguments: {
      'id': null,
      'isChildAdd': false,
    });
    onSetTabIndex(tabIndex);
  }

  /// 跳转详情
  toTaskDetail(id, isChild) async {
    await Navigator.pushNamed(
      context1,
      'task/detail',
      arguments: {
        'id': id,
        'isChild': isChild,
      },
    );
    bool? refresh = WisStorageUtil.get(key: 'isTaskListRefresh') ?? false;
    if (refresh) {
      await WisStorageUtil.set(key: 'isTaskListRefresh', data: false);
      onSetTabIndex(tabIndex);
    }
  }

  // 任务大厅消息
  @observable
  ObservableList<TaskItemModel> noticeList = ObservableList.of([]);
  @action
  Future onGetNoticeList() async {
    var res = await QrcodeServiceImpl.instance!.getTaskList({
      'pageNum': 1,
      'pageSize': 3,
      'type': 'wait_receive',
    });
    final _data = res.data;
    noticeList = ObservableList.of(_data?.list ?? []);
  }

  /// 跳转任务大厅
  toTaskHallList() async {
    await Navigator.pushNamed(context1, 'task/hall');
    onSetTabIndex(tabIndex);
  }

  @observable
  String taskTitle = '';
  @action
  Future onSearchTaskTitles(title) async {
    FocusScope.of(context1).requestFocus(FocusNode());
    taskTitle = title;
    onInitFreshList(tabIndex);
  }

  String type = 'to_me';
  onInitFreshList(tabIndex) async {
    isLast = false;
    isEmpty = false;
    scrollToTop();
    switch (tabIndex) {
      case 0:
        myTaskPrs['pageNum'] = 1;
        myTaskList = ObservableList.of([]);
        type = 'to_me';
        await onGetMyTaskList();
        break;
      case 1:
        oprTaskPrs['pageNum'] = 1;
        taskAssignList = ObservableList.of([]);
        type = 'create';
        await onGetMyAssignList();
        break;
      case 2:
        copyTaskPrs['pageNum'] = 1;
        taskCCList = ObservableList.of([]);
        type = 'transfer';
        await onGetMyCCList();
        break;
      case 3:
        departTaskPrs['pageNum'] = 1;
        taskOrganList = ObservableList.of([]);
        type = 'organ';
        await onGetMyOrganList();
        break;
      case 4:
        transTaskPrs['pageNum'] = 1;
        taskTransferList = ObservableList.of([]);
        type = 'me_transfer';
        await onGetTransferList();
        break;
      case 5:
        otherTaskPrs['pageNum'] = 1;
        taskOrganList = ObservableList.of([]);
        type = 'to_others';
        await onGetOtherList();
        break;
      default:
        break;
    }
  }

  Map<String, dynamic> myTaskPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };

  Map<String, dynamic> oprTaskPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };

  Map<String, dynamic> copyTaskPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };

  Map<String, dynamic> departTaskPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };

  Map<String, dynamic> transTaskPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };

  Map<String, dynamic> otherTaskPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };

  @observable
  String taskStatuString = '';

  @observable
  String filterStatusCode = ''; // 单选状态
  @action
  setStatus(code) {
    filterStatusCode = code;
  }

  @action
  filterStatus(String code) {
    setStatus(code);
    onInitFreshList(tabIndex);
  }

  /// 选择任务状态
  @action
  chooseStatus(status) {
    // taskStatuString = status;
    // taskStatus.forEach((key, value) {
    //   if (key == status) {
    //     taskStatus[key] = true;
    //   } else {
    //     taskStatus[key] = false;
    //   }
    // });
    final matchCode = statusChange[status];
    setStatus(matchCode);
    onInitFreshList(tabIndex);
  }

  getStatusValue() {
    return filterStatusCode.isNotEmpty && filterStatusCode != 'outTime'
        ? filterStatusCode
        : null;
  }

  getTimeOut() {
    return filterStatusCode == 'outTime';
  }

  /// 状态-多选
  getStatussValue() {
    final tempList = [];
    if (taskStatus['isNoOpen']!) {
      tempList.add('no_open');
    }
    if (taskStatus['isDoing']!) {
      tempList.add('doing');
    }
    if (taskStatus['isFinished']!) {
      tempList.add('finished');
    }
    if (taskStatus['isOverdue']!) {
      tempList.add('overdue');
    }
    return tempList.length > 0 ? tempList.join(',') : null;
  }

  /// start=========================================  作业统计来源列表 ===
  final statisticScrollViewListKey = GlobalKey<WisScrollViewState>();
  late Map statisticTaskPrs = {
    'pageNum': 1,
    'pageSize': 20,
  };

  @observable
  String statisticTaskTitle = '';
  @action
  Future onSearchStatisticTaskTitles(title) async {
    FocusScope.of(context1).requestFocus(FocusNode());
    statisticTaskTitle = title;
    statisticTaskPrs['pageNum'] = 1;
    statisticTaskList = ObservableList.of([]);
    initStatisticSourceList(isLoad: false);
  }

  /// 统计来源列表
  @observable
  ObservableList<TaskItemModel> statisticTaskList = ObservableList.of([]);
  @action
  Future initStatisticSourceList({bool isLoad = true}) async {
    if (isLoad) statisticTaskPrs['pageNum']++;
    try {
      final res = await QrcodeServiceImpl.instance!.getTaskList({
        ...statisticTaskPrs,
        'statuss': args['status'] == '' || args['status'] == 'outTime'
            ? 'no_open,doing,finished,overdue'
            : args['status'],
        'taskTimeout': args['status'] == 'outTime',
        'title': statisticTaskTitle,
        'createdAtStart': args['createdAtStart'] ?? null,
        'createdAtEnd': args['createdAtEnd'] ?? null,
        'inventoryIds': args['inventoryId'],
        "organIdList": args['organIdList'],
        'type': args['type']
      });
      final _data = res.data;
      statisticTaskPrs['pageNum'] == 1
          ? statisticTaskList = ObservableList.of(_data?.list ?? [])
          : statisticTaskList.addAll(ObservableList.of(_data!.list!));
      isLoading = false;
      if ((_data?.total ?? 0) == 0) {
        isEmpty = true;
        statisticScrollViewListKey.currentState?.isEmpty();
      } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
          _data!.total! > 0) {
        isLast = true;
        statisticScrollViewListKey.currentState?.isLast();
      }
    } finally {
      isLoading = false;
      WLoadingUtil.hide();
    }
  }

  /// end=========================================  作业统计来源列表 ===

  /// 我的任务列表
  @observable
  ObservableList<TaskItemModel> myTaskList = ObservableList.of([]);
  @action
  Future onGetMyTaskList() async {
    // WLoadingUtil.show(bg: false);
    try {
      final res = await QrcodeServiceImpl.instance!.getTaskList({
        ...myTaskPrs,
        'type': type,
        'status': getStatusValue(),
        'statuss': getStatussValue(),
        'taskTimeout': getTimeOut(),
        'title': taskTitle,
        'sortCreatedAt': sortCreatedAt,
        'inventoryIds': checkListItem.length > 0
            ? checkListItem.map((item) => item).join(',')
            : null,
      });
      final _data = res.data;
      myTaskPrs['pageNum'] == 1
          ? myTaskList = ObservableList.of(_data?.list ?? [])
          : myTaskList.addAll(ObservableList.of(_data!.list!));
      isLoading = false;
      if ((_data?.total ?? 0) == 0) {
        isEmpty = true;
      } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
          _data!.total! > 0) {
        isLast = true;
      } else {
        myTaskPrs['pageNum']++;
      }
    } finally {
      isLoading = false;
      WLoadingUtil.hide();
    }
  }

  /// 我的创建列表
  @observable
  ObservableList<TaskItemModel> taskAssignList = ObservableList.of([]);
  @action
  Future onGetMyAssignList() async {
    try {
      final res = await QrcodeServiceImpl.instance!.getTaskList({
        ...oprTaskPrs,
        'type': type,
        'status': getStatusValue(),
        'statuss': getStatussValue(),
        'taskTimeout': getTimeOut(),
        'title': taskTitle,
        'sortCreatedAt': sortCreatedAt,
        'inventoryIds': checkListItem.length > 0
            ? checkListItem.map((item) => item).join(',')
            : null,
      });
      final _data = res.data;
      oprTaskPrs['pageNum'] == 1
          ? taskAssignList = ObservableList.of(_data?.list ?? [])
          : taskAssignList.addAll(ObservableList.of(_data!.list!));
      isLoading = false;
      if ((_data?.total ?? 0) == 0) {
        isEmpty = true;
      } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
          _data!.total! > 0) {
        isLast = true;
      } else {
        oprTaskPrs['pageNum']++;
      }
    } finally {
      isLoading = false;
      WLoadingUtil.hide();
    }
  }

  /// 我的抄送列表
  @observable
  ObservableList<TaskItemModel> taskCCList = ObservableList.of([]);
  @action
  Future onGetMyCCList() async {
    // WLoadingUtil.show();
    try {
      final res = await QrcodeServiceImpl.instance!.getTaskList({
        ...copyTaskPrs,
        'type': type,
        'status': getStatusValue(),
        'statuss': getStatussValue(),
        'taskTimeout': getTimeOut(),
        'title': taskTitle,
        'sortCreatedAt': sortCreatedAt,
        'inventoryIds': checkListItem.length > 0
            ? checkListItem.map((item) => item).join(',')
            : null,
      });
      final _data = res.data;
      copyTaskPrs['pageNum'] == 1
          ? taskCCList = ObservableList.of(_data?.list ?? [])
          : taskCCList.addAll(ObservableList.of(_data!.list!));
      isLoading = false;
      if ((_data?.total ?? 0) == 0) {
        isEmpty = true;
      } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
          _data!.total! > 0) {
        isLast = true;
      } else {
        copyTaskPrs['pageNum']++;
      }
    } finally {
      isLoading = false;
      WLoadingUtil.hide();
    }
  }

  /// 本部门列表
  @observable
  ObservableList<TaskItemModel> taskOrganList = ObservableList.of([]);
  @action
  Future onGetMyOrganList() async {
    try {
      final res = await QrcodeServiceImpl.instance!.getTaskList({
        ...departTaskPrs,
        'type': type,
        'status': getStatusValue(),
        'statuss': getStatussValue(),
        'taskTimeout': getTimeOut(),
        'title': taskTitle,
        'sortCreatedAt': sortCreatedAt,
        'inventoryIds': checkListItem.length > 0
            ? checkListItem.map((item) => item).join(',')
            : null,
      });
      final _data = res.data;
      departTaskPrs['pageNum'] == 1
          ? taskOrganList = ObservableList.of(_data?.list ?? [])
          : taskOrganList.addAll(ObservableList.of(_data!.list!));
      isLoading = false;
      if ((_data?.total ?? 0) == 0) {
        isEmpty = true;
      } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
          _data!.total! > 0) {
        isLast = true;
      } else {
        departTaskPrs['pageNum']++;
      }
    } finally {
      isLoading = false;
      WLoadingUtil.hide();
    }
  }

  /// 我转派的
  @observable
  ObservableList<TaskItemModel> taskTransferList = ObservableList.of([]);
  @action
  Future onGetTransferList() async {
    try {
      final res = await QrcodeServiceImpl.instance!.getTaskList({
        ...transTaskPrs,
        'type': type,
        'status': getStatusValue(),
        'statuss': getStatussValue(),
        'taskTimeout': getTimeOut(),
        'title': taskTitle,
        'sortCreatedAt': sortCreatedAt,
        'inventoryIds': checkListItem.length > 0
            ? checkListItem.map((item) => item).join(',')
            : null,
      });
      final _data = res.data;
      transTaskPrs['pageNum'] == 1
          ? taskTransferList = ObservableList.of(_data?.list ?? [])
          : taskTransferList.addAll(ObservableList.of(_data!.list!));
      isLoading = false;
      if ((_data?.total ?? 0) == 0) {
        isEmpty = true;
      } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
          _data!.total! > 0) {
        isLast = true;
      } else {
        transTaskPrs['pageNum']++;
      }
    } finally {
      isLoading = false;
      WLoadingUtil.hide();
    }
  }

  /// 我指派的
  @observable
  ObservableList<TaskItemModel> taskOtherList = ObservableList.of([]);
  @action
  Future onGetOtherList() async {
    try {
      final res = await QrcodeServiceImpl.instance!.getTaskList({
        ...otherTaskPrs,
        'type': type,
        'status': getStatusValue(),
        'statuss': getStatussValue(),
        'taskTimeout': getTimeOut(),
        'title': taskTitle,
        'sortCreatedAt': sortCreatedAt,
        'inventoryIds': checkListItem.length > 0
            ? checkListItem.map((item) => item).join(',')
            : null,
      });
      final _data = res.data;
      otherTaskPrs['pageNum'] == 1
          ? taskOtherList = ObservableList.of(_data?.list ?? [])
          : taskOtherList.addAll(ObservableList.of(_data!.list!));
      isLoading = false;
      if ((_data?.total ?? 0) == 0) {
        isEmpty = true;
      } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
          _data!.total! > 0) {
        isLast = true;
      } else {
        otherTaskPrs['pageNum']++;
      }
    } finally {
      isLoading = false;
      WLoadingUtil.hide();
    }
  }

  /// 跳转筛选页面
  var indexList = {
    'to_me': 0,
    'create': 1,
    'transfer': 2,
    'organ': 3,
    'me_transfer': 4,
    'to_others': 5,
  };

  String? inventoryfirstId;
  toFilterPage() async {
    var res = await Navigator.pushNamed(
      context1,
      'task/filter',
      arguments: {
        'code': filterStatusCode,
        'type': type,
        'inventoryIds': checkListItem.length > 0 ? checkListItem : [],
        'inventoryfirstId': inventoryfirstId,
      },
    );
    if (res != null && res is Map) {
      final isRefresh = res['isRefresh'];
      if (isRefresh != false) {
        type = res['type'];
        filterStatusCode = res['code'];
        sortCreatedAt = res['sortCreatedAt'];
        checkListItem = res['inventoryIds'] != null ? res['inventoryIds'] : [];
        inventoryfirstId = res['inventoryfirstId'];
        final index = indexList[type];
        onSetTabIndex(index);
      }
    }
  }
}
