import { action, observable, toJS } from "mobx";
import * as API from "../apis/TodoCenterService";

import { message, Modal, Button } from "antd";
import { WeaForm, WeaTableNew, WeaLogView, } from "comsMobx";
import { WeaLocaleProvider, WeaTools, WeaButtonIcon } from "ecCom";
import isFunction from 'lodash/isFunction';
import {
  checkNonstandard,
  setModal,
  doConfirm,
  onCheck
} from '../util/IntegrationUtil';
import {
  checkTableFieldValueUnique,
} from "../apis/CommonService";

const { TableStore } = WeaTableNew;
const { LogStore } = WeaLogView;
const getLabel = WeaLocaleProvider.getLabel;

export class TodoCenterStore {

  @observable hasRight = true;
  @observable rightLoading = true;
  @observable dialog = '';

  @observable tableStore = new TableStore();
  @observable tableStore2 = new TableStore();
  @observable tableStore3 = new TableStore();
  @observable tableStore4 = new TableStore();

  @observable tableStore_ofsInfoWorkflowType = new TableStore();
  @observable tableStore_ofsInfoWorkflow = new TableStore();
  @observable tableStore_ofsInfoLog = new TableStore();

  @observable searchForm = new WeaForm();
  @observable searchForm2 = new WeaForm();
  @observable searchForm3 = new WeaForm();

  @observable searchForm_ofsInfoWorkflowType = new WeaForm();
  @observable searchForm_ofsInfoWorkflow = new WeaForm();
  @observable searchForm_ofsInfoLog = new WeaForm();

  @observable newForm = new WeaForm();
  @observable newForm2 = new WeaForm();
  @observable ofsInfoAddForm = new WeaForm();
  @observable ofsInfoWorkflowTypeEditForm = new WeaForm();
  @observable ofsInfoWorkflowTypeEditFormOrg = new WeaForm();
  @observable AddObjectDialogForm = new WeaForm();//添加对象弹窗的Form

  @observable logStore = new LogStore();//异构系统日志
  @observable logStore2 = new LogStore();//流程数据日志
  @observable logStore3 = new LogStore();//集成参数日志

  @observable logStore_ofsInfo_workflowType = new LogStore();//集成参数日志

  @observable operateRecordIndex = '';

  @observable
  status = {
    changeDBValue: '',
    changeValue: '',
    checkDifdbnames: [],
    OfsInfoEditWorkflowTypeSpin: true,
    editwftype: 0,
    onlyview: 0,
    pccwurlValue: '',
    appcwurlValue: '',
    tableCheck: {},
    menu: [
      {
        key: "1",
        icon: <i className="icon-coms-Save-as" />,
        content: "保存",
        onClick: () => this.getAddObjectDialogForm('addShare')
      }
    ],
    workflowid: '',
    Btn: [],
    Notab: false,
    Tabkey: '0',
    changeButton: [],
    topTab: [{
      title: `${getLabel('1361', '基本信息')}`,
      viewcondition: "0"
    },
    {
      title: `${getLabel('528479', '创建人范围设置')}`,
      viewcondition: "1"
    }],
    hasNonStandard: true,
    nonStandLoading: true,
    rowSelect: [],
    newForm2Condition: [],
    selectedKey: 0,
    showSearchAd: false,
    rightMenus: [],
    rightMenus2: [],
    rightMenus3: [],
    rightMenus_ofsInfoWorkflowType: [],
    rightMenus_ofsInfoWorkflow: [],

    condition: [],
    condition2: [],
    condition3: [],
    condition_ofsInfoWorkflowType: [],
    condition_ofsInfoWorkflow: [],
    condition_ofsInfoLog: [],

    ofsSettingFormHiddenFields: [],

    ofsInfoAddFormHiddenFields: [],
    ofsInfoAddFormCondition: [],
    ofsInfoWorkflowTypeEditFormHiddenFields: [],

    networkIPColumnsSet: [],
    networkIPData: [],

    rowSelectIds: [],
    rowSelectIds_ofsInfoWorkflowType: [],
    rowSelectIds_ofsInfoWorkflow: [],
    showNewFormDialog: false,
    WorkflowViewFormDialogVisible: false,
    ofsInfoAddFormDialogVisible: false,
    ofsInfoEditDetailDialogVisible: false,
    ofsInfoEditWorkflowTypeDialogVisible: false,
    ofsInfoAddNetworkIPDialogVisible: false,
    logOfsInfoVisible: false,
    logWorkflowVisible: false,
    logOfsSettingVisible: false,
    logOfsInfoWorklfowTypeVisible: false,

    operateIndex: '',
    automaticLogin: [],
  };

  @action setState = (params = {}) => {
    let status = { ...this.status };
    Object.keys(params).forEach(key => {
      status[key] = params[key];
    })
    this.status = status;
  }

  @action
  setOperateRecordIndex = (val) => {
    this.operateRecordIndex = val;
  }

