// ignore_for_file: unnecessary_set_literal

/*
 * @Author: XianKaiQun
 * @Date: 2020-07-21 11:02:34
 * @LastEditors: wuwei
 * @LastEditTime: 2024-01-05 17:03:38
 * @Description: 任务详情逻辑
 */

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
// import 'package:geolocator/geolocator.dart';
import 'package:mobx/mobx.dart';
import 'package:task_package/src/components/input_dialog.dart';
import 'package:task_package/src/impl/qrcode_impl.dart';
import 'package:task_package/src/models/task_operation_node_list.dart';
import 'package:task_package/src/view_models/location_util_store.dart';
import '../../src/impl/auth.dart';
import '../../src/impl/task_service_impl.dart';
import '../../src/models/task_child.dart';
import '../../src/models/task_detail.dart';
import '../../src/models/task_state.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:image/image.dart' as ui;
import 'package:intl/intl.dart';
import "package:collection/collection.dart";
part 'detail_store.g.dart';

class PrivateTaskDetailStore = _PrivateTaskDetailStore
    with _$PrivateTaskDetailStore;

abstract class _PrivateTaskDetailStore with Store, ChangeNotifier {
  ///上下文（请勿修改）
  final BuildContext context1;
  final appGlobalStore = GetIt.I.get<AppGlobalStore>();
  late Map args;

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

  final detailScrollviewKey = GlobalKey<WisScrollViewState>();
  StreamSubscription<Map<String, Object>>? locationListener;

  //当前员工的信息
  EmployeesInfoModel? get userInfo => authGlobalStore.info;

  int tabIndex = 0;

  Map<int, dynamic> multiNumList = {};

  ///切换Tab页面，设置tab索引
  void setTabIndex(index) {
    tabIndex = index;
    notifyListeners();
  }

  /// 销毁
  void destroy() {
    var locationStore = LocationUtilStore(this.context1);

    ///移除定位监听
    if (null != locationListener) {
      locationListener!.cancel();
    }

    ///销毁定位
    locationStore.destroy();
  }

  onInitLocation() async {
    // var locationStore = LocationUtilStore(context1);
    // 初始化定位
    // locationStore.startLocation();

    ///注册定位结果监听
    // locationListener = locationStore.locationPlugin
    //     .onLocationChanged()
    //     .listen((Map<String, Object> result) async {
    //   if (result['longitude'] != null) {
    //     locationStore.myLocation = WisLocationInfo.fromJson(result);
    //     // 逆地理获取地址
    //     // await locationStore.onGetLocateName();

    //     /// 设置地址
    //     onSetCurrentAddr(locationStore.addr);
    //     onSetCurrentLocation(locationStore.myLocation);
    //   }
    //   if (result['errorCode'] == 12) {
    //     WLoadingUtil.hide();
    //     locationStore.showLocationNoOpenDialog();
    //   }
    //   if (result['errorCode'] == 2) {
    //     WLoadingUtil.hide();
    //     destroy();
    //     locationStore.showErrorLocationDialog();
    //   }
    // });
  }

  final formKey = GlobalKey<FormState>();

  /// 详情id
  String? get id => args['id'];
  bool? get isChild => args['isChild'];
  bool get isMulti => args['isMulti'] ?? false;

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

  TaskDetailModel? data;

  late List<TaskStateModel>? status;
  TaskStateModel? firstStatus;

  @observable
  String entryType = 'default';

  @action
  void onSetEntryType(data) {
    entryType = data;
  }

  Map<String, String> presetList = {
    /// 安保巡逻
    'patrol': '451357265515982848',

    /// 设备保养
    'maintain': '451357265520177153',

    /// 设备维修
    'repair': '451357265520177154',

    /// 设备巡检
    'inspection': '451357265520177152',

    /// 保洁
    'clean': '522832327887884288',

    /// 绿化
    'green': '525361915470270464',

    /// 品质巡查
    'qualityInspection': '718505360034664448',
  };

  Map<String, String> repairPointType = {
    'patrolPoint': '巡逻点',
    'devicePoint': '设备点',
    'deviceRoom': '设备间',
  };

  /// 预设清单类型对应操作名称
  String get presetName => onGetPresetName();

