import React from "react";
import { inject, observer } from "mobx-react";
import { Button, Modal } from "antd";
import { checkTableFieldValueUnique } from "../../apis/CommonService";
import { toJS } from "mobx";
import {
  WeaDialog,
  WeaLocaleProvider,
  WeaTools,
  WeaTableEditable,
  WeaHelpfulTip,
  WeaRightMenu
} from "ecCom";

const getLabel = WeaLocaleProvider.getLabel;
const store = ["archiveStore"];

@inject(...store)
@observer
export default class NewForm extends React.Component {

  getColumns = (cols) => {
    cols && cols.forEach((col) => {
      if (col.helpfulTip !== undefined && !col.rendered) {
        let text = col.title;
        col.rendered = true;
        col.title = <span>{text}&nbsp;
          <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@37kmpl@integrationWorkflowarchiveDbColumns${col.dataIndex || ""}`}
            title={col.helpfulTip}
          />
        </span>
      }
    })
    // console.log('col', col);
    return cols;
  }

  handleMainTable = (datas = [], addData, prefix = "") => {
    // ["mainfieldName", "mainfieldtype", "mainiskey", "mainisdoc", "mainisdoctype", "mainisdocname"]
    // ["dtfieldName", "dtfieldtype", "dtiskey", "dtisdoc", "dtisdoctype", "dtismainkey", "dtisdocname"]
    const currentColKey = addData.col && addData.col.dataIndex || "0";
    const currentId = addData.record.id;
    return datas && datas.map(data => {
      if (currentId === data["id"]) {
        if (this.validateMainTable(addData, prefix)) {
          // col set
          // clear col checkbox
          datas.map(item => { item[currentColKey] = "0"; })
          // row set
          // clear row checkbox
          data[`${prefix}key`] && (data[`${prefix}key`] = "0");
          data[`${prefix}doc`] && (data[`${prefix}doc`] = "0");
          data[`${prefix}doctype`] && (data[`${prefix}doctype`] = "0");
          data[`${prefix}docname`] && (data[`${prefix}docname`] = "0");
          data['dtismainkey'] && (data['dtismainkey'] = "0");
          // revert current value
          data[currentColKey] = addData.record[currentColKey];
          // set current checkbox value on this click
          data[currentColKey] = addData.value;
          // data[currentColKey] = addData.record[currentColKey] === "0" ? "1" : "0";
        } else {
          data[currentColKey] = addData.record[currentColKey];
        }
        // data[currentColKey] = "0";
        if (addData.browserDatas) {
          return {
            ...data,
            [`${prefix.substr(0, prefix.length - 2)}fieldName`]: addData.browserDatas[0] ? addData.browserDatas[0].fieldCnName : "",
            [`${prefix.substr(0, prefix.length - 2)}fieldtype`]: addData.browserDatas[0] ? addData.browserDatas[0].fielddbtype : ""
          }
        }
      } else {
        // 字段名不能重复
        if (data[`${prefix.substr(0, prefix.length - 2)}fieldName`] === addData.value) {
          return {
            ...data,
            [`${prefix.substr(0, prefix.length - 2)}fieldName`]: "",
            [`${prefix.substr(0, prefix.length - 2)}fieldtype`]: ""
          }
        }
      }
      return data;
    })
  }

  validateMainTable = (addData, prefix) => {
    const { archiveStore } = this.props;
    const { settingRegisterDBForm } = archiveStore;
    const { col, record, key } = addData;
    const params = settingRegisterDBForm.getFormParams();

    const title = {
      [`${prefix}doc`]: getLabel("22243", "文档"),
      [`${prefix}doctype`]: getLabel("27139", "文档类型"),
      [`${prefix}docname`]: getLabel("1341", "文档名称"),
    }
    let validate = true;
    // 允许点击什么字段，把该字段放入即可
    let docVali = [];
    let doctypeVali = [];
    let docnameVali = [];
    // ftp
    if (["0", "1"].includes(params.FileSaveType)) {
      docVali = ["varchar"];
      doctypeVali = ["varchar"];
      docnameVali = ["varchar"];
    }
    // // 本地
    // if (params.FileSaveType === "1") {
    //   docVali = ["blob", "varchar"];
    //   doctypeVali = ["varchar"];
    //   docnameVali = ["varchar"];
    // }
    // 数据库
    if (params.FileSaveType === "2") {
      docVali = ["blob", "longvarbinary", "binary"];
      doctypeVali = ["varchar"];
      docnameVali = ["varchar"];
    }
    if (key === `${prefix}doc` && (!docVali.includes(record[`${prefix.substr(0, prefix.length - 2)}fieldtype`]))) {
      validate = false;
    } else if (key === `${prefix}doctype` && (!doctypeVali.includes(record[`${prefix.substr(0, prefix.length - 2)}fieldtype`]))) {
      validate = false;
    } else if (key === `${prefix}docname` && (!docnameVali.includes(record[`${prefix.substr(0, prefix.length - 2)}fieldtype`]))) {
      validate = false;
    }
    if (!validate) {
      Modal.warn({
        // title: title[col.dataIndex],
        title: `${title[col.dataIndex]}`,
        content: `${title[col.dataIndex]}${getLabel("84113", "字段类型")}${getLabel("386675", "不匹配")}`
      })
    }

    return validate;
  }

  addMainTable = (datas, addData, prefix = "") => {
    // "dtfieldName", "dtfieldtype", "dtiskey", "dtisdoc", "dtisdoctype", "dtismainkey", "dtisdocname"
    return datas.map(data => {
      if (data.id === addData.id) {
        return {
          ...data,
          [`${prefix}key`]: "0",
          [`${prefix}doc`]: "0",
          [`${prefix}doctype`]: "0",
          [`${prefix}docname`]: "0",
        }
      }
      return data;
    })
  }

  getRightMenu = () => {
    const { archiveStore } = this.props;
    return [{
      key: "BTN_SAVE",
      icon: <i className="icon-coms-Preservation" />,
      content: `${getLabel('86', '保存')}`,
      onClick: () => this.onRightMenuClick("BTN_SAVE")
    }];
  }

  getBtns = () => {
    return [
      <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@jb7nwu@integrationWorkflowarchiveDbButtonSave`} type="primary" onClick={() => this.onRightMenuClick("BTN_SAVE")}>{getLabel('86', '保存')}</Button>
    ]
  }

  onRightMenuClick = type => {
    const { archiveStore } = this.props;
    switch (type) {
      case "BTN_SAVE":
        archiveStore.getArchiveConfigSchemeOperationDB()
        break;
    }
  }

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

  render () {
    const { archiveStore } = this.props;
    const { setConfigSchememainTableColumnsSetBrowserConditionParam } = archiveStore;
    const status = toJS(archiveStore.status);
    const { configSchememainTableColumnsData, configSchemedetailTableColumnsData } = status;
    let title = getLabel('31691,125761', '注册数据库方案');
    if (archiveStore.settingRegisterID != "") {
      title = getLabel('26473,125761', '编辑数据库方案');
    }
    return <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@0vssrp`}
      title={title}
      onCancel={() => archiveStore.setState({ ConfigSchemeAddDialogVisible: false })}
      visible={status.ConfigSchemeAddDialogVisible}
      style={{ width: 900, height: 600 }}
      hasScroll
      moduleName="integration"
      buttons={this.getBtns()}
      moreBtn={{
        datas: this.getRightMenu(),
        collectParams: [{
          favname: `${getLabel(83203, "流程归档集成")}`,
          favouritetype: 1,
          objid: 0,
          link: "wui/engine.html#/integration/WorkflowArchive",
          importantlevel: 1
        }]
      }}
    >
      <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@yglq5c`}
        datas={this.getRightMenu()}
        collectParams={{
          favname: `${getLabel(83203, "流程归档集成")}`,
          favouritetype: 1,
          objid: 0,
          link: "wui/engine.html#/integration/WorkflowArchive",
          importantlevel: 1
        }}>
        {archiveStore.settingRegisterDBForm.render({ col: 1, center: true }, {
          onChange: (v) => {
            //设置联动(导出流转意见文档和导出流转意见开关的联动)
            if (status.configSchememainTableColumnsSet[0] && v.regitDBId) {
              setConfigSchememainTableColumnsSetBrowserConditionParam(v.regitDBId.value);
            }

            if (v.FileSaveType) {
              let ops = [...status.regitTypeOptions[v.FileSaveType.value]];
              archiveStore.settingRegisterDBForm.setField('regitType', {
                options: ops
              })
              archiveStore.settingRegisterDBForm.updateFields({
                regitType: ops[0].key,
              })
              if (v.FileSaveType.value == 2) {
                archiveStore.settingRegisterDBForm.updateFields({
                  filesavetypespan: `${getLabel("125735", "文件内容")}`
                })
              } else {
                archiveStore.settingRegisterDBForm.updateFields({
                  filesavetypespan: `${getLabel('25391', '文件路径')}`
                })
              }
              let datas = configSchememainTableColumnsData && configSchememainTableColumnsData.map(data => {
                return {
                  ...data,
                  mainisdoc: 0
                }
              });
              let detailDatas = configSchemedetailTableColumnsData && configSchemedetailTableColumnsData.map(data => {
                return {
                  ...data,
                  dtisdoc: 0
                }
              })
              archiveStore.setState({ configSchememainTableColumnsData: datas, configSchemedetailTableColumnsData: detailDatas });
            }
            // 文档归档目标
            if (v.expTableType) {
              archiveStore.setState({
                configSchememainTableColumnsData: [],
                configSchemedetailTableColumnsData: []
              })
            }
            // 注册数据库
            if (v.regitDBId) {
              WeaTools.callApi('/api/integration/workflowarchive/getArchiveConfigSchemeOperationDB',
                'POST', { operation: 'toggleRegitDBId', regitDBId: v.regitDBId.value }).then((res) => {
                  let ops = res.hasDetail ? status.expTableTypeOptions.hasDetail : status.expTableTypeOptions.noDetail;
                  archiveStore.settingRegisterDBForm.setField('expTableType', {
                    options: ops
                  })
                  archiveStore.setState({
                    configSchemehasDetail: res.hasDetail,
                    configSchemedetailTableColumnsData: res.detailTableColumnsData,
                    configSchememainTableColumnsData: res.mainTableColumnsData
                  })
                  let params = {
                    expTableType: ops[0].key,
                    mainTable: res.mainTable,
                  }
                  if (res.hasDetail) {
                    params.dtTable = res.dtTable;
                  }
                  archiveStore.settingRegisterDBForm.updateFields(params)
                })
            }
            if (v.name) {
              let checkParams = {
                tableName: 'exp_DBProSettings',
                fieldName: 'name',
                fieldValue: archiveStore.settingRegisterDBForm.getFormParams().name.replace(/^(\s*)|(\s*)$/g, ''),
                idName: 'id',
                idValue: archiveStore.settingRegisterID
              };
              checkTableFieldValueUnique(checkParams).then(result => {
                if (result && result.isNotUnique) {
                  archiveStore.settingRegisterDBForm.showError('name', getLabel('129943', '名称已存在'));
                  // message.error(getLabel('387654','标识已存在'));
                }

              });
            }
          },
          isHide: (key, formParams) => {
            let hide = false;
            if ('regitType' == key && formParams.FileSaveType === "2") {
              hide = true;
            }

            if ('syncmethodHz' == key && formParams.synType !== '1') {
              hide = true;
            }
            //初始化隐藏
            if (('ExpWorkflowRemarkFileFlag' == key && formParams.ExpWorkflowRemarkFlag !== '1') || ('ExpWorkflowRemarkFlag' == key && formParams.ExpWorkflowInfoFlag !== '1')) {
              hide = true;
            }

            if (formParams.ExpWorkflowRemarkFlag !== '1' && 'ExpWorkflowRemarkFileFlag' == key) {
              hide = true;
            }
            if (formParams.ExpWorkflowFileFlag !== '1' && 'ExpWorkflowFileForZipFlag' == key) {
              hide = true;
            }
            if (formParams.ExpWorkflowRemarkFileFlag !== '1' && 'ExpWorkflowRemarkFileForZip' == key) {
              hide = true;
            }
            if (formParams.ExpWorkflowRemarkFileFlag !== '1' && formParams.ExpWorkflowFileFlag !== '1' && 'ExpWorkflowFilePath' == key) {
              hide = true;
            }
            if (formParams.ExpWorkflowInfoFlag !== '1' && 'ExpWorkflowInfoPath' == key) {
              hide = true;
            }
            if (formParams.ExpWorkflowRemarkFlag !== '1' && 'ExpSignFileFlag' == key) {
              hide = true;
            }
            if ((formParams.ExpWorkflowRemarkFlag !== '1' || formParams.ExpSignFileFlag !== '1') && 'ExpSignFilePath' == key) {
              hide = true;
            }
            if (formParams.ExpWorkflowInfoFlag !== '1' && 'bdMapFiletype' == key) {
              hide = true;
            }
            if (formParams.ExpWorkflowFileFlag !== '1' && (['zwMapFiletype', 'fjMapFiletype', 'dwdMapFiletype', 'mwdMapFiletype']).indexOf(key) > -1) {
              hide = true;
            }
            if (formParams.ExpWorkflowRemarkFileFlag !== '1' && (['remarkWDMapFiletype', 'remarkFJMapFiletype']).indexOf(key) > -1) {
              hide = true;
            }
            if (formParams.FileSaveType === "2" && ['ExpWorkflowFilePath', 'ExpWorkflowInfoPath', 'ExpSignFilePath'].includes(key)) {
              hide = true;
            }
            //联动隐藏
            if (formParams.ExpWorkflowInfoFlag !== '1' && ['ExpSignFilePath', 'ExpSignFileFlag', 'ExpWorkflowRemarkFileFlag', 'ExpWorkflowRemarkFileForZip', 'remarkWDMapFiletype', 'remarkFJMapFiletype', 'ExpWorkflowFilePath'].includes(key)) {
              hide = true;
            }
            if (formParams.ExpWorkflowRemarkFlag !== '1' && ['ExpWorkflowRemarkFileForZip', 'ExpWorkflowFilePath'].includes(key)) {
              hide = true;
            }
            if (formParams.ExpWorkflowFileFlag == '1' && 'ExpWorkflowFilePath' == key) {
              hide = false;
            }
            if (formParams.FileSaveType == '2' && 'ExpWorkflowFilePath' == key) {
              hide = true;
            }

            return hide;
          }
        }, true, (item, idx) => {
          // "导出流程文档路径" "ExpWorkflowFilePath"
          // "导出流程表单路径" "ExpWorkflowInfoPath"
          // "导出签章图片路径" "ExpSignFilePath"
          const params = archiveStore.settingRegisterDBForm.getFormParams();
          let configSchememainTableColumnsSet = status.configSchememainTableColumnsSet;
          let configSchemedetailTableColumnsSet = status.configSchemedetailTableColumnsSet;
          let regitDBIdValue = params.regitDBId;
          // 292 - 310 写的比较晦涩，但是相信我，没有bug
          // 此处是只读的设置项
          let needHandleArray = params.expTableType === "0" ?
            [configSchemedetailTableColumnsSet, configSchememainTableColumnsSet] :
            [configSchememainTableColumnsSet, configSchemedetailTableColumnsSet];
          let needHandleKey = params.expTableType === "0" ? ["dtiskey", "mainiskey"] : ["mainiskey", "dtiskey"];
          needHandleArray[0] = needHandleArray[0].map(item => {
            if (item.com[0].type === "CHECKBOX" && item.com[0].key !== needHandleKey[0]) {
              item.com[0].otherParams = { hasBorder: true };
              item.com[0].viewAttr = "1";
            }
            return item;
          })
          needHandleArray[1] = needHandleArray[1].map(item => {
            if (item.com[0].type === "CHECKBOX" && item.com[0].key !== needHandleKey[1]) {
              item.com[0].viewAttr = "2";
              delete item.com[0].otherParams;
            }
            return item;
          })
          if (idx == 2 && regitDBIdValue) {
            // 主表字段列表
            return <div style={{ paddingLeft: 25, paddingRight: 25 }}><WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@k608wd`}
              rowKey="id"
              title={item.title}
              showCollapse={true}
              willDelete={this.willDelete}
              columns={this.getColumns(configSchememainTableColumnsSet)}
              tableProps={{
                showEmptyText: false
              }}
              willEdit={(datas, addData) => this.handleMainTable(datas, addData, 'mainis')}
              willAdd={(datas, addData) => this.addMainTable(datas, addData, 'mainis')}
              datas={status.configSchememainTableColumnsData}
              onChange={(datas) => archiveStore.setState({ configSchememainTableColumnsData: datas })}
              showCopy={false}
            />
            </div>
          }
          if (idx == 4 && status.configSchemehasDetail) {
            // 明细字段列表
            return <div style={{ paddingLeft: 25, paddingRight: 25 }}><WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@gy94su`}
              rowKey={'id'}
              title={item.title}
              showCollapse={true}
              willDelete={this.willDelete}
              tableProps={{
                showEmptyText: false
              }}
              willEdit={(datas, addData) => this.handleMainTable(datas, addData, 'dtis')}
              willAdd={(datas, addData) => this.addMainTable(datas, addData, 'dtis')}
              columns={this.getColumns(configSchemedetailTableColumnsSet)}
              datas={status.configSchemedetailTableColumnsData}
              onChange={(datas) => archiveStore.setState({ configSchemedetailTableColumnsData: datas })}
              showCopy={false}
            />
            </div>
          }
          if ((idx == 3 || idx == 4) && !status.configSchemehasDetail) {
            return <span></span>
          }
        })}
      </WeaRightMenu>
    </WeaDialog>
  }
}