  @action cleanStore = () => {
    this.hasRight = true;
    this.rightLoading = true;
    this.searchForm = new WeaForm();
    this.searchForm2 = new WeaForm();
    this.searchForm3 = new WeaForm();
    this.setState({
      addObjectVisible: false,
      dbnameCells: [],
      searchType: ['base', 'advanced'],
      advanceHeight: 124,
      selectedKey: 0,
      showSearchAd: false,
      buttonLoading: true,
      inteParamsSelectedKey: 0,
      rightMenus: [],
      condition: [],
      newFormCondition: [],
      newFormConditionItem: [],
      selectedRowKeys: [],
      rightMenus_ofsInfoWorkflowType: [],
      rightMenus_ofsInfoWorkflow: [],

      condition_ofsInfoWorkflowType: [],
      condition_ofsInfoWorkflow: [],
      condition_ofsInfoLog: [],

      ofsSettingFormHiddenFields: [],

      ofsInfoAddFormHiddenFields: [],
      ofsInfoWorkflowTypeEditFormHiddenFields: [],

      networkIPColumnsSet: [],
      networkIPData: [],

      rowSelectIds: [],
      rowSelectIds_ofsInfoWorkflowType: [],
      rowSelectIds_ofsInfoWorkflow: [],
      showNewFormDialog: false,
      WorkflowViewFormDialogVisible: false,
      ofsInfoAddFormDialogVisible: false,
      ofsInfoEditDetailDialogVisible: false,
      ofsInfoEditWorkflowTypeDialogVisible: false,
      ofsInfoAddNetworkIPDialogVisible: false,
      logOfsInfoVisible: false,
      logWorkflowVisible: false,
      logOfsSettingVisible: false,
      logOfsInfoWorklfowTypeVisible: false,
      HRMNetworkIPListVisible: false,
      operateIndex: '',
    })
  }

  @action
  doInit = () => {
    this.setState({
      nonStandLoading: true,
      changeValue: '',
      changeDBValue: '',
      checkDifdbnames: []
    })
    // checkNonstandard({ num: "081" }, (result) => {
    //   this.setState({
    //     hasNonStandard: result.isOpen,
    //     nonStandLoading: false
    //   })
    //   if (result.isOpen) {
    //     this.cleanStore();
    //     this.getOfsInfoList();
    //     this.getOfsInfoRightMenu();
    //     this.getOfsInfoCondition();
    //   }
    // });
    this.setState({
      hasNonStandard: true,
      nonStandLoading: false
    })
    this.cleanStore();
    this.getOfsInfoList();
    this.getOfsInfoRightMenu();
    this.getOfsInfoCondition();
  };

  @action setHRMNetworkListVisible = (bool) => {
    this.setState({
      HRMNetworkIPListVisible: bool
    })
  }

  @action setState = (params = {}) => {
    let status = { ...this.status };
    Object.keys(params).forEach(key => {
      status[key] = params[key];
    });
    this.status = status;
  };

  // 操作人原始值
  OfsHrmResourceTransfer = (params = {}, callBack = null) => {
    API.OfsHrmResourceTransfer(params).then(result => {
      if (result.status) {
        if (callBack && typeof (callBack) === "function") {
          callBack(String(result.result));
        }
      }
    })
  }

  /**异构系统 */
  @action getOfsInfoList = () => {
    this.tableStore = new TableStore();
    let params = this.searchForm ? this.searchForm.getFormParams() : {};
    API.getOfsInfoList(params).then(result => {
      if (result.status == 1) {
        if (result.ret && result.ret == "noright") {
          this.hasRight = false;
        } else {
          this.hasRight = true;
        }
        if (result.sessionkey) {
          this.tableStore.getDatas(result.sessionkey, 1);
        }
      }
      this.rightLoading = false;
    }).catch(err => {
      this.rightLoading = false;
    })
  };
  @action getOfsInfoRightMenu = (params = {}) => {
    API.getOfsInfoRightMenu(params).then(result => {
      this.setState({ rightMenus: result.rightMenus || [] });
    });
  };

  @action getOfsInfoCondition = (params = {}) => {
    this.searchForm = new WeaForm();
    API.getOfsInfoCondition(params).then(result => {
      if (result.status == 1) {
        this.setState({ condition: result.condition || [] });
        this.searchForm.initFormFields(result.condition);
      }
    });
  };

  /**流程数据 */
  @action getWorkflowList = () => {
    this.tableStore = new TableStore();
    let params = this.searchForm ? this.searchForm.getFormParams() : {};
    API.getWorkflowList(params).then(result => {
      if (result.sessionkey) {
        const getDatas = this.tableStore.getDatas.bind(this.tableStore);
        this.tableStore.getDatas = (...arg) => {
          let sorter = [{ "orderkey": "receivedate,receivetime", "sortOrder": "descend" }, { "orderkey": "createdate,createtime", "sortOrder": "descend" }];
          if (arg[3] && arg[3].column) {
            sorter = [{ "orderkey": arg[3].column.orderkey, "sortOrder": arg[3].order }];
          }
          getDatas(arg[0], arg[1], arg[2], sorter, arg[4], arg[5]);
        }
        this.tableStore.getDatas(result.sessionkey, 1);
      }
    });
  };