  String onGetPresetName() {
    switch (data?.inventoryId) {
      case '451357265515982848':
        return '巡逻';
      case '451357265520177153':
        return '保养';
      case '451357265520177152':
        return '巡检';
      case '522832327887884288':
        return '保洁';
      case '525361915470270464':
        return '绿化';
      case '718505360034664448':
        return '巡查';
      default:
        return '--';
    }
  }

  ///打电话给添加人
  callCreater() async {
    var url = 'tel:${data?.operatorPhone}';
    launch(url);
  }

  ///打电话给指派人
  callOperator() async {
    var url = 'tel:${data?.operatorPhone}';
    launch(url);
  }

  ///评论
  ///传一整个data过去
  route2comment() async {
    await Navigator.pushNamed(
      context1,
      'task/comment',
      arguments: data?.toJson(),
    );
    detailScrollviewKey.currentState?.initTrigger();
  }

  /// 添加子任务
  toAddChild() async {
    await Navigator.pushNamed(context1, 'task/edit', arguments: {
      'pid': args['id'],
      'isChildAdd': true,
      'pData': data?.toJson(),
    });
    await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
    detailScrollviewKey.currentState?.initTrigger();
  }

  /// 取消任务
  onCancel() async {
    bool? b = await WModalUtil.showSync(
      '任务取消后不可恢复，确认恢复?',
      title: '确认取消',
    );
    if (b!) {
      var res = await TaskServiceImpl.instance!.putTaskCancelV1({
        'id': id,
      });
      if (res.data == 1) {
        WToastUtil.show('任务取消成功');
        Navigator.pop(context1);
        await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
      }
    }
  }

  ///子任务
  route2child() async {
    await Navigator.pushNamed(
      context1,
      'task/child_task',
      arguments: {
        'id': id ?? '',
        'title': data?.title ?? '',
        'fatherFinished': data?.status == 'finished',
        'isoperator': data?.isoperator == true,
        'iscreatedBy': data?.iscreatedBy == true,
      },
    );
    detailScrollviewKey.currentState?.initTrigger();
  }

  ///指派
  route2assigner() async {
    final res = await WPickerUtil.tree<SinglePickerEntity>(
      context1,
      title: Text('任务转派给'),
      initialValue: null,
      data: empList,
      isSearch: true,
      isMulti: false,
      label: 'employeeName',
      value: 'employeeId',
      child: 'employees',
      firstName: 'companyShortName',
      firstValue: 'companyId',
    );
    if (res != null) {
      onPickTransifer(res[0]);
    }
  }

  ///员工列表

  List empList = [];

  /// 获取员工列表
  Future onGetEmpList() async {
    var res = await AuthApi.getOperatorListV2();
    res.data?.forEach((element) {
      element.employees!.forEach((item) {
        if (item.employeeId == userInfo!.id) {
          item.allName = '${item.organName}-${item.employeeName}(本人)';
        } else {
          item.allName = '${item.organName}-${item.employeeName}';
        }
      });
    });
    empList = jsonDecode(jsonEncode(res.data)) ?? [];
  }

  ///选择派送人
  List? mailToIds;
  onSelectCopyPeople(v) {
    mailToIds = v;
  }

  /// 选择，确认转派
  onPickTransifer(item) async {
    bool? b = await WModalUtil.showSync(
      '确认将任务转派给${item.name}?',
      title: '任务转派提示',
    );
    if (b!) {
      var res = await TaskServiceImpl.instance!
          .putTransfer({'id': id, 'operatorId': item.unique});
      if (res) {
        WToastUtil.show('任务转派成功');
        await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
        detailScrollviewKey.currentState?.initTrigger();
      } else {
        WToastUtil.show('任务转派失败');
      }
    }
  }

  /// 跳转编辑
  route2edit() async {
    await Navigator.pushNamed(context1, 'task/edit', arguments: {
      'id': data!.id,
      'data': data!.toJson(),
      'isChild': data!.isChild,
    });
    await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
    detailScrollviewKey.currentState?.initTrigger();
    notifyListeners();
  }

  ///底部完成任务按钮点击事件
  onFinishTap() async {
    bool? resCheck = await TaskServiceImpl.instance!.getCheckChild(
      {'id': id},
    );
    print(resCheck);
    if (resCheck != true) {
      WModalUtil.showSync(
        '此任务有子任务尚未完成，无法完成',
        title: '提示',
      );
    } else {
      var res = await InputDialog.show(context1, id: id);
      if (res == true) {
        await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
        detailScrollviewKey.currentState?.refreshTrigger();
      }
    }
  }

