import React from "react";
import { inject, observer } from "mobx-react";
import { Button, message, Modal } from "antd";
import { toJS } from "mobx";
import * as IntegrationUtil from "../../util/IntegrationUtil";
import { WeaSwitch, WeaTableNew } from "comsMobx";
import isEmpty from 'lodash/isEmpty';
import {
  WeaDialog,
  WeaFormItem,
  WeaInput,
  WeaLocaleProvider,
  WeaRightMenu,
  WeaSearchGroup,
  WeaSelect,
  WeaTableEdit,
  WeaTableEditable,
  WeaTools,
  WeaTab,
  WeaHelpfulTip,
} from "ecCom";

const { WeaTable } = WeaTableNew;
const { getKey } = WeaTools;
const getLabel = WeaLocaleProvider.getLabel;
const { confirm } = Modal;
const store = ["archiveStore"];

@inject(...store)
@observer
export default class NewDetailForm extends React.Component {
  constructor(props) {
    super(props);
    const { archiveStore } = this.props;
    const { detailFieldListColumnsSetData1
      , detailFieldListColumnsSetData2
      , detailFieldListColumnsSetData3
      , detailFieldListColumnsSetData4
    } = toJS(archiveStore.status);
    this.state = {
      selectedKey: 0,
      detailData1: detailFieldListColumnsSetData1,
      detailData2: detailFieldListColumnsSetData2,
      detailData3: detailFieldListColumnsSetData3,
      detailData4: detailFieldListColumnsSetData4
    };
    this.table = null;
    this.tableMain = null;
  }

  componentWillUnmount () {
    this.table = null;
    this.tableMain = null;
  }


