import { observable, action, computed } from "mobx";
import {
  WeaRightMenu,
  WeaHelpfulTip,
  WeaNewScroll,
  WeaTools,
  WeaSelect
} from "ecCom";
import { WeaForm, WeaTableNew, WeaSwitch } from "comsMobx";
import { Button, message, Modal } from "antd";
import Tabs from "../coms/Tabs";
import FormInfo from "../coms/FormInfo";
import HrmBaseStore from "./baseStore";
import * as api from "../apis/workflow";
import { i18n } from "../public/i18n";
import { indexOf, cloneDeep, findIndex, remove } from "lodash";
import find from "lodash/find";
import isEmpty from "lodash/isEmpty";
import get from "lodash/get";
import difference from "lodash/difference";
import filter from "lodash/filter";

import EntrySelect from "../components/workflowSetting/EntrySelect";
import {addContentPath} from '../util/index.js'
const { TableStore } = WeaTableNew;

const confirm = Modal.confirm;

class HrmWorkflowSetting extends HrmBaseStore {
  constructor() {
    super();
  }
  /********************* unobservable list *********************/
  moduleName;
  topBtnAndMenu = () => {
    return {
      btns: [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@t6tkxd`} type="primary" onClick={this.create}>
          {i18n.button.create()}
        </Button>,
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@n27grz`}
          type="primary"
          onClick={() => this.removeWF()}
          disabled={this.multiRemoveable}
        >
          {i18n.button.multiRemove()}
        </Button>
      ],
      menus: [
        {
          key: "1",
          content: i18n.button.create(),
          icon: <i className={this.menuIconCollection.create} />,
          onClick: this.create
        },
        {
          key: "2",
          content: i18n.button.multiRemove(),
          icon: <i className={this.menuIconCollection.remove} />,
          onClick: () => this.removeWF(),
          disabled: this.multiRemoveable
        },
        ...this.getBasicMenus(
          this.moduleName === "stateschedule"
            ? "HRM_ENGINE_HRM_ATT_PROCSET"
            : "HRM_ENGINE_HRM_STATE_CHANGE"
        )
      ]
    };
  };

  orgTreeProps = {
    needSearch: true,
    topPrefix: "hrmSearch",
    inputLeftDom: `<b>${i18n.label.organization()}</b>`,
    treeNodeClick: this.treeNodeClick,
    params: {
      rightStr: "StateChangeProcess:Set"
    }
  };

  attendanceOrgTreeProps = {
    ...this.orgTreeProps,
    params: {
      rightStr: "HrmAttendanceProcess:setting"
    }
  };

  tabConfig = {
    tabs: [
      {
        color: "#000000",
        groupId: "roleList",
        title: "",
        viewCondition: "1",
        searchType: ["base", "advanced"],
        searchKey: "field001",
        doSearch: params => this.getTableData(params)
      }
    ],
    keyParam: "viewCondition",
    activeTabKey: "1"
  };

  editTabConfig = {
    tabs: [
      {
        color: "#000000",
        groupId: "info",
        title: "流程概览",
        viewCondition: "1"
      },
      {
        color: "#000000",
        groupId: "field",
        title: "字段对应",
        viewCondition: "2"
      },
      {
        color: "#000000",
        groupId: "actionSetting",
        title: "动作设置",
        viewCondition: "3"
      }
    ],
    keyParam: "viewCondition",
    activeTabKey: "1"
  };

  generateFormFields = [
    {
      title: i18n.label.basicSetting(),
      items: [
        {
          colSpan: 2,
          conditionType: "INPUT",
          domkey: ["formName"],
          fieldcol: 12,
          isQuickSearch: false,
          label: i18n.label.formName(),
          labelcol: 6,
          precision: 0,
          rules: "required|string",
          value: "",
          viewAttr: 3
        }
      ],
      defaultshow: true
    }
  ];

  wfFormItemRender = {
    field001: (field, textAreaProps, form, formParams) => {
      return (
        <div className="browser">
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@agmjye`}
            fieldConfig={{
              ...field,
              ...textAreaProps,
              addOnClick: values => this.callAddPath(values)
            }}
            form={form}
            formParams={formParams}
            onChange={this.onWfChange}
          />
        </div>
      );
    },
    field002: (field, textAreaProps, form, formParams) => {
      return (
        <div>
          <div className="browser">
            <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@vt0di4`}
              fieldConfig={{
                ...field,
                ...textAreaProps,
                helpfulTip: "",
                addOnClick: values => this.callAddForm(values)
              }}
              form={form}
              formParams={formParams}
            />
          </div>
          <a className="autoGen" onClick={this.createForm}>
            {i18n.button.autoGenerate()}
          </a>
          <span className="tips">
            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@x27km7`} title={field.helpfulTip} />
          </span>
        </div>
      );
    },
    field004: (field, textAreaProps, form, formParams) => {
      return (
        <div className="browser">
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@0f6wm4`}
            fieldConfig={{ ...field, ...textAreaProps }}
            form={form}
            formParams={formParams}
          />
        </div>
      );
    },
    field006: (field, textAreaProps, form, formParams) => {
      return (
        <div className="browser">
          <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@poc47a`}
            fieldConfig={{ ...field, ...textAreaProps }}
            form={form}
            formParams={formParams}
          />
        </div>
      );
    }
  };

  editorDialogRightMenu = [];
  getDialogOpButtons = () => {
    let buttons = [];
    this.editorDialogRightMenu.length = 0;
    switch (this.dialogParams.opType) {
      case "":
        buttons.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h90ewu`} type="primary" op="save" onClick={() => this.saveWf()}>
            {i18n.button.save()}
          </Button>
        );
        buttons.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1u58fr`} type="primary" op="entry" onClick={() => this.saveWf(true)}>
            {i18n.button.saveAndSetting()}
          </Button>
        );
        break;
      case "showContent":
        buttons.push(
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@5i7zly`} type="primary" op="save" onClick={() => this.save()}>
            {i18n.button.save()}
          </Button>
        );
        break;
    }

    buttons.map((btn, index) => {
      const { props } = btn;
      this.editorDialogRightMenu.push({
        key: index.toString(),
        content: props.children,
        icon: <i className={this.menuIconCollection[props.op]} />,
        onClick: props.onClick
      });
    });

    this.dialogParams.moreBtn.datas = this.editorDialogRightMenu;
    return buttons;
  };

  autoGenDialogRightMenu = [];
  getAutoGenDialogOpButtons = () => {
    let buttons = [];
    this.autoGenDialogRightMenu.length = 0;
    buttons.push(
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@cnweaf`}
        type="primary"
        op="save"
        onClick={() => this.dispatchAutoGenForm()}
      >
        {i18n.button.save()}
      </Button>
    );

    buttons.map((btn, index) => {
      const { props } = btn;
      this.autoGenDialogRightMenu.push({
        key: index.toString(),
        content: props.children,
        icon: <i className={this.menuIconCollection[props.op]} />,
        onClick: props.onClick
      });
    });

    this.generateFormDialogParams.moreBtn.datas = this.autoGenDialogRightMenu;
    return buttons;
  };

  wfFormFields;
  selectedSubCompany;
  tableEditDatas;

  needRender = ["field005", "field006", "field007"];
  renderCol = {};
  browsers = [];
  /********************* unobservable list *********************/

  /********************* dialog info setting *********************/

  /********************* dialog info setting *********************/

  /********************* observable list *********************/
  @observable table = new TableStore();
  @observable spinning = false;

  @observable isEntry = false;
  dialogParams = {
    ...this.dialogPropsDef,
    opType: "",
    onCancel: () => {
      this.dialogParams.opType = "";
      this.dialogParams.visible = false;
      this.opId = null;
    }
  };

  @observable generateFormDialogParams = {
    ...this.dialogPropsDef,
    onCancel: () => {
      this.generateFormDialogParams.visible = false;
    }
  };

  @observable tableConfig = {
    ...this.editTableConfig,
    showTitle: false,
    draggable: false,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    columns: [],
    datas: [],
    selectedData: {},
    getRowSelection: rowSelection => {
      return null;
    },
    onChange: data => {
      this.tableEditDatas = data;
      this.tableConfig.datas = this.convertData(data, true);
    }
  };

  @observable refreshMainTab = new Date().getTime();
  @observable refreshTab = new Date().getTime();
  /********************* observable list *********************/

  /********************* computed list *********************/
  @computed get multiRemoveable() {
    return this.table.selectedRowKeys.length === 0;
  }
  /********************* computed list *********************/

  /********************* action list *********************/
  clearParams = () => {
    this.selectedSubCompany = null;
    this.opId = null;
  };

  initData = moduleName => {
    this.clearParams();
    this.moduleName = moduleName;
    this.containerInitFinished = {
      ...this.containerInitFinished,
      init: true
    };
    api.initModuleData(moduleName).then(rs => {
      rs.map((result, index) => {
        if (result.status === "1") {
          switch (index) {
            case 0:
              this.wfFormFields = result.condition;
              this.setFormData("wfForm", result.condition);
              break;
            case 1:
              this.setFormData("conditionForm", result.conditions);
              if (this.formTarget.conditionForm.isFormInit) {
                this.refreshMainTab = new Date().getTime();
                this.getTableData();
              }
              break;
          }
        }
      });
    });
  };

  @action treeNodeClick = (event, ids, nodeids, nodes) => {
    this.formTarget.conditionForm.resetForm();
    const { data: nodeData } = event.node.props;
    this.selectedSubCompany = nodeData;
    this.formTarget.conditionForm.updateFields({
      subcompanyid: {
        value: nodeData.id.toString(),
        valueSpan: nodeData.name,
        valueObj: [
          {
            id: nodeData.id.toString(),
            name: nodeData.name
          }
        ]
      }
    });
    this.getTableData();
  };

  getTableData = params => {
    this.table = new TableStore();
    if (params == null)
      params = { ...this.formTarget.conditionForm.getFormParams() };
    // this.selectedSubCompany != null && Object.assign(params, {
    // 	subcompanyid: this.selectedSubCompany.id,
    // })
    api.getWorkflowList(this.moduleName, params).then(
      data => {
        if (data.status === "1") this.table.getDatas(data.sessionkey, 1);
        else message.error(data.message);
      },
      error => {}
    );
  };

  getFormData = params => {
    api.getFormInfo(this.moduleName, params).then(data => {
      if (data.status === "1") {
        this.setFormData("wfForm", data.condition);
        this.refreshTab = new Date().getTime();
        this.dialogParams.visible = true;
      } else message.error(data.message);
    });
  };

  @action create = () => {
    const f = cloneDeep(this.wfFormFields);
    this.selectedSubCompany != null &&
      f.map(g => {
        g.items.map(item => {
          if (item.domkey[0] === "field004") {
            item.browserConditionParam.replaceDatas = [
              {
                id: this.selectedSubCompany.id,
                name: this.selectedSubCompany.name
              }
            ];
          }
        });
      });
    this.setFormData("wfForm", f);
    if (this.formTarget.wfForm.isFormInit) {
      this.dialogParams.title =
        this.moduleName === "statechange"
          ? i18n.label.createStateChangeWf()
          : i18n.label.createStatesSchedule();
      this.dialogParams.style = {
        width: 600,
        height: 260
      };
      this.dialogParams.coms = (
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@yk6t69`} height={"100%"}>
          <FormInfo ecId={`${this && this.props && this.props.ecId || ''}_FormInfo@o3seh4`}
            menu={this.editorDialogRightMenu}
            form={this.formTarget.wfForm}
            formFields={this.formTarget.wfFormFields}
            itemRender={this.wfFormItemRender}
          />
        </WeaNewScroll>
      );
      this.dialogParams.visible = true;
    }
  };

  @action createForm = () => {
    const formParams = this.formTarget.wfForm.getFormParams();
    let typeLabel = this.formTarget.wfForm.fieldMap.field006.label;
    let options = this.formTarget.wfForm.fieldMap.field006.options;
    if (formParams.field006 == null || formParams.field006 === "") {
      message.error(`${i18n.message.plsSelect()}"${typeLabel}"!`);
      return;
    }
    let formTemp =
      options[
        findIndex(options, {
          key: formParams.field006
        })
      ].showname;
    let arr =
      this.moduleName === "statechange" ? ["2", "4", "5"] : ["0", "1", "2"];
    if (indexOf(arr, formParams.field006) < 0) {
      message.error(`"${formTemp}"${i18n.message.autoGenFormFaild()}`);
      return;
    }

    let content = i18n.confirm.checkGenForm();
    content = content.replace("{param}", `"${formTemp}"`);
    this.confirmInfo({
      content,
      onOk: () => {
        this.setFormData("autoGenForm", this.generateFormFields);
        if (this.formTarget.autoGenForm.isFormInit) {
          this.generateFormDialogParams.title = i18n.label.plsSetFormName();
          this.generateFormDialogParams.style = {
            height: 90
          };
          this.generateFormDialogParams.visible = true;
        }
      }
    });
  };

  @action callAddPath = values => {
    const formParams = this.formTarget.wfForm.getFormParams();
    let url =
      "/spa/workflow/static4engine/engine.html#/main/workflowengine/path/addContent?isRoute=true";
    if (formParams.field002 != null && formParams.field002 != "") {
      url += `&formId=${formParams.field002}`;
    }
    const dialog = WeaTools.createDialog({
      title: i18n.label.createWorkflow(),
      moduleName: "workflow",
      url:addContentPath(url),
      style: {
        width: 600,
        height: 600
      },
      callback: datas => {
        this.formTarget.wfForm.updateFields({
          field001: {
            value: datas.id.toString(),
            valueSpan: datas.name,
            valueObj: [
              {
                id: datas.id.toString(),
                name: datas.name
              }
            ]
          }
        });
        this.getFormInfoByWorkflow(datas.id);
      },
      onCancel: () => {}
    });
    dialog.show();
  };

  @action callAddForm = () => {
    let url =
      "/spa/workflow/static4engine/engine.html#/main/workflowengine/form/formSet/addForm?isRoute=true";
    const dialog = WeaTools.createDialog({
      title: i18n.label.createForm(),
      moduleName: "workflow",
      url:addContentPath(url),
      style: {
        width: 600,
        height: 600
      },
      callback: datas => {
        this.formTarget.wfForm.updateFields({
          field002: {
            value: datas.id.toString(),
            valueSpan: datas.name,
            valueObj: [
              {
                id: datas.id.toString(),
                name: datas.name
              }
            ]
          }
        });
        if (datas.inDetail) {
          this.callSetFomDetail(datas.id);
        }
      },
      onCancel: () => {}
    });
    dialog.show();
  };

  @action callSetFomDetail = formId => {
    let url = `/spa/workflow/static4engine/engine.html#/main/workflowengine/form/formSet/edidForm?formId=${formId}&isBill=1`;
    const dialog = WeaTools.createDialog({
      title: "表单详细设置",
      moduleName: "workflow",
      url:addContentPath(url),
      style: {
        width: 600,
        height: 600
      },
      callback: datas => {},
      onCancel: () => {}
    });
    dialog.show();
  };

  dispatchAutoGenForm = () => {
    const formParams = this.formTarget.wfForm.getFormParams();
    let params = {
      field006: formParams.field006
    };
    this.formTarget.autoGenForm.validateForm().then(f => {
      if (f.isValid) {
        Object.assign(params, this.formTarget.autoGenForm.getFormParams());
        this.selectedSubCompany != null &&
          Object.assign(params, {
            subcompanyid: this.selectedSubCompany.id
          });
        api.createForm(this.moduleName, params).then(
          data => {
            if (data.status === "1") {
              this.generateFormDialogParams.onCancel();
              this.formTarget.wfForm.updateFields({
                field002: {
                  value: data.formId.toString(),
                  valueSpan: data.formName,
                  valueObj: [
                    {
                      id: data.formId.toString(),
                      name: data.formName
                    }
                  ]
                }
              });
            } else {
              message.error(data.message);
            }
          },
          error => {}
        );
      } else {
        f.showErrors();
        this.showError = new Date().getTime();
      }
    });
  };

  saveWf = (entry = false) => {
    const params = {};
    this.opId != null &&
      Object.assign(params, {
        id: this.opId
      });
    this.selectedSubCompany != null &&
      Object.assign(params, {
        subcompanyid: this.selectedSubCompany.id
      });
    this.formTarget.wfForm.validateForm().then(f => {
      if (f.isValid) {
        if (this.spinning) return;
        this.spinning = true;
        !entry && this.dialogParams.onCancel();
        const formParams = this.formTarget.wfForm.getFormParams();
        Object.assign(params, formParams);
        api.saveWf(this.moduleName, params).then(
          data => {
            if (data.status === "1") {
              entry &&
                this.doEdit(
                  {
                    id: data.id
                  },
                  "2",
                  formParams.field006
                );
              this.table.getDatas(null, 1);
              message.success(i18n.message.saveSuccess());
            } else message.error(data.message);
            this.spinning = false;
          },
          error => {
            this.spinning = false;
          }
        );
      } else {
        f.showErrors();
        this.showError = new Date().getTime();
      }
    });
  };

  @action setActiveTab = key => {
    this.editTabConfig.activeTabKey =
      key || this.editTabConfig.tabs[0].viewCondition;
    const tabIndex = this.getTabIndex(this.editTabConfig.tabs, key);
    if (tabIndex < 0) return;
    switch (key) {
      case "1":
        this.getFormData({
          id: this.opId,
          subcompanyid: this.selectedSubCompany
            ? this.selectedSubCompany.id
            : null
        });
        break;
      case "2":
        !this.isEntry ? this.getField() : this.initFieldList();
        break;
      case "3":
        this.tableEditDatas = null;
        this.getActionSetting();
        break;
      default:
        break;
    }
    this.refreshTab = new Date().getTime();
  };

  @action getField = () => {
    this.formTarget.fieldFormFields = [];
    this.spinning = true;
    let params = {
      id: this.opId
    };
    this.selectedSubCompany != null &&
      Object.assign(params, {
        subcompanyid: this.selectedSubCompany.id
      });
    api.getField(this.moduleName, params).then(
      data => {
        if (data.status === "1") {
          this.setFormData("fieldForm", data.condition);
          // this.refreshTab = new Date().getTime();
        } else {
          message.error(data.message);
        }
        this.spinning = false;
      },
      error => {
        this.spinning = false;
      }
    );
  };

  convertColumn = columns => {
    columns.map(col => {
      if (indexOf(this.needRender, col.dataIndex) >= 0) {
        col.useRecord = true;
        this.renderCol[col.dataIndex] = col;
      }
    });
    return columns;
  };

  convertData = (datas, onChange) => {
    datas.map((data, i) => {
      data.com = data.com || {};
      data.com["field005"] = this.renderCol["field005"].com;
      if (data.field005 === "0") {
        data.com["field006"] = this.browsers[0].com;
        data.com["field007"] = [<div />];
      } else {
        data.com["field006"] = this.browsers[1].com;
        delete data.com["field007"];
      }
      // data.com['field006'] = data.field005 === '0' ? this.browsers[0].com : this.browsers[1].com;
      // data.com['field007'] = data.field005 === '0' ? this.browsers[0].com : this.browsers[1].com;
      if (onChange && data.field005 != this.tableConfig.datas[i].field005) {
        data.field006 = "";
        data.field006span = "";
      }
    });
    return datas;
  };

  @action getActionSetting = () => {
    this.spinning = true;
    this.tableConfig.columns.length = 0;
    this.tableConfig.datas.length = 0;
    api
      .getActionSetting(this.moduleName, {
        id: this.opId
      })
      .then(
        data => {
          if (data.status === "1") {
            this.browsers = data.items[0].table.browsers;
            const columns = this.convertColumn(data.items[0].table.columns);
            const datas = this.convertData(data.items[0].table.datas);
            this.tableConfig.columns = columns;
            this.tableConfig.datas = datas;
            this.refreshTab = new Date().getTime();
          } else {
            message.error(data.message);
          }
          this.spinning = false;
        },
        error => {
          this.spinning = false;
        }
      );
  };

  doEdit = (params, key, field006) => {
    const obj = {
      id: params.id,
      topage: "content"
    };
    if (field006 < 1 && this.moduleName == 'statechange') {
      this.isEntry = true;
    } else {
      this.isEntry = false;
    }
    this.moduleName != "statechange" &&
      Object.assign(obj, {
        field006
      });
    api.getTab(this.moduleName, obj).then(
      data => {
        if (data.status === "1") {
          this.editTabConfig.tabs.length = 0;
          data.tabs.map((tab, i) => {
            this.editTabConfig.tabs.push({
              color: "#000000",
              groupId: tab.key,
              title: tab.title,
              viewCondition: (i + 1).toString()
            });
          });
          this.opId = params.id;
          this.dialogParams.title =
            this.moduleName === "statechange"
              ? i18n.label.editStateChangeWf()
              : i18n.label.editStatesSchedule();
          this.dialogParams.opType = "showContent";
          this.dialogParams.style = {
            width: 700,
            height: 500
          };
          this.setActiveTab(key);
        } else {
          message.error(data.message);
        }
      },
      error => {}
    );
  };

  @action save = () => {
    let params = {
      field001: this.opId
    };
    switch (this.editTabConfig.activeTabKey) {
      case "1":
        this.saveWf();
        break;
      case "2":
        this.saveField();
        break;
      case "3":
        this.saveAction();
        break;
    }
  };

  resetOptionsVal = domkey => {
    this.formTarget.fieldForm.updateFields({
      [domkey]: {
        value: ""
      }
    });
  };

  saveField = () => {
    if (this.spinning) return;

    if (this.isEntry) {
      this.saveEntryFields();
      //   this.entryValidate(this.dialogParams.onCancel);
    } else {
      this.formTarget.fieldForm.validateForm().then(f => {
        if (f.isValid) {
          this.spinning = true;
          let params = {
            field001: this.opId,
            ...this.formTarget.fieldForm.getFormParams()
          };
          this.selectedSubCompany != null &&
            Object.assign(params, {
              subcompanyid: this.selectedSubCompany.id
            });
          api.saveField(this.moduleName, params).then(
            data => {
              if (data.status === "1") {
                this.dialogParams.onCancel();
                message.success(i18n.message.saveSuccess());
                this.spinning = false;
              } else {
                message.error(data.message);
                this.spinning = false;
              }
            },
            error => {
              this.spinning = false;
            }
          );
        } else {
          f.showErrors();
          this.showError = new Date().getTime();
        }
      });
    }
  };

  saveAction = () => {
    if (this.spinning) return;
    this.spinning = true;
    let params = {
      field001: this.opId,
      field002: ""
    };
    const datas =
      this.tableEditDatas != null
        ? this.tableEditDatas
        : this.toJS(this.tableConfig.datas);
    datas.map(d => {
      delete d.com;
    });
    params.field002 = JSON.stringify(datas);
    api.saveActionSetting(this.moduleName, params).then(
      data => {
        if (data.status === "1") {
          this.dialogParams.onCancel();
          message.success(i18n.message.saveSuccess());
          this.spinning = false;
        } else {
          message.error(data.message);
          this.spinning = false;
        }
      },
      error => {
        this.spinning = false;
      }
    );
  };

  doChangeStatus = record => {
    let content =
      record.field005 === "1"
        ? i18n.confirm.forbidden()
        : i18n.confirm.active();
    let params = {
      id: record.id,
      field005: record.field005 === "1" ? "0" : "1"
    };
    this.confirmInfo({
      content,
      onOk: () => {
        api.changeStatus(this.moduleName, params).then(
          data => {
            if (data.status === "1") {
              message.success(i18n.message.opSuccess());
              this.table.getDatas();
            } else {
              message.error(data.message);
            }
          },
          error => {}
        );
      }
    });
  };

  removeWF = params => {
    let content;
    if (params == null) {
      params = {
        ids: this.table.selectedRowKeys
      };
      content = i18n.confirm.removeSelected();
    } else {
      content = i18n.confirm.remove();
    }
    this.confirmInfo({
      content,
      onOk: () => {
        api.removeWf(this.moduleName, params).then(data => {
          if (data.status === "1") {
            message.success(i18n.message.removeSuccess());
            this.table.getDatas(null, 1);
          }
        });
      }
    });
  };

  onWfChange = (ids, names, datas) => {
    if (names.value.length === 0) {
      this.formTarget.wfForm.updateFields({
        field002: {
          value: "",
          valueSpan: "",
          valueObj: [
            {
              id: "",
              name: ""
            }
          ]
        }
      });
    } else {
      this.getFormInfoByWorkflow(names.value);
    }
  };

  getFormInfoByWorkflow = id => {
    api
      .getFormInfoByWorkflow({
        workflowid: id
      })
      .then(
        data => {
          if (data.status === "1") {
            const { id, name } = data;
            this.formTarget.wfForm.updateFields({
              field002: {
                value: id || "",
                valueSpan: name || "",
                valueObj: [
                  {
                    id: id || "",
                    name: name || ""
                  }
                ]
              }
            });
          } else {
            message.error(data.message);
          }
        },
        error => {}
      );
  };

  @action showOpLog = logSmallType => {
    this.showLog({
      logType: "4",
      logSmallType
    });
  };
  /********************* action list *********************/

  /********************************************************************* 入职流程 *****************************************************************/
  weaErrorRef = {};

  //#region 状态监听对象
  @observable topTab;
  @observable tabSelectedKey = "-1";

  @observable _fieldKeys = {};
  @computed get fieldKeys() {
    return this.toJS(this._fieldKeys);
  }
  set fieldKeys(v) {
    this._fieldKeys = v;
  }

  @observable _optionMap = {};
  @computed get optionMap() {
    return this.toJS(this._optionMap);
  }
  set optionMap(v) {
    this._optionMap = v;
  }

  @observable _fieldsColumns = [];
  @computed get fieldsColumns() {
    return this.toJS(this._fieldsColumns);
  }
  set fieldsColumns(v) {
    this._fieldsColumns = v;
  }

  @observable _fieldsData = [];
  @computed get fieldsData() {
    return this.toJS(this._fieldsData);
  }
  set fieldsData(v) {
    this._fieldsData = v;
  }

  @observable _browserConfig = {};
  @computed get browserConfig() {
    return this.toJS(this._browserConfig);
  }
  set browserConfig(v) {
    this._browserConfig = v;
  }

  @observable _selectedRowKeys = [];
  @computed get selectedRowKeys() {
    return this.toJS(this._selectedRowKeys);
  }
  set selectedRowKeys(v) {
    this._selectedRowKeys = v;
  }

  @computed get fieldListTableProps() {
    return {
      rowKey: "id",
      showTitle: false,
      columns: this.fieldsColumns,
      datas: this.fieldsData,
      initialDatas: this.fieldsData,
      getRowSelection: this.getRowSelection,
      tableProps: { scroll: { y: 360 } },
      onRowSelect: this.onRowSelect,
      selectedRowKeys: this.selectedRowKeys
    };
  }

  @computed get fieldRemovable() {
    return this.selectedRowKeys.length == 0;
  }
  //#endregion

  //#region 初始化入职流程字段对应数据
  @action clearEntryData = () => {
    this.tabSelectedKey = "-1";
    this.selectedRowKeys = [];
    this.weaErrorRef = {};
  };

  @action initFieldList = () => {
    this.clearEntryData();
    this.getTabData();
    this.getContentData();
  };
  //#endregion

  //#region tab
  @action tabChange = key => {
    this.tabSelectedKey = key;
    this.getContentData();
  };

  @action getTabData = async () => {
    const tabData = await api.getHrmFieldTabs();
    if (tabData.status == "1") {
      this.topTab = tabData.tabs;
    } else message.error(data.message);
  };
  //#endregion

  //#region 获取tableedit数据源，下拉框数据以及字段key集合
  @action onRowSelect = selectedRowKeys =>
    (this.selectedRowKeys = selectedRowKeys);
  @action getRowSelection = rowSelection => {
    let sel = { ...rowSelection };
    sel.getCheckboxProps = record => {
      return {
        disabled: record.require
      };
    };
    return sel;
  };

  @action getHrmFieldByScope = async () => {
    const params = {
      subcompanyid: this.selectedSubCompany && this.selectedSubCompany.id,
      id: this.opId,
      scopeId: this.tabSelectedKey
    };
    this.loading = true;
    const data = await api.getHrmFieldByScope(params);
    this.loading = false;
    if (data.status == 1) {
      const { columns, datas, fieldKeys, optionMap, browserConfig } = data;
      return { columns, datas, fieldKeys, optionMap, browserConfig };
    } else {
      message.error(data.message);
      return null;
    }
  };

  @action getContentData = async () => {
    const data = await this.getHrmFieldByScope();
    this.fieldsColumns = data.columns.map((col, i) => {
      const column = { ...col };
      switch (col.dataIndex) {
        case "sysField":
          Object.assign(column, {
            com: [
              {
                type: "TEXT",
                key: col.dataIndex
              }
            ]
          });
          break;
        case "wfField":
          Object.assign(column, {
            com: [
              {
                type: "CUSTOM",
                key: col.dataIndex,
                render: (text, record, index, onEdit) => {
                  const onChange = v => {
                    this.fieldsData = this.fieldsData.map((d, i) => {
                      const data = { ...d };
                      if (i == index) Object.assign(data, { wfField: v });
                      return data;
                    });
                  };
                  return (
                    <EntrySelect ecId={`${this && this.props && this.props.ecId || ''}_EntrySelect@hdxgyu@${i}`}
                      store={this}
                      record={record}
                      onChange={onChange}
                    />
                  );
                }
              }
            ]
          });
          break;
      }
      return column;
    });
    this.fieldsData = data.datas;
    this.fieldKeys = data.fieldKeys;
    this.browserConfig = data.browserConfig.browserConditionParam;
    this.optionMap = data.optionMap;
  };
  //#endregion

  //#region 保存字段对应
  @action setRef = (id, dom) => (this.weaErrorRef[id] = dom);

  @action saveEntryFields = async () => {
    const params = {
      entry: 1,
      field001: this.opId,
      scopeId: this.tabSelectedKey
    };
    this.selectedSubCompany &&
      Object.assign(params, { subcompanyid: this.selectedSubCompany.id });

    let flag = true;
    this.fieldsData.map(data => {
      Object.assign(params, {
        [data.id]: data.wfField
      });
      let checkRs = true;
      if(data.require && isEmpty(data.wfField)){
        flag = false;
        checkRs = false;
      }
      try {
        !checkRs && get(this.weaErrorRef, data.id).showError();
      } catch (e) {}
    });

    if (flag) {
      this.spinning = true;
      const data = await api.saveField(this.moduleName, params);
      if (data.status === "1") {
        // 保存走dialog关闭，浏览按钮添加走刷新
        message.success(i18n.message.saveSuccess());
      } else {
        message.error(data.message);
      }
      this.spinning = false;
    }
  };
  //#endregion

  //#region 添加/删除字段
  requireField = ["departmentid", "jobtitle", "lastname", "sex", "locationid", "status"];
  @action browserChange = async (ids, names, datas) => {
    const newList = ids.split(",");
    const addList = filter(difference(newList, this.fieldKeys), v => v != '');
    const deleteList = filter(difference(this.fieldKeys, newList), v => v != '' && indexOf(this.requireField, v) < 0);

    if (addList.length == 0 && deleteList.length == 0) return;

    const params = {
      field001: this.opId,
      fieldkeys: this.fieldKeys,
      scopeId: this.tabSelectedKey,
      keys: ids
    };

    const data = await api.saveEntryField(params);
    if (data.status == 1) {
      let fieldKeys = this.fieldKeys,
        fieldsData = this.fieldsData,
        optionMap = this.optionMap;
      if (deleteList.length > 0) {
        // fieldKeys = filter(fieldKeys, k => deleteList.indexOf(k) < 0);
        fieldsData = filter(
          fieldsData,
          d => deleteList.indexOf(d.fieldKey) < 0
        );
        Object.keys(optionMap).map(k => {
          if (findIndex(fieldsData, { id: k }) < 0) delete optionMap[k];
        });
      }

      const data = await this.getHrmFieldByScope();
      const {
        datas: newDatas,
        optionMap: newOptionMap,
        fieldKeys: newFieldKeys
      } = data;
      if (addList.length > 0) {
        addList.map(k => {
          const newData = find(newDatas, { fieldKey: k });
          fieldsData.push(newData);
          Object.assign(optionMap, {
            [newData.id]: newOptionMap[newData.id]
          });
        });
      }else{
        // fieldKeys.push(...newFieldKeys);
        // fieldsData.push(...newDatas);
        // Object.assign(optionMap, {...newOptionMap});
      }
      this.fieldKeys = newFieldKeys;
      this.fieldsData = fieldsData;
      this.optionMap = optionMap;
      
      this.browserConfig = Object.assign(this.browserConfig, {
        replaceDatas: fieldsData.map(d => ({id: d.fieldKey, name: d.sysField}))
      });
    } else {
      message.error(data.message);
    }
  };

  @action deleteFields = async () => {
    confirm({
      content: i18n.confirm.removeSelected(),
      onOk: () => this.doDeleteFields(),
      onCancel() {}
    });
  };

  @action doDeleteFields = async () => {
    const param = {
      fieldkeys: this.selectedRowKeys.join(","),
      field001: this.opId,
      scopeId: this.tabSelectedKey
    };

    const data = await api.delEntryField(param);
    if (data.status == 1) {
      let fieldKeys = this.fieldKeys,
        fieldsData = this.fieldsData,
        optionMap = this.optionMap,
        replaceDatas = this.browserConfig.replaceDatas;
      this.selectedRowKeys.map(key => {
        const data = find(this.fieldsData, { id: key });

        fieldKeys = filter(fieldKeys, k => k != data.fieldKey);
        fieldsData = filter(fieldsData, d => d.id != key);
        replaceDatas = filter(replaceDatas, d => d.id != data.fieldKey);
        Object.keys(optionMap).map(k => {
          if (findIndex(fieldsData, { id: k }) < 0) delete optionMap[k];
        });
      });
      this.fieldKeys = fieldKeys;
      this.fieldsData = fieldsData;
      this.optionMap = optionMap;
      this.selectedRowKeys = [];
      this.browserConfig = Object.assign(this.browserConfig, {
        replaceDatas
      });
    } else {
      message.error(data.message);
    }
  };
  //#endregion
}

export const hrmWorkflowSetting = new HrmWorkflowSetting();