  ///点击删除事件
  onDelete() async {
    var c = await WModalUtil.showSync(
      '删除后，任务相关数据将不可恢复， 请谨慎操作！',
      title: '确认删除该任务？',
    );
    if (!c!) {
      return;
    }
    var res = await TaskServiceImpl.instance!.delete(data!.id);
    if (res.data == 1) {
      await WModalUtil.showSync('删除成功', canCancel: false);
      await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
      Navigator.pop(context1, 'delete');
    }
  }

  ///任务开始事件
  Future onStartTask() async {
    bool? confirm = await WModalUtil.showSync(
      '开始后任务不可再修改，并将通知任务派发人，确认开始吗？',
      title: '确认开始该任务？',
      confirmText: '确认开始',
    );
    if (confirm == true) {
      var res = await TaskServiceImpl.instance!.putStartTask(id!);
      if (res) {
        // onInitLocation();
        WToastUtil.show('任务开始成功');
        await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
        detailScrollviewKey.currentState?.refreshTrigger();
      } else {
        WToastUtil.show('任务开启失败');
      }
    }
  }

  /// 复制附件链接 [link] 链接地址
  onCopyLink(link, title) {
    Clipboard.setData(ClipboardData(text: link));
    if (link != null || link != '') {
      WModalUtil.showSync('复制$title成功！', canCancel: false);
    }
  }

  /// 预览文件
  route2perview(url, name) {
    WisPreviewUtil.show(
      url: url,
      name: name,
    );
  }

  ///合并
  Future getData() async {
    getDetail();
    await Future.wait([
      getState(),
      onGetEmpList(),
      onGetTaskChildList(),
    ]);
    notifyListeners();
  }

  /// 上级任务
  // @observable
  TaskDetailModel? father;
  // @action
  Future<void> onGetFather() async {
    if (data?.parentId == null || data?.parentId == '') {
      return;
    }
    var res = await TaskServiceImpl.instance!.getTaskDetail(data!.parentId);
    father = (res.data ?? {}) as TaskDetailModel?;
    notifyListeners();
  }

  @observable
  ObservableList<TaskChildModel> taskChildList = ObservableList.of([]);

  ///子任务列表
  Future<void> onGetTaskChildList({bool isLoad = true}) async {
    if (id == null || id == '') {
      return;
    }
    var res = await TaskServiceImpl.instance!.getTaskChildList({
      'parentId': id,
    });

    taskChildList = ObservableList.of(res.data ?? []);
  }

  ///  .pdf, .doc, .docx, .xls, .xlsx, .pptx, .ppt, image/*
  final List<String> fileArr = [
    'pdf',
    'docx',
    'xlsx',
    'xls',
    'doc',
    'pptx',
    'ppt'
  ];

  @observable
  ObservableList fileList = ObservableList.of([]);
  @observable
  ObservableList imgList = ObservableList.of([]);

  @action
  setImgList(data) {
    imgList = ObservableList.of(data);
  }

  @action
  setFileList(data) {
    fileList = ObservableList.of(data);
  }

  /// 任务详情
  @action
  Future<void> getDetail() async {
    var res = await TaskServiceImpl.instance!.getTaskDetail(id);
    List img = [];
    List file = [];
    if (res.data?.accessoryVos != null && res.data!.accessoryVos!.length > 0) {
      res.data!.accessoryVos!.forEach((item) => {
            if (fileArr.indexWhere((element) =>
                    element ==
                    item.accessoryName!
                        .substring(item.accessoryName!.lastIndexOf('.') + 1)) !=
                -1)
              {
                item.type = 'file',
                file.add(item),
              }
            else
              {
                item.type = 'img',
                img.add(item.accessoryId),
              }
          });
    }
    data = res.data ?? TaskDetailModel();
    setImgList(img);
    setFileList(file);

    /// 维修表单进行中才初始化位置信息
    // if (data?.inventoryId == presetList['repair'] && data?.status == 'doing') {
    //   onInitLocation();
    // }

    /// 待领取
    if (data?.status == 'waitReceive') {
      onSetEntryType('pickUp');
    }

    /// 查询标签枚举 改为所有任务类型都有标签 2023.11.29
    // if (data?.inventoryId == presetList['qualityInspection']) {
    getLabels();
    // }

    /// 父级任务
    if (data?.parentId != null && data?.parentId != '') {
      onGetFather();
    }

    /// 获取任务路线
    if (data?.preset == true) {
      onGetRoute();
    }
  }

