/*
 * @Author       : WuWei
 * @LastEditors: ChenYaJin
 * @Date         : 2021-04-28 14:40:50
 * @LastEditTime: 2023-08-10 18:00:58
 * @FilePath     : /wisdom-huiguanjia-app/task_package/lib/src/view_models/edit_store.dart
 * @Description  : 任务添加、编辑逻辑
 */
import 'dart:convert';
import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import '../../src/impl/auth.dart';
import '../../src/impl/task_service_impl.dart';
import '../../src/pages/edit/index.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:intl/intl.dart';
part 'edit_store.g.dart';

class EditStore = _EditStore with _$EditStore, ChangeNotifier;

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

  ///路由参数（请勿修改）
  EditPageArguments get arguments =>
      EditPageArguments.fromRouteArguments(context1);
  @action
  _EditStore(this.context1) {
    if (arguments.id != null) {
      params['title'] = ObservableMap.of(arguments.data ?? {})['title'];
      params['content'] = ObservableMap.of(arguments.data ?? {})['content'];
      mailToIds = ObservableList.of(
          ObservableMap.of(arguments.data ?? {})['mailFromIds'] ?? []);
      inventoryId = ObservableMap.of(arguments.data ?? {})['inventoryId'];
      operatorId = ObservableMap.of(arguments.data ?? {})['operatorId'];
      supervisorId = ObservableMap.of(arguments.data ?? {})['supervisorId'];
      var tmpImgArr =
          ObservableMap.of(arguments.data ?? {})['accessoryVos'] ?? [];
      fileIds = tmpImgArr.length > 0
          ? ObservableList.of(tmpImgArr
              .where((e) => e.type == 'file')
              .toList()
              .map((item) => {
                    'id': item.accessoryId,
                    'name': item.accessoryName,
                  })
              .toList())
          : ObservableList.of([]);
      imageList = tmpImgArr.length > 0
          ? ObservableList.of(tmpImgArr
              .where((e) => e.type == 'img')
              .toList()
              .map((item) => {
                    'id': item.accessoryId,
                    'name': item.accessoryName,
                  })
              .toList())
          : ObservableList.of([]);
      params['closeTime'] = ObservableMap.of(arguments.data ?? {})['closeTime'];
      params['isPublic'] = ObservableMap.of(arguments.data ?? {})['isPublic'];
    }

    if (arguments.isChildAdd == true) {
      supervisorId = arguments.pData['supervisorId'] ?? '';
    }

    if (arguments.isAbnormalAdd == true) {
      params['title'] = ObservableMap.of(arguments.data ?? {})['title'];
      params['content'] = ObservableMap.of(arguments.data ?? {})['content'];
    }

    ///可在此处理进入页面前的操作，比如响应路由的传参进行赋值。
  }
  bool? get isAbnormalAdd => arguments.isAbnormalAdd;
  String? get id => arguments.id;
  Map get pData => Map.from(arguments.pData ?? {});

  @observable
  ObservableList fileIds = ObservableList.of([]);

  ///