  @action getWorkflowRightMenu = (params) => {
    API.getWorkflowRightMenu(params).then(result => {
      this.setState({ rightMenus: result.rightMenus || [] });
    });
  };
  @action getWorkflowCondition = (params) => {
    this.searchForm = new WeaForm();
    API.getWorkflowCondition(params).then(result => {
      this.setState({ condition: result.condition || [] });
      this.searchForm.initFormFields(result.condition);
    });
  };

  /**集成日志 */
  @action getOfsLogList = () => {
    this.tableStore = new TableStore();
    let params = this.searchForm ? this.searchForm.getFormParams() : {};
    API.getOfsLogList(params).then(result => {
      if (result.sessionkey) {
        const getDatas = this.tableStore.getDatas.bind(this.tableStore);
        this.tableStore.getDatas = (...arg) => {
          let sorter = [{ "orderkey": "operatedate,operatetime", "sortOrder": "descend" }];

          if (arg[3] && arg[3].column) {
            sorter = [{ "orderkey": arg[3].column.orderkey, "sortOrder": arg[3].order }];
          }
          getDatas(arg[0], arg[1], arg[2], sorter, arg[4], arg[5]);
        }
        this.tableStore.getDatas(result.sessionkey, 1);
      }
    });
  };
  @action getOfsLogCondition = (params = {}) => {
    this.searchForm = new WeaForm();
    API.getOfsLogCondition(params).then(result => {
      this.setState({ condition: result.condition || [] });
      this.searchForm.initFormFields(result.condition);
    });
  };

  /**集成设置 */
  @action getOfsSettingForm = (params = {}, changeTab = false, callBack) => {
    this.newForm = new WeaForm();
    API.getOfsSettingForm(params).then(result => {
      if (result.status == 1) {
        let inteParamsTabDatas = [];
        result.condition && result.condition.forEach((item, index) => {
          inteParamsTabDatas.push({
            viewcondition: index,
            title: item.title || ""
          })
        })
        this.newForm.initFormFields(result.condition);
        this.setState({
          newFormCondition: result.condition || [],
        })
        if (!changeTab) {
          this.setState({
            newFormConditionItem: result.condition.length > 1 ? [result.condition[0]] : [],
            ofsSettingFormHiddenFields: result.hiddenFields,
            inteParamsTabDatas,
            inteParamsSelectedKey: 0,
          })
        } else {
          if (callBack && typeof (callBack) === "function") {
            callBack();
          }
        }
      }
    });
  };
  @action getOfsSettingOperation = (params) => {
    API.getOfsSettingOperation(params).then(result => {
      if (result.errmsgTip) {
        message.success(result.errmsgTip);
      }
      this.getOfsSettingForm({}, true, () => {
        const { inteParamsSelectedKey, newFormCondition } = toJS(this.status);
        this.setState({
          newFormConditionItem: newFormCondition.length > Number(inteParamsSelectedKey) ? [newFormCondition[Number(inteParamsSelectedKey)]] : [],
        })
      });
    });
  };
  @action getSmstemplate = (flag = false, params = {}) => {
    this.setState({ buttonLoading: true, dialogLoading: true });
    API.getSmstemplate(params).then(result => {
      this.setState({
        buttonLoading: false,
        dialogLoading: false,
        smsColumns: result.columns,
        smsDatas: result.datas,
        smsFields: result.fields
      });
      if (!flag) {
        this.setState({
          selectedRowKeys: result.datas.length ? [result.datas[0].key] : [],
          selectedRowKeysName: result.datas.length ? result.datas[0].remindType : "",
          remindContentValue: result.datas.length ? result.datas[0].remindContent : "",
          remindTypeValue: result.datas.length ? result.datas[0].remindTypeValue : ""
        })
      } else {
        const { selectedRowKeys } = this.status;
        if (selectedRowKeys && selectedRowKeys.length) {
          let key = selectedRowKeys[0];
          let item = result.datas.find(item => item.key === key);
          if (item) {
            this.setState({
              selectedRowKeysName: item.remindType || "",
              remindContentValue: item.remindContent || "",
              remindTypeValue: item.remindTypeValue || ""
            })
          }
        }
      }
    })
  }

  @action resetSmstemplate = (params = {}) => {
    API.resetSmstemplate(params).then(result => {
      if (result.status == 1) {
        message.success(getLabel('516483', '恢复默认设置成功'));
        this.getSmstemplate(true, { syscode: params.syscode || "" });
      }
    })
  }

  @action saveSmstemplate = (params = {}) => {
    API.saveSmstemplate(params).then(result => {
      if (result.status == 1) {
        message.success(getLabel('22619', '保存成功'));
        this.getSmstemplate(true, { syscode: params.syscode || "" });
      }
    })
  }