  onCloseAbnormalListModal() {
    Navigator.pop(context1);
  }

  /// 需要处理的异常列表
  @observable
  ObservableList<TaskOperationNodeListItemList> needDealAbnormalList =
      ObservableList.of([]);

  /// 任务路线
  @observable
  ObservableList<TaskNodeList> routeList = ObservableList.of([]);

  /// 任务路线
  Future<void> onGetRoute() async {
    var res = await QrcodeServiceImpl.instance!.getOperationNodeList({
      'excutivePlatformId': id,
    });
    routeList = ObservableList.of(res.data?.list ?? []);

    /// 过滤异常列表
    if (data?.preset == true &&
        ['finished', 'doing'].contains(data?.status) &&
        routeList.length > 0) {
      needDealAbnormalList = ObservableList.of((routeList[0].list ?? []).where(
          (item) =>
              item.nodeData['resultAbnormal'] == true &&
              item.nodeData['status'] == 'untreated'));
    }
  }

  /// 预览详情图片
  void onShowImage(image) {
    List<ImageProvider> images = [];
    images.add(CachedNetworkImageProvider(AppParseUtil.image(image)));
    WisPhotoViewUtil.show(images, 0);
  }

  ///任务动态
  Future getState() async {
    var res = await TaskServiceImpl.instance!.getState({'id': id});
    status = res.data ?? [];
    firstStatus = (status?.length ?? 0) > 0 ? status?.first ?? null : null;
  }

  /// 重新开启
  @observable
  String openComment = '';
  onInputOpenComment(value) {
    openComment = value;
  }

  /// 任务重启
  onSubmitOpen() async {
    if (openComment == '') {
      WToastUtil.show('请填写重新开启原因');
      return;
    }
    WLoadingUtil.show();
    var res;

    try {
      res = await TaskServiceImpl.instance!.putTaskReopen(
        {
          "id": data!.id,
          "content": openComment,
        },
      );
    } finally {
      WLoadingUtil.hide();
      if (res?.data == 1) {
        WToastUtil.show('任务重启已成功');
        Navigator.pop(context1);
        await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
        detailScrollviewKey.currentState?.initTrigger();
      }
    }
  }

  /// 审查评论
  @observable
  String checkContent = '';
  onInputCheckComment(value) {
    checkContent = value;
  }

  /// 审查
  onSubmitCheck() async {
    if (checkContent == '') {
      WToastUtil.show('请填写审查内容');
      return;
    }
    WLoadingUtil.show();
    var res;

    try {
      res = await TaskServiceImpl.instance!.putTaskCheck(
        {
          "id": data!.id,
          "content": checkContent,
        },
      );
    } finally {
      WLoadingUtil.hide();
      if (res?.data == 1) {
        WToastUtil.show('审查已成功');
        Navigator.pop(context1);
        await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
        detailScrollviewKey.currentState?.initTrigger();
      }
    }
  }

  /// 输入评论
  @observable
  String? comment;
  onInputComment(value) {
    comment = value;
  }

  /// 添加评论
  onSubmitComment() async {
    if (comment == null || comment == '') {
      WToastUtil.show('请填写评论内容');
      return;
    }
    WLoadingUtil.show();
    var res;
    try {
      res = await TaskServiceImpl.instance!.postCommentCreate(
        {
          "id": data!.id,
          "content": comment,
          "imgs": imageList.length > 0
              ? imageList.map((img) => img['id']).join(',')
              : '',
        },
      );
    } finally {
      WLoadingUtil.hide();
      if (res?.data != null && res.data > 0) {
        imageList = ObservableList.of([]);
        WToastUtil.show('评论成功');
        Navigator.pop(context1);
        detailScrollviewKey.currentState?.initTrigger();
      }
    }
  }

