/*
 * @Author       : WuWei
 * @LastEditors  : WuWei
 * @Date         : 2021-03-29 11:11:02
 * @LastEditTime : 2023-05-25 15:55:06
 * @FilePath     : /wisdom-huiguanjia-app/oa_package/lib/src/view_models/private_detail_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:flutter/services.dart';
import 'package:mobx/mobx.dart';
import 'package:oa_package/src/impl/oa_service_impl.dart';
import 'package:oa_package/src/models/task_detail_model.dart';
import 'package:oa_package/src/pages/detail/index.dart';
// import 'package:wisdom_cli/new/widgets/image.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
part 'private_detail_store.g.dart';

class DetailStore = _DetailStore with _$DetailStore, ChangeNotifier;

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

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

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

  /// 任务详情
  @observable
  TaskDetailModel? taskDetail;
  List? formHtml = [];
  dynamic formValue;
  String? formId;
  @action
  Future<void> onGetFlowsDetail() async {
    final res = await OaServiceImpl.instance!.getTaskDetaiil({
      'id': arguments.id,
      'type': arguments.type,
    });

    taskDetail = res.data ?? TaskDetailModel.fromJson({});
    if (taskDetail!.activeTaskName == null) {
      taskDetail!.activeTaskName = 'end';
    }
    // 每个流程结尾添加结束伪节点
    taskDetail?.traces?.add(TracesOfTaskDetailModel.fromJson({
      "title": "流程结束",
      "taskName": 'end',
    }));
    // 表单表格
    formHtml = jsonDecode(taskDetail!.formHtml!)['fields'];
    // 表单填写内容
    formValue = jsonDecode(taskDetail!.formValue!)['formVar'];
    formHtml!.forEach((formItem) {formatFormValue(formItem, formValue[formItem['__vModel__']]);});
  }

  /// 格式化详情表单内容
  /// @formItem 表单行 ；formValue 表单所填内容；
  /// @formItem['_value_'] 返回的表单行所填的值
  formatFormValue(formItem, formValue) {
    switch (formItem['__config__']['tag']) {
      // 开关
      case 'el-switch':
        return formItem['_value_'] = formValue != null && formValue ? '是' : '否';
      // 时间
      case 'el-date-picker':
      case 'el-time-picker':
        return formItem['_value_'] =
            (formValue is List) ? formValue.join(' 至 ') : formValue;
      // 选择
      case 'el-select':
        List resultList = formItem['__slot__']['options']
            .where((item) => item['value'] == formValue)
            .toList()
            .map((item) => item['label'])
            .toList();
        String result = '';
        if (resultList.length > 0) {
          for (var i = 0; i < resultList.length; i++) {
            result =
                '$result${resultList[i]}${i == (resultList.length - 1) ? '' : '、'}';
          }
        }
        return formItem['_value_'] = result;
      // 选择
      case 'el-radio-group':
        final d = formItem['__slot__']['options']
            .where((item) => item['value'] == formValue)
            .toList();
        if (d.length > 0) {
          return formItem['_value_'] = d[0]['label'];
        }
        return formItem['_value_'] = '--';
      // 多选
      case 'el-checkbox-group':
        if (formValue is List) {
          List resultList = [];
          formValue.forEach((valueItem) {
                formItem['__slot__']['options'].forEach((option) =>
                    option['value'] == valueItem
                        ? resultList.add(option['label'])
                        : '');
              });
          String result = '';
          if (resultList.length > 0) {
            for (var i = 0; i < resultList.length; i++) {
              result =
                  '$result${resultList[i]}${i == (resultList.length - 1) ? '' : '、'}';
            }
          }
          return formItem['_value_'] = result;
        }
        break;
      // 上传
      case 'el-upload':
        //图片
        if (formItem['__config__']['tagIcon'] == 'imgUpload') {
          if (formValue is List) {
            final images = formValue.map((e) => e['id']).toList();
            return formItem['_value_'] = images;
          }
        }
        // 附件
        if (formItem['__config__']['tagIcon'] == 'upload') {
          if (formValue is List) {
            return formItem['_value_'] = formValue;
          }
        }
        break;
      default:
        return formItem['_value_'] = formValue;
    }
  }

  ///驳回、提交审批
  /// @content 填写内容；
  /// @type 类型；
  /// @typeText 类型文字；
  /// @id taskId;；
  Future<void> onTaskAction(
      String content, String? type, String? typeText, String? id, audit) async {
    if (audit != null && audit && (content == '')) {
      WToastUtil.show('$typeText原因不可为空');
      return;
    }
    var res = await OaServiceImpl.instance!.patchTaskDetail({
      'id': id,
      'action': type,
    }, {
      'formVar': {
        "auditDesc": content,
      }
    });
    if (res == true) {
      // 关闭弹窗
      Navigator.pop(context1);
      // 退出详情
      Navigator.pop(context1, true);
      WToastUtil.show('$typeText提交成功！');
    }
  }

  /// 跳到申请审批
  Future<void> onToute2TaskDetail() async {
    await WNavUtil.instance!.pushNamed('oa/process', arguments: {
      'title': '${taskDetail?.processName ?? ''}',
      "formHtml": formHtml,
      "formValue": formValue,
      "activeTaskId": taskDetail?.activeTaskId,
    }).then((value) => onGetFlowsDetail());
  }

  ///终止审批
  Future<void> onTerminateTask() async {
    var res = await (OaServiceImpl.instance!.patchTaskTerminate({
      'id': arguments.id,
    }) as FutureOr<bool>);
    if (res) {
      Navigator.pop(context1, true);
      WToastUtil.show('终止成功！');
    }
  }

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

  /// 复制附件链接 [link] 链接地址
  void onCopyLink(file) {
    final String baseUrl = APPConfig.baseURL;
    final reg = RegExp('^image/');
    String link;
    // 图片
    if (reg.hasMatch(file['type'])) {
      link = baseUrl + 'file/images/' + file['id'];
    } else {
      // 附件
      link = baseUrl + 'file/download/' + file['id'];
    }
    Clipboard.setData(ClipboardData(text: link));
    if (link != '') {
      WModalUtil.showSync('复制${file['name']}成功，请到浏览器打开！', canCancel: false);
    }
  }
}
