/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-03-16 16:48:40
 * @LastEditTime : 2023-05-16 16:49:28
 * @FilePath     : /wisdom-huiguanjia-app/oa_package/lib/src/view_models/private_process_store.dart
 * @Description  : Do not edit
 */
import 'dart:async';
import 'dart:convert';

import 'package:app_package/app_package.dart';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
// import 'package:oa_package/src/models/task_list_model.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import 'package:oa_package/src/pages/process/index.dart';
// import 'package:oa_package/src/models/menu_detail_model.dart';
import 'package:oa_package/src/impl/oa_service_impl.dart';
// import 'package:oa_package/src/models/flows_detail_model.dart';
import 'package:oa_package/src/models/tast_history_list_model.dart';
part 'private_process_store.g.dart';

class PrivateProcessStore = _PrivateProcessStore
    with _$PrivateProcessStore, ChangeNotifier;

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

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

  _PrivateProcessStore(this.context1) {
    ///可在此处理进入页面前的操作，比如响应路由的传参进行赋值。
    ///
  }
  String? get processId => arguments.id;
  get formHtml => arguments.formHtml;
  get formValue => arguments.formValue;
  get activeTaskId => arguments.activeTaskId;

  /// 设置标题栏标题
  @observable
  String barTitle = '申请';
  @action
  void setBarTitle() {
    barTitle = '${arguments.title}';
  }

  ///true：显示“发起审批” false:“显示提交记录”
  @observable
  bool isForm = true;
  @action
  setisForm(bool value) => isForm = value;

  /// 提交审批表单初始化
  Future<void> onInitform() async {
    setBarTitle();
    if (formHtml == null) {
      await Future.wait([onGetMenuDetail(processId)]);
    } else {
      formList = ObservableList.of(formHtml);
      postFormPrs = ObservableMap.of(formValue);
    }
  }

  ///表单列表
  @observable
  ObservableList formList = ObservableList.of([]);

  /// 获取表单详情
  /// @id 流程id;
  @action
  Future<void> onGetMenuDetail(id) async {
    final res = await OaServiceImpl.instance!.getMenuFormDetail({
      'id': processId,
    });
    this.formList =
        ObservableList.of(jsonDecode(res.data!.formHtml!)['fields']);
    if (formHtml == null) {
      oninitialFormValue();
      onGetDraftsDetail(res.data?.id);
    }
  }

  /// 初始化表单初始值
  void oninitialFormValue() {
    for (num i = 0; i < formList.length; i++) {
      if (formList[i as int]['__config__']['defaultValue'] != null) {
        onSetFormPrs(formList[i]['__vModel__'],
            formList[i]['__config__']['defaultValue']);
      }
    }
  }

  /// 获取草稿详情
  ///
  Future<void> onGetDraftsDetail(id) async {
    final res = await OaServiceImpl.instance!.getDraftsDetail({
      'formId': id,
      'flowId': processId,
    });
    if (res.data?.formValue != null) {
      postFormPrs = ObservableMap.of(jsonDecode(res.data!.formValue!));
    }
  }

  late Map taskParams = {
    'pageNum': 1,
    'pageSize': 20,
  };

  final taskHistoryScrollViewKey = GlobalKey<WisScrollViewState>();

  /// 获取历史提交记录
  @observable
  ObservableList<TaskHistoryListModel>? taskHistoryList = ObservableList.of([]);
  @action
  Future<void> onGetUserHistoryList() async {
    final res = await OaServiceImpl.instance!.getTaskHistoryList({
      'processId': processId,
      'pageNum': taskParams['pageNum'],
      'pageSize': taskParams['pageSize']
    });
    final _data = res.data;

    taskParams['pageNum'] == 1
        ? taskHistoryList = ObservableList.of(res.data!.list!)
        : taskHistoryList!.addAll(ObservableList.of(res.data!.list!));
    if ((_data?.total ?? 0) == 0) {
      taskHistoryScrollViewKey.currentState?.isEmpty();
    } else if ((_data?.pages ?? 0) <= (_data?.pageNum ?? 0) &&
        _data!.total! > 0) {
      taskHistoryScrollViewKey.currentState?.isLast();
    } else {
      taskParams['pageNum']++;
    }
  }

  /// 填写验证
  /// @value 表单填写内容；
  /// @regList 校验规则列表；
  /// @formItem 当前表单；
  String? onValidateFormItem(dynamic value, List regList, formItem) {
    if (regList.length == 0) return null;
    List notMatchList = [];
    regList.forEach((regItem) {
      /// 去除js正则斜杠
      List<String> list = regItem['pattern'].split('');
      List<String> arr = [];
      for (num i = 0; i < list.length; i++) {
        if (list[i as int] != '/' && (i != 0 && i != (list.length - 1)))
          arr.add(list[i]);
      }
      final reg = new RegExp(ListFunc.list2String(arr), multiLine: true);
      if (!reg.hasMatch(value)) {
        notMatchList.add(regItem);
      }
    });

    if (notMatchList.length > 0) {
      return notMatchList[0]['message'];
    } else {
      return null;
    }
  }

  /// 整个表单认证
  bool onValidateForm() {
    final List resultList = [];
    for (var formItem in formList) {
      if (!formItem['__config__']['required']) {
        resultList.add(true);
        break;
      }
      if (postFormPrs['${formItem['__vModel__']}'] == null ||
          postFormPrs['${formItem['__vModel__']}'] == '' ||
          (postFormPrs['${formItem['__vModel__']}'] is List &&
              postFormPrs['${formItem['__vModel__']}'].length == 0)) {
        resultList.add(false);
        WToastUtil.show('请填写${formItem['__config__']['label']}');
        break;
      }
      if (onValidateFormItem(postFormPrs['${formItem['__vModel__']}'],
              formItem['__config__']['regList'], formItem) !=
          null) {
        resultList.add(false);
        WToastUtil.show(onValidateFormItem(
            postFormPrs['${formItem['__vModel__']}'],
            formItem['__config__']['regList'],
            formItem)!);
        break;
      }
      resultList.add(true);
    }

    if (resultList.where((element) => !element).toList().length > 0)
      return false;
    else
      return true;
  }

  /// @postFormPrs 提交表单内容
  @observable
  ObservableMap postFormPrs = ObservableMap.of({});

  /// 表单赋值
  /// @prsName 表单属性；
  /// @value 填写的表单内容；
  @action
  void onSetFormPrs(prsName, value) {
    postFormPrs.remove(prsName);
    postFormPrs.addAll({
      '$prsName': value,
    });
  }

  /// 重置表单
  @action
  void onResetPostprs() {
    postFormPrs.clear();
  }

  final formKey = GlobalKey<FormState>();
  Future<void> onSubmitForm() async {
    final res = onValidateForm();
    if (res) {
      if (formHtml == null) {
        final id = await OaServiceImpl.instance!.postFlowsStart(
          processId,
          {'formVar': postFormPrs, 'ccOperator': []},
        );
        if (id != null) {
          WToastUtil.show('${arguments.title}审批提交成功！');
          onResetPostprs();
          Navigator.pop(context1);
        }
      } else {
        final isSuccess = await (OaServiceImpl.instance!.patchTaskDetail(
          {
            'id': activeTaskId,
            'action': 'submit',
          },
          {'formVar': postFormPrs, 'ccOperator': []},
        ) as FutureOr<bool>);
        if (isSuccess) {
          WToastUtil.show('${arguments.title}审批重新提交成功！');
          onResetPostprs();
          Navigator.pop(context1);
        }
      }
    }
  }

  /// 跳转详情
  Future<void> onToTaskDetail(TaskHistoryListModel taskItem) async {
    WNavUtil.instance!.pushNamed(
      'oa/detail',
      arguments: {
        'id': taskItem.orderId,
        'type': taskItem.type,
      },
    );
  }

  @observable
  bool isFlowsShow = false;

  ///查看审批环节
  @action
  Future<void> onViewFlows() async {
    onValidateForm();
    isFlowsShow = !isFlowsShow;
  }

  ///选择上传图片
  @action
  Future<void> onFilesChanged(List<FileEntity> files, label) async {
    final futures =
        files.map((e) => GlobalApi.postUploadImageObject(e.file!)).toList();
    List imageArr = postFormPrs[label] ?? [];
    try {
      WLoadingUtil.show();
      final res = await Future.wait(futures);
      imageArr.addAll(res.map((e) => e).toList());
      onSetFormPrs(label, imageArr);
    } finally {
      WLoadingUtil.hide();
    }
  }

  ///删除图片
  @action
  void onImageRemoveAt(label, index) {
    List imageArr = postFormPrs[label] ?? [];
    imageArr.removeAt(index);
    onSetFormPrs(label, imageArr);
  }
}