  /// 选择照片
  @observable
  ObservableList imageList = ObservableList.of([]);
  @action
  Future<void> onSelectImages(List<FileEntity> files) async {
    final futures =
        files.map((e) => GlobalApi.postUploadImageObject(e.file!)).toList();
    try {
      WLoadingUtil.show();
      final res = await Future.wait(futures);
      imageList.addAll(res.map((e) => e).toList());
    } finally {
      WLoadingUtil.hide();
    }
  }

  /// 删除照片
  @action
  onDeleteImages(index) {
    imageList.removeAt(index);
  }

  /// 跳转子任务详情
  toTaskDetail(id, isChild, isMulti) async {
    await Navigator.pushNamed(
      context1,
      'task/detail',
      arguments: {
        'id': id,
        'isChild': isChild,
        'isMulti': isMulti ?? null,
      },
    );
  }

  /// 跳转点位详情，并进行异常处理
  toTaskPointFormByAbnormal(item) async {
    await Navigator.pushNamed(
      context1,
      'task/point_form',
      arguments: {
        'id': id,
        'relationIds': item.relationId,
        'route': routeList,
        'detailData': data,
        'detailStatus': data?.status,
        'seqencing': data?.seqencing ?? false,
        'isDealAbnormalSolve': true,
        'routeItem': item,
        'platformId': item.id,
        'cid': item.id,
      },
    );
    final refresh = WisStorageUtil.get(key: 'abnormal_list_refresh');
    if (refresh) {
      needDealAbnormalList =
          ObservableList.of(needDealAbnormalList.where((e) => item.id != e.id));
      if (needDealAbnormalList.length == 0) {
        Navigator.pop(context1);
      }
      WisStorageUtil.set(key: 'abnormal_list_refresh', data: false);
    }
    await onGetTaskChildList();
  }

  /// 跳转到点位操作页面
  toTaskPointForm(item) async {
    if (data?.status == 'no_open') {
      WToastUtil.show('当前任务未开始，请点击开始任务后可执行');
      return;
    }
    if (data?.status == 'cancel') {
      WToastUtil.show('当前任务已取消，不可执行');
      return;
    }
    if (data?.status == 'overdue') {
      WToastUtil.show('当前任务已逾期，不可执行');
      return;
    }
    if (data?.status != 'finished' &&
        item?.status != 'finished' &&
        item?.executable == false) {
      WToastUtil.show('当前任务存在次序，请先完成之前环节');
      return;
    }
    if ((((item?.status == 'unFinished') && (data?.isoperator == true)) ||
        (item?.status == 'finished'))) {
      if (item?.nodeData['nodeChildNum'] == 0) {
        await Navigator.pushNamed(
          context1,
          'task/point_form',
          arguments: {
            'id': id,
            'relationIds': item.relationId,
            'platformId': item.id,
            'cid': item.id,
            'route': routeList,
            'detailData': data,
            'detailStatus': data?.status,
            'seqencing': data?.seqencing ?? false,
          },
        );
        await getData();
        await onGetTaskChildList();
      } else {
        await Navigator.pushNamed(
          context1,
          'task/equipment',
          arguments: {
            'id': id,
            'childId': item.id,
            'relationIds': item.relationId,
            'detailData': data,
            'detailStatus': data?.status,
            'seqencing': data?.seqencing ?? false,
          },
        );
        await getData();
        await onGetTaskChildList();
      }
    }
  }

  /// 领取任务
  Future<void> onHandlePickup(id) async {
    try {
      var res = await QrcodeServiceImpl.instance!.postTaskReceive({'id': id});
      if (res == 1) {
        WToastUtil.show(
          '领取成功！',
        );
        await WisStorageUtil.set(key: 'isTaskListRefresh', data: true);
        Navigator.pop(context1);
        Navigator.pop(context1);
      }
    } finally {}
  }

  ///  维修前工单内容填写
  @observable
  String? descriptionFront = '';
  @action
  void onSetBeforeContent(value) {
    descriptionFront = value;
  }

  ///  删除维修工单图片
  // void onImageRemoveAtBefore(index, type) {
  //   if (type == 'before') {
  //     photosFront.removeAt(index);
  //   }
  //   if (type == 'after') {
  //     photosAfter.removeAt(index);
  //   }
  // }

  GlobalKey wmglkey = new GlobalKey();
  String date = DateFormat("yyyy-MM-dd HH:mm:ss").format(DateTime.now());