//@observable
//int value;

  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();
  //当前员工的信息
  EmployeesInfoModel? get userInfo => authGlobalStore.info;

  final formKey = GlobalKey<FormState>();
  final formKey1 = GlobalKey<FormState>();

  ///传参就是编辑
  // String get title => ;
  String get title => arguments.id != null
      ? '编辑${arguments.isChild == true ? '子' : ''}任务'
      : '添加${arguments.isChildAdd == true ? '子' : ''}任务';

  ///如果id==null  那页面类型一定是新建
  bool get isCreate => arguments.id == null;

  bool get isChild => arguments.isChild ?? false;

  bool get isChildAdd => arguments.isChildAdd ?? false;

  @observable
  ObservableMap<String, dynamic> params = ObservableMap.of(new Map.from({
    'isPublic': true,
    'closeTime': null,
  }));

  /// 改变表单值
  @action
  paramsChange(field, data) {
    params[field] = data;
  }

  /// 完成时间选择
  void onTimePicker(time) {
    params['closeTime'] = time;
  }

  @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);
  }

  /// 选择任务公开
  @action
  isPublicChange(data) {
    paramsChange('isPublic', data);
  }

  ///合并   判断是新建还是编辑
  Future submit() async {
    if (!onHandleValidate()) {
      return;
    }
    if (isCreate) {
      await create();
    } else {
      await upDate();
    }
  }

  bool onHandleValidate() {
    if (params['title'] == null || params['title'] == '') {
      WToastUtil.show('请填写任务标题');
      return false;
    }

    if (params['content'] == null || params['content'] == '') {
      WToastUtil.show('请填写任务内容');
      return false;
    }

    if (inventoryId == null || inventoryId == '') {
      WToastUtil.show('请选择任务类型');
      return false;
    }

    if (operatorId == null || operatorId == '') {
      WToastUtil.show('请选择执行人');
      return false;
    }

    if (supervisorId == null || supervisorId == '') {
      WToastUtil.show('请选择监督人');
      return false;
    }
    return true;
  }

  ///新建
  @action
  Future create() async {
    List tempArr = [...imageList, ...fileIds];
    DateFormat outputFormat = DateFormat("yyyy-MM-dd HH:mm");
    final closeTime = params['closeTime'] != null
        ? outputFormat.format(DateTime.parse(params['closeTime']))
        : null;
    final formPrs = {
      "title": params['title'],
      "content": params['content'],
      "isPublic": params['isPublic'],
      "closeTime": closeTime,
      "operatorId": operatorId,
      "supervisorId": supervisorId,
      "mailToIds": mailToIds,
      "accessorys": tempArr,
      "inventoryId": inventoryId,
      "subOperatorIds": childOperatorId,
    };
    if (isAbnormalAdd == true) {
      formPrs['resultAbnormalSolve'] = true;
      formPrs['operationRecordAnswerId'] = arguments.operationRecordAnswerId;
      formPrs.remove('subOperatorIds');
    }
    if (isChildAdd || isAbnormalAdd == true) {
      formPrs['id'] = pData['id'];
      var res = await TaskServiceImpl.instance!.postTaskChildV2(formPrs);
      if (res.data == 1) {
        WModalUtil.showSync('添加成功', canCancel: false).then(
          (value) => Navigator.pop(context1, true),
        );
      }
    } else {
      var res = await TaskServiceImpl.instance!.postTaskAddV3(formPrs);
      if (res.data == 1) {
        WModalUtil.showSync('添加成功', canCancel: false).then(
          (value) => Navigator.pop(context1),
        );
      }
    }
  }

  ///修改
  Future upDate() async {
    List tempArr = [...imageList, ...fileIds];
    DateFormat outputFormat = DateFormat("yyyy-MM-dd HH:mm");
    final closeTime = params['closeTime'] != null
        ? outputFormat.format(DateTime(params['closeTime']))
        : null;

    final formPrs = {
      "title": params['title'],
      "content": params['content'],
      "isPublic": params['isPublic'],
      "closeTime": closeTime,
      "operatorId": operatorId,
      "supervisorId": supervisorId,
      "mailToIds": mailToIds,
      "accessorys": tempArr,
      "inventoryId": inventoryId,
      'id': id,
    };
    var res = await TaskServiceImpl.instance!.putTaskUpdateV2(formPrs);
    if (res.data == 1) {
      WModalUtil.showSync('修改成功', canCancel: false).then(
        (value) => Navigator.pop(context1),
      );
    }
  }

  ///抄送人列表
  @observable
  List mailList = [];

  @observable
  List operatorList = [];

  @action
  onGetOperatorList() 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}';
        }
      });
    });
    mailList = jsonDecode(jsonEncode(res.data)) ?? [];
    var list = res.data != null ? res.data : [];
    operatorList = jsonDecode(jsonEncode(list)) ?? [];
  }

  onAddEdit() {}

  ///执行人  如果为null，则认定为执行给本人
  @observable
  String? operatorId;

  @action
  onSetOperatorPeople(v) {
    operatorId = v;
  }

  /// 选择监督人
  @observable
  String? supervisorId = '';

  @action
  onSetSupervisor(v) {
    supervisorId = v ?? '';
  }

  ///子执行人
  @observable
  List childOperatorId = [];

  @action
  onSetChildOperator(v) {
    childOperatorId = v;
  }

  ///选择抄送人
  @observable
  List? mailToIds;
  @action
  onSelectCopyPeople(v) {
    mailToIds = v;
  }

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

  /// 选择任务类型
  @observable
  String? inventoryId;
  @action
  void onSelectListItem(item) {
    inventoryId = item;
  }
}