  // 自定义参数
  @action getOfsCustomDefinition = () => {
    this.setState({
      rowSelect: []
    })
    API.getOfsCustomDefinition().then(result => {
      if (result.status == 1) {
        const { datas = [], columns = [] } = result.data;
        this.setState({
          customDefinitionDatas: datas,
          customDefinitionColumns: columns,
          validator: {
            rules: {
              displayname: "required|checkUniqueDisplayName|DisplayNameDiffdanames",
              dbname: "required|checkUnique|checkUniqueLeft",
            },
            customRegister: [
              {
                name: "checkUnique",
                rules: (value, requirement, attribute) => {
                  let dbnames = this.status.customDefinitionDatas && toJS(this.status.customDefinitionDatas).map(data => data.dbname ? data.dbname.toLocaleUpperCase() : "");
                  let last = dbnames.lastIndexOf(value.trim());
                  let first = dbnames.indexOf(value.trim());
                  return last == first;
                },
                errorMessage: getLabel('523527', '数据库字段名称重复')
              },
              {
                name: 'checkUniqueLeft',
                rules: (value, requirement, attribute) => {
                  if (value == this.status.changeDBValue) {
                    let dbnames = this.status.customDefinitionDatas && toJS(this.status.customDefinitionDatas).map(data => data.displayname ? data.displayname.toLocaleUpperCase() : "");
                    dbnames.pop();
                    let isExist = dbnames.indexOf(value.trim().toLocaleUpperCase()) == -1 ? true : false;
                    return isExist;
                  }else{
                    return true
                  }          
                },
                errorMessage: getLabel('534251', '数据库字段名称与除自身字段显示名称重复')
              },
              {
                name: "checkUniqueDisplayName",
                rules: (value, requirement, attribute) => {
                  let displaynames = this.status.customDefinitionDatas && toJS(this.status.customDefinitionDatas).map(data => data.displayname ? data.displayname.trim() : "");
                  let last = displaynames.lastIndexOf(value.trim());
                  let first = displaynames.indexOf(value.trim());
                  return last == first;
                },
                errorMessage: getLabel('534171', '字段显示名称重复')
              }, {
                name: "DisplayNameDiffdanames",
                rules: (value, requirement, attribute) => {
                  if (value == this.status.changeValue) {
                    if (this.status.checkDifdbnames.indexOf(value.toLocaleUpperCase()) == -1) {
                      return true
                    } else {
                      return false;
                    }
                  }
                  return true;
                },
                errorMessage: getLabel('534172', '字段显示名称与除自身数据库字段名称重复')
              }
            ]
          },
          dbnameCells: {
            dbname: {
              com: [{
                key: "dbname",
                regExp: "^[a-zA-Z][a-zA-Z0-9_]*$",
                type: "INPUT",
                hasBorder: true,
                viewAttr: 1,
              }]
            }
          }
        })
      }
    })
  }

  @action saveOfsCustomDefinition = (params = {}, callback = null) => {
    API.saveOfsCustomDefinition(params).then(result => {
      if (result.status == 1) {
        if (params.operate === "save") {
          message.success(getLabel('22619', '保存成功'));
          this.getOfsCustomDefinition();
        } else if (params.operate === "delete") {
          message.success(getLabel('20461', '删除成功'));
          if (callback && typeof (callback) === "function") {
            callback();
          }
        }

      }
    })
  }

  // 流程注册
  @action getWorkflowViewFormEdit = (params = {}) => {
    this.newForm2 = new WeaForm();
    API.getWorkflowViewFormEdit(params).then(result => {
      if (result.status == 1) {
        this.setState({
          newForm2Condition: result.condition || []
        })
        this.newForm2.initFormFields(result.condition);
      }
    })
  }


  getWorkflowViewForm = (params, title = "") => {
    this.newForm2 = new WeaForm();
    API.getWorkflowViewForm(params).then(result => {
      if (result.status == 1) {
        this.setState({
          newForm2Condition: result.condition || []
        })
        this.newForm2.initFormFields(result.condition);
        this.status.WorkflowViewFormDialogVisible = true;
        this.status.onlyRead = true;
        this.status.operateIndex = params.id || "";
      } else if (result.status == -1) {
        this.confirmDeleteInfo(title);
      }
    });
  };

  getWorkflowOperation = (params, callback) => {
    API.getWorkflowOperation(params).then(result => {
      if (!callback) {
        if (result.errmsgTip) {
          message.success(result.errmsgTip);
        }
      }
      if (this.status.ofsInfoEditDetailDialogVisible) {
        this.getOfsInfoWorkflowList({ sysid: params.sysid });
      } else {
        this.getWorkflowList();
      }
      isFunction(callback) && callback(result);
    });
  };