  /// 添加水印
  @action
  Future<File?> addWaterMark(File file) async {
    /// 水印widget 转图片
    if (currentAddress != null) {
      var tempMark = await (capturePng(wmglkey) as FutureOr<Uint8List>);

      /// 水印
      ui.Image tempMarkImg = ui.decodeImage(tempMark)!;

      /// 照片
      ui.Image fileImg = ui.decodeImage(file.readAsBytesSync())!;

      /// 照片上加上水印
      ui.Image img = ui.drawImage(fileImg, tempMarkImg);
      List<int> wmImage = ui.encodeJpg(img);
      file.writeAsBytesSync(wmImage);
      return file;
    }
    return null;
  }

  /// 上传水印照片
  Future onPostWaterMarkImg(File file) async {
    var res = await addWaterMark(file);
    if (res != null) {
      return await GlobalApi.postUploadImageObject(res);
    } else {
      WLoadingUtil.hide();
      return null;
    }
  }

  /// 维修后工单内容填写
  @observable
  String? descriptionAfter = '';
  @action
  void onSetAfterContent(value) {
    descriptionAfter = value;
  }

  // 当前地址
  @observable
  String? currentAddress;
  @action
  void onSetCurrentAddr(String? addr) {
    currentAddress = addr;
  }

  // @observable
  // Position? currentLocation;
  // @action
  // void onSetCurrentLocation(location) {
  //   currentLocation = location;
  // }

  /// 添加维修照片
  // @observable
  // ObservableList photosFront = ObservableList.of([]);
  // @observable
  // ObservableList photosAfter = ObservableList.of([]);
  // @action
  // Future<void> onSelectPic(List<FileEntity> files, String type) async {
  //   await onInitPicLocation(files, type);
  // }

  // /// 初始化图片位置信息
  // Future<void> onInitPicLocation(List<FileEntity> files, String type) async {
  //   WLoadingUtil.show();
  //   final futures = files.map((e) => onPostWaterMarkImg(e.file!)).toList();
  //   final pic = await Future.wait(futures);
  //   WLoadingUtil.hide();
  //   if (type == 'before') {
  //     photosFront.addAll(pic.map((e) => e).toList());
  //   }
  //   if (type == 'after') {
  //     photosAfter.addAll(pic.map((e) => e).toList());
  //   }
  //   WLoadingUtil.hide();
  // }

  List multiList = [];
  List? multiListAll = [];
  late Map groupByNo;

  /// 获取多环节任务列表
  Future<void> onGetMuitiTaskList() async {
    final res = await TaskServiceImpl.instance!.getMultiTaskList(id);
    multiListAll = res.data;
    onFilterOutTimeUrge();
    groupByNo = groupBy(res.data!, (dynamic obj) => obj?.nodeSequenceNumber);
    groupByNo.forEach((key, value) {
      multiList.add(value);
    });
    notifyListeners();
  }

  List urgeActiveList = [];

  /// 过滤超时催办环节任务
  void onFilterOutTimeUrge() {
    List urgeList = WisStorageUtil.get<List>(key: 'urgelist') ?? [];
    List tempList = [];
    if (urgeList.length == 0) {
      return;
    }
    var time;

    /// 筛选催办超过五分钟的环节任务
    urgeList.forEach((item) {
      time = json.decode(item)['time'];
      if ((DateTime.parse(time)
              .add(new Duration(minutes: 5))
              .isAfter(DateTime.now())) ==
          true) {
        urgeActiveList.add(
          json.decode(item),
        );
        tempList.add(item);
      }
      ;
    });
    urgeActiveList = urgeActiveList;
    WisStorageUtil.set(key: 'urgelist', data: tempList);
  }

  /// 判断当前环节任务是否被催办过
  @action
  bool isCheckActiveList(item) {
    return urgeActiveList
            .where((element) => element['id'] == item?.id)
            .toList()
            .length >
        0;
  }

  /// 所有环节任务是否完成
  bool isCheckMultiFinished() {
    return multiListAll!
                .where((element) => element?.status == 'unFinished')
                .toList()
                .length >
            0
        ? false
        : true;
  }