  getBtns = () => {
    const { newDetailSelectedKey } = toJS(this.props.archiveStore.status);
    let btns = []
    if (newDetailSelectedKey.toString() === "0" || newDetailSelectedKey.toString() === "1") {
      btns = [
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@8wb23o@integrationWorkflowarchiveNewDetailButtonSave`} type='primary' onClick={() => this.onRightMenuClick('BTN_SAVE')}>{getLabel(86, '保存')}</Button>
        // ,<Button type='primary' onClick={() => this.onRightMenuClick('BTN_CHECK')}>{getLabel(32367,'有效性检查')}</Button>
      ];
    }
    return btns;
  }

  getRightMenu () {
    const { archiveStore } = this.props;
    const { editlogTableStore } = archiveStore;
    let { getNewDatailFormrightMenus, rowSelectIds, newDetailSelectedKey } = toJS(archiveStore.status);
    let btnArr = [];
    let m = (getNewDatailFormrightMenus && getNewDatailFormrightMenus[0]) ? getNewDatailFormrightMenus[0] : [];

    newDetailSelectedKey == 2 && getNewDatailFormrightMenus && getNewDatailFormrightMenus.map((item, index) => {
      btnArr.push({
        key: `${item.menuIcon}`,
        icon: <i className={item.menuIcon} />,
        content: `${item.menuName}`,
        disabled: editlogTableStore.selectedRowKeys.length > 0 ? false : true,
        onClick: () => {
          if (rowSelectIds.length > 0) {
            archiveStore.confirmModal(`${getLabel(125754, '是否批量归档?')}`, archiveStore.getArchiveRegisterOperation, { operation: 'exp', ids: rowSelectIds });
          } else {
            archiveStore.confirmModal(`${getLabel(125753, '请选择需要归档的流程')}`);
          }
        }
      })
    })
    newDetailSelectedKey != '2' && btnArr.push({
      key: 'BTN_SAVE',
      icon: <i className='icon-coms-Preservation' />,
      content: `${getLabel(86, '保存')}`,
      onClick: () => this.onRightMenuClick('BTN_SAVE')
    })
    return btnArr;
  }

  onRightMenuClick = (type) => {
    console.log('chufa ')
    const { archiveStore } = this.props;
    const { newForm, newFormRegisterDB, newFormRegisterXML, status } = archiveStore;
    const { proType, ArchiveFormHiddenFields, ArchiveRegisterFormHiddenFields_DB,
      ArchiveRegisterFormHiddenFields_XML, ArchiveRegisterForm_MainTableFieldsColumnsData_XML,
      fieldDetailData, mainFixDatas, detailFixDatas, newDetailSelectedKey } = toJS(status);

    if (type == 'BTN_SAVE') {
      if (newDetailSelectedKey == 0) {
        //基本信息页保存
        newForm.validateForm().then(f => {
          if (f.isValid) {
            //合并hiddenfield参数
            let params = Object.assign(ArchiveFormHiddenFields, newForm.getFormParams());
            params.operation = "edit";
            archiveStore.getArchiveRegisterOperation(params, (result) => {
              if (result.status == "1") {
                message.success(getLabel('22619', '保存成功'));
                archiveStore.setState({ showNewFormDialog: false, rowSelectIds: [] });
              } else {
                message.error(getLabel('22620', '保存失败'));
              }
            });
          } else {
            f.showErrors();
            this.setState({ date: new Date() });
          }
        });
      } else if (newDetailSelectedKey == 1) {//newDetailSelectedKey是弹窗中的tab下标
        //字段配置保存
        let params = {}
        if (proType.toString() === "0") {
          params = ArchiveRegisterFormHiddenFields_XML;
          params = Object.assign(ArchiveRegisterFormHiddenFields_XML, newFormRegisterXML.getFormParams());
          params.operation = "editxml";
          params.dtinfo_mainFieldData = JSON.stringify(ArchiveRegisterForm_MainTableFieldsColumnsData_XML);
          archiveStore.getArchiveRegisterOperation(params, (result) => {
            if (result.status == "1") {
              message.success(getLabel('22619', '保存成功'));
            } else {
              message.error(getLabel('22620', '保存失败'));
            }
          });
        }
        if (proType.toString() === "1") {
          params = ArchiveRegisterFormHiddenFields_DB;
          params = Object.assign(ArchiveRegisterFormHiddenFields_DB, newFormRegisterDB.getFormParams());
          params.operation = "editDB";
          params.dtinfo_mainFieldData = JSON.stringify(fieldDetailData);
          params.mainFixDatas = JSON.stringify(mainFixDatas);
          params.detailFixDatas = JSON.stringify(detailFixDatas);
          newFormRegisterDB.validateForm().then(f => {
            if (f.isValid) {
              let result = true, res = true;
              try {
                if (this.table || this.tableMain) {
                  if (this.table) {
                    result = this.table.doValidate().pass;
                  }
                  if (this.tableMain) {
                    result = this.tableMain.doValidate().pass;
                  }
                  if (this.table && this.tableMain) {
                    (this.table.doValidate().pass && this.tableMain.doValidate().pass) == true ? result = true : result = false;
                  }
                }
              } catch (err) { }
              if (!result || (!res)) {
                return
              }
              archiveStore.getArchiveRegisterOperation(params, (result) => {
                if (result.status == "1") {
                  message.success(getLabel('22619', '保存成功'));
                } else {
                  message.error(getLabel('22620', '保存失败'));
                }
              });
            } else {
              f.showErrors();
              this.setState({ date: new Date() });
            }
          })
        }
      }
    }
  }

  getAdvancedSearch = () => {
    const { archiveStore } = this.props;
    const { dialogSearchForm, status } = archiveStore;
    const { newDetailSelectedKey, ArchiveEditconditionInfo } = toJS(status);
    let form = dialogSearchForm;
    let condition = [...ArchiveEditconditionInfo];
    if (newDetailSelectedKey == 2) {
      form = dialogSearchForm;
      condition = [...ArchiveEditconditionInfo];
    }
    return IntegrationUtil.getAdvancedItem(form, condition, this.handleSearchFun, false, this && this.props && this.props.ecId || '', "integrationWorkflowarchiveNewDetailForm");
  }

  handleSearchFun = () => {
    const { archiveStore } = this.props;
    const { status: { ArchiveFormHiddenFields, newDetailSelectedKey } } = archiveStore;
    if (newDetailSelectedKey == 2) {
      archiveStore.getArchiveRegisterEditFormLogList({
        workflowid: ArchiveFormHiddenFields.workflowid,
        sysid: ArchiveFormHiddenFields.id
      });
    }
    archiveStore.setState({ showSearchAd2: false });
  }

  getTabButtonsAd () {
    const { archiveStore } = this.props;
    return IntegrationUtil.getSearchBtns(
      this.handleSearchFun,
      () => archiveStore.dialogSearchForm.reset(),
      () => archiveStore.setState({ showSearchAd2: false }),
      this && this.props && this.props.ecId || '',
      "integrationWorkflowarchiveNewDetailForm"
    );
  }

  getTabButton = () => {
    const { archiveStore } = this.props;
    const { editlogTableStore } = archiveStore;
    let { getNewDatailFormrightMenus, rowSelectIds } = toJS(archiveStore.status);
    let btnArr = [];
    let m = getNewDatailFormrightMenus[0]
    let disabled = false;
    disabled = editlogTableStore.selectedRowKeys.length > 0 ? false : true;
    let btn = <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@zwvzdq`} type="primary" disabled={m.menuIcon === 'icon-coms-File' && disabled} onClick={() => {
      if (rowSelectIds.length > 0) {
        archiveStore.confirmModal(`${getLabel(125754, '是否批量归档?')}`, archiveStore.getArchiveRegisterOperation, { operation: 'exp', ids: rowSelectIds });
      } else {
        archiveStore.confirmModal(`${getLabel(125753, '请选择需要归档的流程')}`);
      }
    }}>{`${m.menuName}`}</Button>;
    btnArr.push(btn);
    return btnArr;
  }

  render () {
    const { archiveStore } = this.props;
    const { status, dialogSearchForm } = archiveStore;
    const { showSearchAd2, showNewDetailFormDialog, proType, newDetailSelectedKey } = toJS(status);
    const topTab = [
      {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(82751, "基础设置")}`,
        viewcondition_dt: 0
      }
      , {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(125610, "字段映射")}`,
        viewcondition_dt: 1
      }
      , {
        color: "#000000",
        groupid: "flowAll",
        showcount: true,
        title: `${getLabel(83255, "归档日志")}`,
        viewcondition_dt: 2
      }
    ];
    let tabContent = "";

    switch (newDetailSelectedKey.toString()) {
      case "0":
        tabContent = this.getSearchs()
        break;
      case "1":
        console.log(proType);
        if (proType == "0") {
          tabContent = this.getSearchs2();
        } else {
          tabContent = this.getSearchs2DB();
        }
        break;
      case "2":
        tabContent = this.getSearchs3();
        break;
    }
    return (
      <div className='wea-integration-single'>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@wka1pz`}
          title={`${getLabel('26473,33925,127023', '编辑归档流程注册信息')}`}
          icon='icon-coms-integration'
          iconBgcolor='#1a57a0'
          visible={showNewDetailFormDialog}
          hasScroll={true}
          style={{ width: 1050, height: 600 }}
          onCancel={() => archiveStore.setState({ showNewDetailFormDialog: false })}
          buttons={this.getBtns()}
          moreBtn={{
            datas: this.getRightMenu(),
            collectParams: []
          }}
        >
          <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ek6sis`}
            datas={this.getRightMenu()}
            collectParams={[]}>
            <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@tqgi1b`}
              datas={topTab}
              keyParam="viewcondition_dt" //主键
              countParam="groupid" //数量
              selectedKey={newDetailSelectedKey}
              searchType={newDetailSelectedKey == '2' ? ['base', 'advanced'] : []}
              buttons={newDetailSelectedKey == '2' ? this.getTabButton() : []}
              advanceHeight={120}
              searchsAd={this.getAdvancedSearch()}
              showSearchAd={showSearchAd2}
              setShowSearchAd={() => { archiveStore.setState({ showSearchAd2: !showSearchAd2 }) }}
              hideSearchAd={() => { archiveStore.setState({ showSearchAd2: false }) }}
              buttonsAd={this.getTabButtonsAd()}
              onChange={v => {
                archiveStore.setState({ newDetailSelectedKey: v });
                if (v == '2') {
                  dialogSearchForm.reset();
                  archiveStore.getArchiveRegisterEditFormLogList({
                    workflowid: archiveStore.status.ArchiveFormHiddenFields.workflowid,
                    sysid: archiveStore.status.ArchiveFormHiddenFields.id
                  });
                }
              }}
              onSearch={() => {
                let params = {
                  workflowid: archiveStore.status.ArchiveFormHiddenFields.workflowid,
                  sysid: archiveStore.status.ArchiveFormHiddenFields.id
                };
                if (newDetailSelectedKey == '2') {
                  archiveStore.getArchiveRegisterEditFormLogList(params);
                }
              }}
              searchsBaseValue={newDetailSelectedKey == '2' ? dialogSearchForm.getFormParams().requestname : ""}
              onSearchChange={value => {
                archiveStore.dialogSearchForm.updateFields({ requestname: value })
              }}
            />
            {tabContent}
          </WeaRightMenu>
        </WeaDialog>
      </div>
    )
  }

  insertAfterText = (textDom, value) => {
    let str = '';
    textDom = textDom.querySelector('.ant-input');

    var selectRange;
    if (document.selection) {
      // IE Support
      textDom.focus();
      selectRange = document.selection.createRange();
      selectRange.text = value;
      textDom.focus();
      str = textDom.value;
    } else if (textDom.selectionStart || textDom.selectionStart == '0') {
      // Firefox support
      var startPos = textDom.selectionStart;
      var endPos = textDom.selectionEnd;
      var scrollTop = textDom.scrollTop;
      str = textDom.value.substring(0, startPos) + value + textDom.value.substring(endPos, textDom.value.length);
      textDom.focus();
      textDom.selectionStart = startPos + value.length;
      textDom.selectionEnd = startPos + value.length;
      textDom.scrollTop = scrollTop;
    }
    else {
      str = textDom.value + value;
      textDom.focus();
    }
    return str;
  }

  mark = (e, key) => {
    const { archiveStore } = this.props;
    const { newFormRegisterXML } = archiveStore;
    let textDom = ReactDOM.findDOMNode(this.refs.fieldattr);
    let val = this.insertAfterText(textDom, '${' + key + '}');
    newFormRegisterXML.updateFields({ fieldattr: val });
  }

  /**
   * 初始渲染明细表
   * @param mainFieldListColumnsSet 明细表的配置数据
   * @param newForm
   */
  initColumsSet = (mainFieldListColumnsSet, columns = 2, mainFieldListColumnsSetData, storeKey) => {
    const { archiveStore } = this.props;
    //转换规则逻辑
    if (mainFieldListColumnsSet[columns] === undefined) {
      return;
    }
    mainFieldListColumnsSet[columns].com[0].type = 'custom';

    mainFieldListColumnsSet[columns].com[0].render = (text, record, index, onEdit) => {
      if (record.fieldhtmltypes == 4) {
        let checkValue = record['checkedValueTo_' + record.mainFieldIds];
        let unCheckValue = record['uncheckedValueTo_' + record.mainFieldIds];
        return (<div><nobr><span>{getLabel('125766,125765', '已勾选转换值')}:</span><WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@rzmemx`} onChange={(value) => { let key = 'checkedValueTo_' + record.mainFieldIds; mainFieldListColumnsSetData[index][key] = value; archiveStore.setState({ [storeKey]: mainFieldListColumnsSetData }); onEdit({ record, index, key, value }) }} value={checkValue} fieldName={'checkedValueTo_' + record.mainFieldIds} style={{ marginLeft: 5, width: '30%' }} /></nobr><br /><nobr><span>{getLabel('125767,125765', '不勾选转换值')}:</span><WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@6hvt4h`} onChange={(value) => { let key = 'uncheckedValueTo_' + record.mainFieldIds; mainFieldListColumnsSetData[index][key] = value; archiveStore.setState({ [storeKey]: mainFieldListColumnsSetData }); onEdit({ record, index, key, value }) }} value={unCheckValue} fieldName={'uncheckedValueTo_' + record.mainFieldIds} style={{ marginLeft: 5, width: '30%' }} /></nobr></div>)
      } else {
        let selectValue = record['fieldRules_' + record.mainFieldIds] || "0";
        return (<WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@w501it`}
          fieldName={'fieldRules_' + record.mainFieldIds}
          options={record.selectOptions}
          value={selectValue}
          onChange={(value) => {
            let key = 'fieldRules_' + record.mainFieldIds;
            mainFieldListColumnsSetData[index][key] = value;
            archiveStore.setState({ [storeKey]: mainFieldListColumnsSetData });
            onEdit({ type: "CUSTOM", record, index, key, value })
          }} />)
      }
    }
  }

  handleOperatesClick = (record, index, operate) => {
    const { archiveStore } = this.props;
    if (operate.index == '1') {
      archiveStore.getArchiveRegisterOperation({ operation: 'exp', ids: record.randomFieldId, expworkflowDetailid: archiveStore.status.ArchiveFormHiddenFields.id });
    }
  }

  getColumnsInfo = data => {
    if (!isEmpty(data)) {
      for (let index = 0; index < data.length; index++) {
        if (data[index].dbField == "requestname") {
          data[index].render = (text, record, index) =>
            <a href={`${window.ecologyContentPath || ""}/spa/workflow/index_form.jsp#/main/workflow/req?requestid=${record.requestid}&_workflowid=${record.workflowid}`} target="_blank"><span dangerouslySetInnerHTML={{ __html: record.requestnamespan }}></span></a>
        }
      }
    }
  }

  getRowSelection = () => {
    return { onChange: selectedRowKeys => this.props.archiveStore.setState({ rowSelectIds: selectedRowKeys }) }
  }

  getSearchs3 = () => {
    const { archiveStore } = this.props;
    const { editlogTableStore } = archiveStore;
    return <div>
      <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@m5sci5`}
        comsWeaTableStore={editlogTableStore}
        getColumns={this.getColumnsInfo}
        hasOrder={true}
        needScroll={true}
        onOperatesClick={this.handleOperatesClick}
        rowSelection={this.getRowSelection()}
      />
    </div>;
  }

  getSearchs2 = () => {
    const { archiveStore } = this.props;
    const { newFormRegisterXML, status } = archiveStore;
    const { summary, warning } = toJS(status);
    const { ArchiveRegisterFormFields_XML, ArchiveRegisterFormFieldLabels_XML,
      ArchiveRegisterForm_MainTableFieldsColumnsSet_XML, ArchiveRegisterForm_MainTableFieldsColumnsData_XML } = toJS(status);
    const { isFormInit } = newFormRegisterXML;
    let group = [];
    let i = 0;
    const formParams = newFormRegisterXML.getFormParams();

    isFormInit && ArchiveRegisterFormFields_XML && ArchiveRegisterFormFields_XML.map((c) => {
      let items = [];
      let dom = '';
      c.items.map(fields => {
        if (getKey(fields) === 'fieldattr') {
          dom = <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@9b7hh2@integrationWorkflowarchiveNewForm${fields.domkey[0]}`} title={`${summary}<span class='warning'>${warning}</span>`} width={196} style={{ paddingLeft: 20 }} />
        }
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@2szixg@integrationWorkflowarchiveNewForm${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              error={newFormRegisterXML.getError(fields)}
              tipPosition="bottom"
            >
              <nobr>
                <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@39ewp2@integrationWorkflowarchiveNewForm${fields.domkey[0]}`} ref={fields.domkey[0]} fieldConfig={fields} form={newFormRegisterXML} formParams={formParams} />
                {dom}
              </nobr>
            </WeaFormItem>),
          colSpan: 1,
          hide: newFormRegisterXML.isHide(fields, (keys, allParams) => {
            let bool = false;
            getKey(fields) === 'requestid' && allParams.datarecordtype == '1' && (bool = true);
            getKey(fields) === 'FTriggerFlag' && allParams.datarecordtype == '1' && (bool = true);
            getKey(fields) === 'FTriggerFlagValue' && allParams.datarecordtype == '1' && (bool = true);
            getKey(fields) === 'isupdatewfdataField' && allParams.isupdatewfdata == '1' && (bool = true);
            return bool;
          })
        });
      })
      //主表字段mark
      if (i == 1) {
        let obj = ArchiveRegisterFormFieldLabels_XML;
        let mark = [];
        for (let k = 0, len = obj.length; k < len; k++) {
          mark.push((<span onClick={(e) => { this.mark(e, obj[k].id) }} style={{ marginLeft: 5, cursor: 'pointer', color: 'blue', whiteSpace: 'nowrap' }} key={obj[k].id}>
            {obj[k].label}</span>
          ))
          k % 5 === 4 ? mark.push(<br />) : mark.push()
        }


        group.push(
          <WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@3y90yy@integrationWorkflowarchiveNewForm${i}`}
            center
            col={1}
            needTigger={true}
            title={c.title}
            showGroup={c.defaultshow}
          >
            {mark}
          </WeaSearchGroup>
        );

      }

      //主表字段转换规则
      if (i == 2) {
        this.initColumsSet(ArchiveRegisterForm_MainTableFieldsColumnsSet_XML, 2, ArchiveRegisterForm_MainTableFieldsColumnsData_XML, 'ArchiveRegisterForm_MainTableFieldsColumnsData_XML');
        items.push({
          com: (
            <div>
              <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@6yhf06@integrationWorkflowarchiveNewForm${i}`}
                showTitle={false}
                pushTitleIntoHeader={false}
                tableProps={{ showEmptyText: false }}
                columns={ArchiveRegisterForm_MainTableFieldsColumnsSet_XML}
                datas={ArchiveRegisterForm_MainTableFieldsColumnsData_XML}
                draggable={false}
                showAdd={false}
                showDelete={false}
                showCopy={false}
                getRowSelection={a => { return false }}
                onAdd={(ks, ds) => { }}
                onEdit={(ks, ds) => { }}
                onCopy={(ks, ds) => { }}
                onDelete={(ks, ds) => { }}
                onChange={(datas) => { archiveStore.setState({ ArchiveRegisterForm_MainTableFieldsColumnsData_XML: datas }) }}
              />

            </div>
          ),
          hide: newFormRegisterXML.isHide(c, (keys, allParams) => {
            return (false);
          })
        });

        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@l84cfo@integrationWorkflowarchiveNewForm${i}`} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
      }


      if (i < 1) {
        group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@mqrd5k@integrationWorkflowarchiveNewForm${i}`} center col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
      }

      i++;
    });
    return group;
  }

  getConstantFieldName = (mainFixDatas = [], key, value = "", dataName = "", fieldName = "", fieldType = "") => {
    for (let i = 0; i < mainFixDatas.length; i++) {
      let data = mainFixDatas[i];
      if (data && data[key] && data[key].trim()) {
        if (data[key].trim() === value.trim()) {
          mainFixDatas[i] = {
            ...mainFixDatas[i],
            [fieldName]: "",
            [fieldType]: "",
          };
          this.props.archiveStore.setState({
            [dataName]: mainFixDatas
          })
          return false;
        }
      }
    }
    return true;
  }

  willEditDB = (datas = [], addData) => {
    const {
      key,
      index,
      browserDatas,
      record,
    } = addData, {
      archiveStore,
    } = this.props, {
      status,
    } = archiveStore, {
      mainFixDatas = [],
    } = toJS(status);

    if (key === "expfieldName") {
      let currentData = {};
      if (browserDatas.length) {
        // 转换规则和固定值字段名称不可重复
        this.getConstantFieldName(mainFixDatas, "mfixfieldName", browserDatas[0].fieldCnName, "mainFixDatas", "mfixfieldName", "mfixfieldtype");
        currentData = {
          expfieldName: browserDatas[0].fieldCnName,
          expfieldtype: browserDatas[0].fielddbtype,
        };
      } else {
        currentData = {
          expfieldName: "",
          expfieldtype: "",
        }
      }
      datas[index] = {
        ...datas[index],
        ...currentData,
      };
      if (browserDatas.length) {
        datas && datas.forEach((v, idx) => {
          if (v.expfieldName === browserDatas[0].fieldCnName && v.mainFieldIds != record.mainFieldIds) {
            datas[idx] = {
              ...datas[idx],
              expfieldName: "",
              expfieldtype: "",
            }
          }
        })
      }
    }
    return datas;
  }

  willEditConstantDB = (datas = [], addData) => {
    const {
      key,
      index,
      browserDatas,
      record,
    } = addData, {
      archiveStore,
    } = this.props, {
      status,
    } = archiveStore, {
      fieldDetailData = [],
    } = toJS(status);

    if (key === "mfixfieldName") {
      let currentData = {};
      if (browserDatas.length) {
        // 转换规则和固定值字段名称不可重复
        this.getConstantFieldName(fieldDetailData, "expfieldName", browserDatas[0].fieldCnName, "fieldDetailData", "expfieldName", "expfieldtype");
        currentData = {
          mfixfieldName: browserDatas[0].fieldCnName,
          mfixfieldtype: browserDatas[0].fielddbtype,
        }
      } else {
        currentData = {
          mfixfieldName: "",
          mfixfieldtype: "",
        }
      }
      datas[index] = {
        ...datas[index],
        ...currentData,
      };
      if (browserDatas.length) {
        datas && datas.forEach((v, idx) => {
          if (v.mfixfieldName === browserDatas[0].fieldCnName && v.id != record.id) {
            datas[idx] = {
              ...datas[idx],
              mfixfieldName: "",
              mfixfieldtype: "",
            }
          }
        })
      }
    }
    return datas;
  }

  willEditConstantDerailDB = (datas = [], addData) => {
    const {
      key,
      index,
      browserDatas,
      record,
    } = addData;
    if (key === "dtfixfieldName") {
      let currentData = {};
      if (browserDatas.length) {
        currentData = {
          dtfixfieldName: browserDatas[0].fieldCnName,
          dtfixfieldtype: browserDatas[0].fielddbtype,
        }
      } else {
        currentData = {
          dtfixfieldName: "",
          dtfixfieldtype: "",
        }
      }
      datas[index] = {
        ...datas[index],
        ...currentData,
      };
      if (browserDatas.length) {
        datas && datas.forEach((v, idx) => {
          if (v.dtfixfieldName === browserDatas[0].fieldCnName && v.id != record.id) {
            datas[idx] = {
              ...datas[idx],
              dtfixfieldName: "",
              dtfixfieldtype: "",
            }
          }
        })
      }
    }
    return datas;
  }

  getSearchs2DB = () => {
    const { archiveStore } = this.props;
    const { newFormRegisterDB } = archiveStore;
    const status = toJS(archiveStore.status)

    return newFormRegisterDB.render({ center: true, col: 1 }, {
      onChange: (e) => { }
    }, true, (item, idx) => {
      // 流程主表字段转换规则
      if (item.id === "cfe93337-bd81-82a2-18dd-641c98d65a57") {
        this.initColumsSet(status.fieldDetailColumnsSet, 3, status.fieldDetailData, "fieldDetailData");
        return (
          <div style={{ paddingLeft: 25, paddingRight: 25 }}>
            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@bsnaij`}
              rowKey="mainFieldIds"
              title={item.title}
              showCollapse={true}
              columns={status.fieldDetailColumnsSet}
              getRowSelection={e => false}
              willEdit={this.willEditDB}
              datas={status.fieldDetailData}
              onChange={(datas) => archiveStore.setState({ fieldDetailData: datas })}
              showCopy={false}
              showAdd={false}
              showDelete={false}
            />
          </div>
        )

      }
      // 归档库主表固定值设置
      if (item.id === "b15ba9a4-13b9-5dae-5b9f-45332ce724fe") {
        return (
          <div style={{ paddingLeft: 25, paddingRight: 25 }}>
            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@b9h1n2`}
              rowKey="id"
              ref={el => this.tableMain = el}
              title={item.title}
              showCollapse={true}
              columns={status.mainFixColumnSet}
              validator={{
                rules: {
                  mfixfieldName: "required",
                  mainfixValue: "required"
                },
                errorMessage: {
                  required: '此项必填',
                }
              }}
              tableProps={{ showEmptyText: false }}
              willEdit={this.willEditConstantDB}
              willDelete={this.willDelete}
              datas={status.mainFixDatas}
              onChange={(datas) => {
                archiveStore.setState({ mainFixDatas: datas })
              }}
              showCopy={false}
            />
          </div>
        )
      }
      // 归档库明细表固定值设置
      if (item.id === "77b3d8a3-6d1f-006a-220c-5d93a6b03d52") {
        return (
          <div style={{ paddingLeft: 25, paddingRight: 25 }}>
            <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@8tzfa3`}
              rowKey="id"
              ref={el => { this.table = el }}
              title={item.title}
              columns={status.detailFixColumnSet}
              tableProps={{ showEmptyText: false }}
              showCollapse={true}
              validator={{
                rules: {
                  dtfixValue: "required",
                  dtfixfieldName: "required"
                },
                errorMessage: {
                  required: '此项必填',
                },
              }}
              willEdit={this.willEditConstantDerailDB}
              // willAdd={(datas, addData) => this.addMainTable(datas, addData)}
              willDelete={this.willDelete}
              datas={status.detailFixDatas}
              onChange={(datas) => {
                archiveStore.setState({ detailFixDatas: datas })
              }}
              showCopy={false}
            />
          </div>
        )
      }
    })
  }

  willDelete = (datas, keys) => new Promise((resolve, reject) => {
    confirm({
      content: `${getLabel(385625, '确定要删除选择的记录吗？')}`,
      onOk: () => resolve(true),
      onCancel: () => resolve(false),
    })
  })

  /**
   * todo 冗余代码,和NewForm一致, 待处理
   * @returns {Array}
   */
  getSearchs = () => {
    const { archiveStore } = this.props;
    const { newForm, status } = archiveStore;
    const { ArchiveFormFields } = toJS(status);
    const { isFormInit } = newForm;
    let group = [];
    let i = 0;
    const formParams = newForm.getFormParams();
    isFormInit && ArchiveFormFields && ArchiveFormFields.map(c => {
      let items = [];
      c.items.map(fields => {
        items.push({
          com: (
            <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1f1l6x@integrationWorkflowarchiveNewFormSearch${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{ span: `${fields.labelcol}` }}
              wrapperCol={{ span: `${fields.fieldcol}` }}
              error={newForm.getError(fields)}
              tipPosition="bottom"
            >
              <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8iczi9@integrationWorkflowarchiveNewFormSearch${fields.domkey[0]}`} fieldConfig={fields} form={newForm} formParams={formParams} onChange={v => {
                if (getKey(fields) === 'expid') {
                  archiveStore.getArchiveRegisterOperation({ operation: 'ExpGetProInf', Proid: newForm.getFormParams().expid }, (result) => {
                    if (result && result.ExpGetProInf && result.ExpGetProInf.indexOf("#") > 0) {
                      newForm.updateFields({ proType: (result.ExpGetProInf).split("#")[0] });
                      newForm.updateFields({ proFileSaveType: (result.ExpGetProInf).split("#")[1] });
                    } else {
                      newForm.updateFields({ proType: '' });
                      newForm.updateFields({ proFileSaveType: '' });
                    }
                  });
                }
              }} />
            </WeaFormItem>),
          colSpan: 1,
          hide: newForm.isHide(fields, (keys, allParams) => {
            let bool = false;
            if (allParams.isview == "1") {
              if (getKey(fields) === 'requestid' || getKey(fields) === 'FTriggerFlag'
                || getKey(fields) === 'FTriggerFlagValue' || getKey(fields) === 'isupdatewfdataField') {
                bool = true;
              }
            }
            getKey(fields) === 'requestid' && allParams.datarecordtype == '1' && (bool = true);
            getKey(fields) === 'FTriggerFlag' && allParams.datarecordtype == '1' && (bool = true);
            getKey(fields) === 'FTriggerFlagValue' && allParams.datarecordtype == '1' && (bool = true);

            getKey(fields) === 'isupdatewfdataField' && allParams.isupdatewfdata == '1' && (bool = true);
            return bool;
          })
        });

      })
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@wd0gov@integrationWorkflowarchiveNewFormSearch${i}`} center col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items} />);
      i++;
    });
    return group;
  }
}