  ReceiveRequestInfoByJson = (params = {}, callback = null) => {
    let createTime = (params.createtime && params.createtime.split(':') && params.createtime.split(':').length == 3) ? params.createtime : `${params.createtime}:00`,
      receiveTime = (params.receivetime && params.receivetime.split(':') && params.receivetime.split(':').length == 3) ? params.receivetime : `${params.receivetime}:00`;
    API.OfsDataOperation({
      ...params,
      isauto: "-1",
      createdatetime: `${params.createdate} ${createTime}`,
      receivedatetime: `${params.receivedate} ${receiveTime}`,
    }).then(result => {
      if (result) {
        if (result.operResult == "0") {
          message.warning(result.message);
        } else {
          message.success(result.message);
          if (this.status.ofsInfoEditDetailDialogVisible) {
            this.getOfsInfoWorkflowList({ sysid: params.sysid });
          } else {
            this.getWorkflowList();
          }
          if (callback && typeof (callback) === "function") {
            callback();
          }
        }
      }
    })
  }

  @action
  getOfsInfoAddForm = (params = {}, callBack = null) => {
    this.ofsInfoAddForm = new WeaForm();
    API.getOfsInfoAddForm(params).then(result => {
      // result.condition[0].items[16].max = 9999.99;
      // result.condition[0].items[16].min = -999.99;
      if (result.status == "1") {
        this.setState({
          ofsInfoAddFormHiddenFields: result.hiddenFields,
          ofsInfoAddFormCondition: result.condition || [],
          networkIPColumnsSet: result.networkIPColumnsSet,
          networkIPData: result.networkIPData || [],
        })
        this.ofsInfoAddForm.initFormFields(result.condition);
        this.handleCondition({
          condition: result.condition,
          func: 'handlelfCondition'
        });
        if (callBack && typeof (callBack) === "function") {
          callBack();
        }
      }
    });
  };

  @action
  handleCondition = (params = {}) => {
    const {
      condition,
      func
    } = params;
    this.setState({ automaticLogin: [] });
    condition[0].items.forEach(item => {
      const key = item.domkey[0];
      this[func]({
        key,
        item,
      })
    });
  }

  @action
  handlelfCondition = (params) => {
    const {
      key,
      item,
    } = params;

    if (['autologinflag', 'ipaddress'].includes(key)) {
      this.status.automaticLogin.push(item);
    }
  }