  /// 多环节任务详情
  void toMultiDetail(item) {
    /// 1、主任务不可查看
    if (item?.id == null) {
      return;
    }

    /// 2、非执行人、非创建人不可查看隐藏任务
    if (item?.isPublic == false &&
        item?.isoperator == false &&
        item?.iscreatedBy == false) {
      WToastUtil.show('该任务未公开，您没有查看权限哦~');
      return;
    }

    /// 3、当前任务无需查看
    if ((item?.relationId == null && item?.exPlatformId == data?.id) ||
        (item?.relationId != null && item?.relationId == data?.id)) {
      return;
    }

    toTaskDetail(item?.relationId, false, true);
  }

  /// 催办
  Future onPostTaskUrge(item) async {
    List urgeList = WisStorageUtil.get<List>(key: 'urgelist') ?? [];
    if (isCheckActiveList(item)) {
      WToastUtil.show('已经催办过了哦~');
      return;
    }
    final res = await TaskServiceImpl.instance!.postTaskUrge(item?.id);
    if (res != null) {
      WToastUtil.show('催办已成功！');
      var tempItem = {
        'id': item.id,
        'time': DateTime.now(),
      };
      urgeActiveList.add(tempItem);
      urgeActiveList = urgeActiveList;
      urgeList.add(json.encode(tempItem, toEncodable: myEncode));
      WisStorageUtil.set(key: 'urgelist', data: urgeList);
      notifyListeners();
    } else {
      WToastUtil.show('催办未成功，请稍后重试哦~');
    }
  }

  /// 一键催办
  Future onPostTaskMultiUrge() async {
    List urgeList = WisStorageUtil.get<List>(key: 'urgelist') ?? [];
    List tempList = [];
    final res = await TaskServiceImpl.instance!.postTaskMultiUrge(id);
    if (res != null) {
      WToastUtil.show('一键催办成功！');
      multiListAll!.forEach((element) {
        /// 非当前层级任务、已完成环节任务、本人执行 不可催办
        if (element?.isAllowUrge == true &&
            element?.status != 'finished' &&
            element?.isoperator != true) {
          /// 未催办过的
          if (!isCheckActiveList(element) && element?.id != null) {
            var tempItem = {
              'id': element?.id,
              'time': DateTime.now(),
            };
            tempList.add(tempItem);
            urgeList.add(json.encode(tempItem, toEncodable: myEncode));
          } else {
            /// 已催办过的 进行时间更新
            if (isCheckActiveList(element)) {
              var tempItem = {"id": element?.id, "time": DateTime.now()};
              int index = urgeActiveList.indexWhere(
                  (activeElement) => activeElement['id'] == element.id);
              int index2 = urgeList.indexWhere((activeElement) =>
                  json.decode(activeElement)['id'] == element.id);

              urgeActiveList[index] = tempItem;
              urgeList[index2] = json.encode(tempItem, toEncodable: myEncode);
            }
          }
        }
      });
      urgeActiveList.addAll(tempList);
      urgeActiveList = urgeActiveList;
      WisStorageUtil.set(key: 'urgelist', data: urgeList);
      multiList = multiList;
      notifyListeners();
    }
  }

  /// 时间的单独encode 否则会报错
  dynamic myEncode(dynamic item) {
    if (item is DateTime) {
      return item.toIso8601String();
    }
    return item;
  }

  deleteState(item) async {
    final boolean = await WModalUtil.showSync(
      '确定要删除此条动态吗？',
      title: '删除动态',
      cancelText: '取消',
      confirmText: '确认',
    );
    if (boolean == true) {
      final res = await TaskServiceImpl.instance!.deleteTaskState(item.id);
      if (res == 1) {
        WToastUtil.show('删除动态成功');
        detailScrollviewKey.currentState?.initTrigger();
      }
    }
  }

  /// 跳转任务动态
  toTaskDynamic() async {
    await Navigator.pushNamed(
      context1,
      'task/dynamic',
      arguments: {
        'id': args['id'],
      },
    );
  }

  /// 获取标签列表
  @action
  Future getLabels() async {
    // final res = await TaskServiceImpl.instance!.getLabelList();
    // getLabelName(data?.labels ?? [], res.data ?? []);
    getLabelName(data?.labelVos ?? []);
  }

  /// 标签
  getLabelName(data) {
    List _label = [];
    data.forEach((item) {
      _label.add(item.name);
    });
    setLabelName(_label.join(','));
  }

  /// 标签名称
  String labelName = '';

  /// 设置标签名称
  setLabelName(name) {
    labelName = name;
    notifyListeners();
  }
}