  getOfsInfoOperation = (params = {}, callback) => {
    API.getOfsInfoOperation(params).then(result => {
      if (result.status == 1) {
        if ("delete" == params.operation) {
          message.success(getLabel('20461', '删除成功'));
        } else {
          message.success(getLabel('22619', '保存成功'));
          // this.setState({ editwftype: result.onlyview })
        }
        this.getOfsInfoList();
        this.status.ofsInfoAddFormDialogVisible = false;
        isFunction(callback) && callback(result);
      }
    });
  };
  getOfsInfoLogList = (p = {}) => {
    this.tableStore_ofsInfoLog = new TableStore();
    let searchParams = (this.searchForm_ofsInfoLog && this.searchForm_ofsInfoLog.getFormParams()) || {};
    let params = Object.assign(searchParams, p);
    API.getOfsInfoLogList(params).then(result => {
      if (result.sessionkey) {
        const getDatas = this.tableStore_ofsInfoLog.getDatas.bind(this.tableStore_ofsInfoLog);
        this.tableStore_ofsInfoLog.getDatas = (...arg) => {
          let sorter = [{ "orderkey": "operatedate,operatetime", "sortOrder": "descend" }];

          if (arg[3] && arg[3].column) {
            sorter = [{ "orderkey": arg[3].column.orderkey, "sortOrder": arg[3].order }];
          }
          getDatas(arg[0], arg[1], arg[2], sorter, arg[4], arg[5]);
        }

        this.tableStore_ofsInfoLog.getDatas(result.sessionkey, 1);
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };
  getOfsInfoLogRightMenu = (params) => {
    // API.getOfsInfoLogRightMenu(params).then(result => {
    // });
  };
  getOfsInfoLogCondition = (params) => {
    this.searchForm_ofsInfoLog = new WeaForm();
    API.getOfsInfoLogCondition(params).then(result => {
      this.status = { ...this.status, condition_ofsInfoLog: result.condition };
      this.searchForm_ofsInfoLog.initFormFields(result.condition);
    });
  };

  getOfsInfoWorkflowList = (p = {}) => {
    let params = Object.assign(p, (this.searchForm_ofsInfoWorkflow && this.searchForm_ofsInfoWorkflow.getFormParams()) || {});
    API.getOfsInfoWorkflowList(params).then(result => {
      this.tableStore_ofsInfoWorkflow = new TableStore();
      if (result.sessionkey) {
        const getDatas = this.tableStore_ofsInfoWorkflow.getDatas.bind(this.tableStore_ofsInfoWorkflow);
        this.tableStore_ofsInfoWorkflow.getDatas = (...arg) => {
          let sorter = [{ "orderkey": "receivedate,receivetime", "sortOrder": "descend" }, { "orderkey": "createdate,createtime", "sortOrder": "descend" }];

          if (arg[3] && arg[3].column) {
            sorter = [{ "orderkey": arg[3].column.orderkey, "sortOrder": arg[3].order }];
          }
          getDatas(arg[0], arg[1], arg[2], sorter, arg[4], arg[5]);
        }
        this.tableStore_ofsInfoWorkflow.getDatas(result.sessionkey, 1);
        this.setState({ rowSelectIds_ofsInfoWorkflow: [] })
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });
  };
  getOfsInfoWorkflowRightMenu = (params) => {
    API.getOfsInfoWorkflowRightMenu(params).then(result => {
      this.status = { ...this.status, rightMenus_ofsInfoWorkflow: result.rightMenus };
    });
  };
  getOfsInfoWorkflowCondition = (params) => {
    this.searchForm_ofsInfoWorkflow = new WeaForm();
    API.getOfsInfoWorkflowCondition(params).then(result => {
      this.status = { ...this.status, condition_ofsInfoWorkflow: result.condition };
      this.searchForm_ofsInfoWorkflow.initFormFields(result.condition);
    });
  };
  getOfsInfoWorkflowTypeList = (p) => {
    p = p ? p : {};
    let params = Object.assign(p, (this.searchForm_ofsInfoWorkflowType && this.searchForm_ofsInfoWorkflowType.getFormParams()) || {});
    API.getOfsInfoWorkflowTypeList(params).then(result => {
      if (result.sessionkey) {
        this.tableStore_ofsInfoWorkflowType.getDatas(result.sessionkey, 1);
        this.setState({ rowSelectIds_ofsInfoWorkflowType: [], editwftype: result.onlyview })
      } else {
        this.status = { ...this.status, isAlertPage: true };
      }
    });

  };
  getOfsInfoWorkflowTypeRightMenu = (params) => {
    API.getOfsInfoWorkflowTypeRightMenu(params).then(result => {
      this.status = { ...this.status, rightMenus_ofsInfoWorkflowType: result.rightMenus };
    });
  };
  getOfsInfoWorkflowTypeCondition = (params) => {
    this.searchForm_ofsInfoWorkflowType = new WeaForm();
    API.getOfsInfoWorkflowTypeCondition(params).then(result => {
      this.status = { ...this.status, condition_ofsInfoWorkflowType: result.condition };
      this.searchForm_ofsInfoWorkflowType.initFormFields(result.condition);
    });
  };
  getOfsInfoWorkflowTypeEditForm = (params) => {
    this.ofsInfoWorkflowTypeEditForm = new WeaForm();
    this.ofsInfoWorkflowTypeEditFormOrg = new WeaForm();
    API.getOfsInfoWorkflowTypeEditForm(params).then(result => {
      result.condition[0].items[3]['helpfulTip'] = getLabel('533157', '只有设置新建流程地址后，才允许在OA中新建对应的异构系统流程，创建人范围方可生效。');
      result.condition[0].items[4]['helpfulTip'] = getLabel('533157', '只有设置新建流程地址后，才允许在OA中新建对应的异构系统流程，创建人范围方可生效。');
      this.ofsInfoWorkflowTypeEditForm.setCondition(result.condition);
      this.ofsInfoWorkflowTypeEditFormOrg.setCondition(result.condition);
      this.status.ofsInfoWorkflowTypeEditFormHiddenFields = result.hiddenFields;
      this.setState({
        OfsInfoEditWorkflowTypeSpin: false,
      })

    });

  };
  getOfsInfoWorkflowTypeOperation = (params, callback) => {
    API.getOfsInfoWorkflowTypeOperation(params).then(result => {
      if (!callback) {
        if (result.errmsgTip) {
          message.success(result.errmsgTip);
        }
      }
      this.getOfsInfoWorkflowTypeList(params);
      isFunction(callback) && callback(result);
    });
  };

  getNetworkIPColumnsSet = () => {
    API.getNetworkIPColumnsSet().then(result => {
      if (result.status == '1') {
        this.status.networkIPColumnsSet = result.networkIPColumnsSet;
        this.dialog.hide();
      }
    })
  }

  confirmModal = (content, func, val) => {
    //确认信息， 方法， 方法参数
    Modal.confirm({
      title: `${getLabel(131329, '信息确认')}`,
      content: content,
      okText: `${getLabel(16631, '确定')}`,
      cancelText: `${getLabel(201, '取消')}`,
      onOk: () => {
        func(val), this.setState({ rowSelectIds: [] })
      },
    })
  };

  openNetworkSegmentStrategy = () => {
    this.dialog = WeaTools.createDialog({
      title: getLabel(83726, '网段策略'),
      moduleName: 'hrm',
      url: `${window.ecologyContentPath || ""}/spa/hrm/engine.html#/hrmengine/securitySetting?single=1&type=network`,
      style: {
        width: 820,
        height: 650
      },
      callback: (datas) => { },
      onCancel: () => { },
      moreBtn: {
        collectParams: []
      },
      buttons: []
    });
    this.dialog.show();
  }

  confirmDeleteInfo = (text) => {
    setModal(`【${text}】${getLabel('510374', '已被删除')}`);
  }
  //注册流程类型保存并进入详细设置
  saveAndIntoDetail = () => {
    this.setState({ Tabkey: '1', Notab: false, changeButton: [] })
    this.getEditWorkflowTypeList('1')
  }
  //获取编辑流程类型弹窗的list数据
  @action getEditWorkflowTypeList = (v) => {
    if (v == '1') {
      this.tableStore4 = new TableStore()
      let params
      this.setState({ tableCheck: [] })
      if (this.status.onlyview == '0') {
        params = {
          workflowid: this.status.workflowid,
          operate: 'getShare'
        }
      } else {
        params = {
          workflowid: this.status.workflowid,
          operate: 'getShare',
          onlyview: 1
        }
      }
      API.getofsWorkflowShareList(params).then(result => {
        this.tableStore4.getDatas(result.sessionkey, 1)
      }
      );
      this.getRightButton([]);
      if (v = 1 && this.status.onlyview == 1) {
        this.setState({ Btn: [] })
      }
    } else {
      this.setState({ Btn: [] })
    }
  }

  getRightButton = (flag) => {
    const tableCheckFlag = toJS(this.status.tableCheck);
    if (flag.length == 0) {
      this.setState({
        Btn: [
          <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@sq5up1@TodoCenteradd`} buttonType="add" type="primary" onClick={() => this.getAddObjectDialogForm('getAddShareForm')} />,
          <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@lp463b@TodoCenterdel`} buttonType="del" type="primary" disabled={true} onClick={this.openDelObjectDialog} />
        ]
      })
    } else {
      this.setState({
        Btn: [
          <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@sq5up1@TodoCenteradd`} buttonType="add" type="primary" onClick={() => this.getAddObjectDialogForm('getAddShareForm')} />,
          <WeaButtonIcon ecId={`${this && this.props && this.props.ecId || ''}_WeaButtonIcon@lp463b@TodoCenterdel`} buttonType="del" type="primary" disabled={false} onClick={this.openDelObjectDialog} />
        ]
      })
    }

  }

  //编辑流程类型弹窗tab右侧删除按钮(第二个函数就是删除接口函数)
  openDelObjectDialog = () => {
    this.setState({ delObjectVisible: true })
    doConfirm(getLabel(15097, '确定要删除吗？'), this.delShareTableData, { operation: 'delete', });
  }

  //删除调用
  delShareTableData = () => {
    API.getofsWorkflowShareForm({ operate: 'delShare', workflowid: this.status.workflowid, del: this.status.tableCheck }).then(data => {
      data.status == '1' && this.getEditWorkflowTypeList('1')
    }
    )
  }


  //此处请求添加对象弹窗的Form数据
  @observable AddObjectDialogFormField = [];
  @action getAddObjectDialogForm = (type) => {
    let Formdata = this.AddObjectDialogForm.getFormParams();
    let params = {};
    if (type == 'addShare') {
      params = {
        workflowid: this.status.workflowid,
        operate: 'addShare',
        ...Formdata
      }
      this.AddObjectDialogForm.validateForm().then(f => {
        if (f.isValid) {
          API.getofsWorkflowShareForm(params).then(data => {
            data.status == '1' && this.setState({ addObjectVisible: false });
            this.getEditWorkflowTypeList('1')
          })
        } else {
          f.showErrors();
        }
      }
      )
    }
    if (type == 'getAddShareForm') {
      this.AddObjectDialogForm = new WeaForm();
      params = {
        workflowid: this.status.workflowid,
        operate: 'getAddShareForm'
      }
      this.setState({ addObjectVisible: true });
      API.getofsWorkflowShareForm(params).then(data => {
        this.AddObjectDialogFormField = data.condition;
        this.AddObjectDialogForm.initFormFields(this.AddObjectDialogFormField)
      })
    }
  }

  //添加对象弹窗的关闭操作调用
  onCancelHandle = () => {
    this.setState({ addObjectVisible: false })
  }
  //#region  OfsInfoEditWorkflowType中部分方法主要公共使用 现调整到store中
  @action onRightMenuClick = (type) => {
    const { ofsInfoWorkflowTypeEditFormHiddenFields, Tabkey, Notab, changeButton, onlyview } = toJS(this.status);
    if (Tabkey != '1') {
      if (type == 'BTN_SAVE') {
        this.setState({ Tabkey: '0' })
        this.ofsInfoWorkflowTypeEditForm.validateForm().then(f => {
          if (f.isValid) {
            if (this.status.Notab == true && this.ofsInfoWorkflowTypeEditFormOrg.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, '') != this.ofsInfoWorkflowTypeEditForm.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, '')) {
              let checkParams = {
                tableName: 'Ofs_workflow',
                fieldName: 'workflowname',
                fieldValue: this.ofsInfoWorkflowTypeEditForm.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, ''),
                idName: 'workflowid',
                idValue: status.operateIndex,
                sysid: ofsInfoWorkflowTypeEditFormHiddenFields.sysid || ""
              };
              this.checkUniquenew(checkParams, this.ofsInfoWorkflowTypeEditForm, "workflowname", "7", "", this.saveWorkflowType);
            } else {
              let checkParams = {
                tableName: 'Ofs_workflow',
                fieldName: 'workflowname',
                fieldValue: this.ofsInfoWorkflowTypeEditForm.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, ''),
                idName: 'workflowid',
                idValue: status.operateIndex,
                sysid: ofsInfoWorkflowTypeEditFormHiddenFields.sysid || ""
              };
              if (this.ofsInfoWorkflowTypeEditFormOrg.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, '') != this.ofsInfoWorkflowTypeEditForm.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, '')) {
                if (this.checkUniquenew(checkParams, this.ofsInfoWorkflowTypeEditForm, "workflowname", "7", "")) {
                  this.saveWorkflowType();
                }
              } else {
                this.saveWorkflowType();
              }
            }
          } else {
            f.showErrors();
          }
        });
        this.setState({ onlyview: 0 })
      } if (type == 'BTN_SAVE_INFO') {
        this.ofsInfoWorkflowTypeEditForm.validateForm().then(f => {
          if (f.isValid) {
            if (this.ofsInfoWorkflowTypeEditFormOrg.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, '') != this.ofsInfoWorkflowTypeEditForm.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, '')) {
              let checkParams = {
                tableName: 'Ofs_workflow',
                fieldName: 'workflowname',
                fieldValue: this.ofsInfoWorkflowTypeEditForm.getFormParams().workflowname.replace(/^(\s*)|(\s*)$/g, ''),
                idName: 'workflowid',
                idValue: status.operateIndex,
                sysid: ofsInfoWorkflowTypeEditFormHiddenFields.sysid || ""
              };
              this.checkUniquenew(checkParams, this.ofsInfoWorkflowTypeEditForm, "workflowname", "7", "", this.saveWorkflowType, 'BTN_SAVE_INFO');
            } else {
              this.saveWorkflowType('BTN_SAVE_INFO');
            }
          } else {
            f.showErrors();
          }
        });
      }
    } else {
      this.setState({ ofsInfoEditWorkflowTypeDialogVisible: false })
      this.closeDialog()
      return
    }
  }

  @action saveWorkflowType = (type) => {
    const { ofsInfoWorkflowTypeEditFormHiddenFields, workflowid } = toJS(this.status);
    let params = Object.assign(ofsInfoWorkflowTypeEditFormHiddenFields, this.ofsInfoWorkflowTypeEditForm.getFormParams());
    this.getOfsInfoWorkflowTypeOperation(params, (result) => {
      this.setState({ workflowid: result.id })
      if (result && result.errorMsg) {
        message.error(result.errorMsg);
        return;
      } else if (result && result.status == '1') {
        if (type == 'BTN_SAVE_INFO') {
          this.setState({ ofsInfoEditWorkflowTypeDialogVisible: true })
          this.setState({ Tabkey: '1', Notab: false, changeButton: [], operateIndex: '编辑' })
          this.ofsInfoWorkflowTypeEditFormOrg.updateFields({ 'workflowname': this.ofsInfoWorkflowTypeEditForm.getFormParams().workflowname })
          this.getEditWorkflowTypeList('1')
        } else {
          this.setState({ ofsInfoEditWorkflowTypeDialogVisible: false })
        }
      }
    })
  }

  checkUniquenew = (checkParams, form, key, name = "1", operateIndex = "", saveCallBack, params = {}, errorback) => {
    const { Tabkey, Notab, changeButton } = toJS(this.status);
    checkTableFieldValueUnique(checkParams).then(result => {
      if (result && result.isNotUnique && operateIndex == "") {
        let title = "";
        if (name == 1) {
          title = getLabel('129943', '名称已存在');
        } else if (name == 2) {
          title = getLabel('387654', '标识已存在');
        } else if (name == 3) {
          title = getLabel('513558', '路径已存在');
        } else if (name == 4) {
          title = getLabel('513568', '地址已存在');
        } else if (name == 5) {
          title = getLabel('504645', '简称已存在');
        } else if (name == 6) {
          title = getLabel('504643', '全称已存在');
        } else if (name == 7) {
          title = getLabel('514192', '流程类型已存在');
        } else if (name == 8) {
          title = getLabel('126042', '主键字段已存在');
        }
        form.showError(key, title);
        if (errorback && typeof (errorback) === "function") {
          errorback();
        }
        return false
      } else {
        if (saveCallBack && typeof (saveCallBack) === "function" && result.isNotUnique == false) {
          saveCallBack(params);
          return true
        }
      }
    })
  }
  //#endregion

}
