import React from "react";
import {inject, observer} from "mobx-react";
import {Button, message, Modal} from "antd";
import {checkTableFieldValueUnique} from "../../apis/CommonService";
import {toJS} from "mobx";
import {WeaSwitch} from "comsMobx";
import {
  WeaTableEdit,
  WeaSearchGroup,
  WeaInput,
  WeaFormItem,
  WeaTools,
  WeaRightMenu,
  WeaDialog,
  WeaSelect,
  WeaLocaleProvider,
  WeaHelpfulTip,
  WeaTableEditable,
} from "ecCom";
import uuid from 'uuid';
import copy from 'copy-to-clipboard';
import {
   onCheck,
   checkUnique,
} from '../../util/IntegrationUtil';
import PreviewDialog from "./PreviewDialog";
import SqlTestDialog from "./SqlTestDialog";
import IndexTestDialog from "./IndexTestDialog";

const {getKey} = WeaTools;
const {getLabel} = WeaLocaleProvider;
const {confirm} = Modal;
const {Base64} = WeaTools;

@inject("dataShowStore")
@observer
export default class NewForm extends React.Component {
   constructor(props) {
      super(props);
      this.state = {
        dialogStyle: {width: 1200, height: 700},
        regExpValue: /^(requestid|type|fielddbtype|currenttime|workflowid|wfid|billid|isbill|f_weaver_belongto_userid|f_weaver_belongto_usertype|wfTestStr|fieldid|viewtype|fromModule|wfCreate|_random_)$/gi,
        baseConfig: {
          validatePass: '',
          draggable: true,
          showAdd: true,
          showDelete: true,
          showCopy: false,
          showMove: false,
          showCollapse: true,
          tableProps: {showEmptyText: false, scroll: {x: "auto"}}
        },
        esbInitCells: {
          new_istitle: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_istitle"}]},
          new_issearch: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_issearch"}]},
          new_isshow: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_isshow"}]},
          new_fieldtype: {com: [{type: "SELECT", viewAttr: 1, hasBorder: true, key: "new_fieldtype", defaultValue: "2", options: [
            {disabled: false, key: "2", selected: true, showname: getLabel('22360', '文字'), visible: true},
            {disabled: false, key: "1", selected: false, showname: getLabel('607', '数字'), visible: true}
          ]}]},
          new_width: {com: [{type: "INPUTNUMBER", viewAttr: 1, hasBorder: true, key: "new_width", otherParams: {min: 1}}]},
          new_transql: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_transql"}]},
          new_wokflowfieldname: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_wokflowfieldname"}]},
        },
        esbIsShowTitleOpen: {
          new_istitle: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_istitle"}]},
          new_isshow: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_isshow"}]},
          new_issearch: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_issearch"}]},
          new_fieldtype: {com: [{type: "SELECT", viewAttr: 1, hasBorder: true, key: "new_fieldtype", defaultValue: "2", options: [
            {disabled: false, key: "2", selected: true, showname: getLabel('22360', '文字'), visible: true},
            {disabled: false, key: "1", selected: false, showname: getLabel('607', '数字'), visible: true}
          ]}]},
          new_wokflowfieldname: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_wokflowfieldname"}]},
         //  new_desensitization: {com: [{type: "CHECKBOX", viewAttr: 2, hasBorder: true, key: "new_desensitization"}]},
        },
        esbIsSearchOpen: {
          new_fieldname: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_fieldname"}]},
          new_issearch: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_issearch"}]},
          new_width: {com: [{type: "INPUTNUMBER", viewAttr: 1, hasBorder: true, key: "new_width", otherParams: {min: 1}}]},
          new_transql: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_transql"}]},
        },
        esbIsTitleOpen: {
          new_fieldname: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_fieldname"}]},
          new_issearch: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_issearch"}]}
        },
        initCells: {
          new_fieldtype: {com: [{type: "SELECT", viewAttr: 1, className: "inte-datashow-selectStyle", hasBorder: true, key: "new_fieldtype", defaultValue: "2", options: [
            {disabled: false, key: "2", selected: true, showname: getLabel('22360', '文字'), visible: true},
            {disabled: false, key: "1", selected: false, showname: getLabel('607', '数字'), visible: true}
          ]}]},
          new_width: {com: [{type: "INPUTNUMBER",viewAttr: 1,hasBorder: true,key: "new_width",otherParams: {min: 1}}]},
          new_transql: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_transql"}]},
          new_wokflowfieldname: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_wokflowfieldname"}]},
          new_isshow: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_isshow"}]},
        },
        isShowTitleOpen: {
          new_fieldtype: {com: [{
            type: "SELECT", viewAttr: 1, hasBorder: true, key: "new_fieldtype", defaultValue: "2", options: [
              {disabled: false, key: "2", selected: true, showname: getLabel('22360', '文字'), visible: true},
              {disabled: false, key: "1", selected: false, showname: getLabel('607', '数字'), visible: true}
            ]
          }]},
          new_isshow: {com: [{type: "CHECKBOX", viewAttr: 1, hasBorder: true, key: "new_isshow"}]},
          new_wokflowfieldname: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_wokflowfieldname"}]},
         //  new_desensitization: {com: [{type: "CHECKBOX", viewAttr: 2, hasBorder: true, key: "new_desensitization"}]},
        },
        isSearchOpen: {
          new_width: {com: [{type: "INPUTNUMBER",viewAttr: 1,hasBorder: true,key: "new_width", otherParams: {min: 1}}]},
          new_transql: {com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_transql"}]},
        },
        showClass_is_2_newWorkFlowFieldName: {
          com: [{type: "INPUT", viewAttr: 1, hasBorder: true, key: "new_wokflowfieldname"}]
        },
        // 脱敏设置
        // 允许设置二次验证
        new_desensitization_is_1_cells: {
          new_secondAuth: {com: [{type: "CHECKBOX", viewAttr: 2, hasBorder: true, key: "new_secondAuth"}]},
        },
        // 允许进行脱敏显示的设置
        allow_desensitization_cells: {
          new_desensitization: {com: [{type: "CHECKBOX", viewAttr: 2, hasBorder: true, key: "new_desensitization"}]},
        }
      }
   }

   getBtns = () => {
      const {
         dataShowStore,
      } = this.props, {
         newForm, 
         status, 
      } = dataShowStore, {
         dataShowFormHiddenFields,
         menus,
         buttonDisabled,
      } = status;
      const formParams = newForm.getFormParams();
      let btns = [];

      menus && menus.forEach(v => {
         if('BTN_TEST' === v.key) {
            if(!(formParams.datafrom == '4')) {
               btns.push(<Button 
                  ecId={`${this && this.props && this.props.ecId || ''}_Button@uhw4zj@integrationDatashowNewForm${v.key}`} 
                  type='primary' 
                  disabled={buttonDisabled}
                  onClick={() => this.onRightMenuClick(v.key)}
               >{v.content}</Button>);
            }
         }else if('BTN_GET_SEARCHPAGE' === v.key) {
            if (formParams.showclass == "2" && dataShowFormHiddenFields && dataShowFormHiddenFields.id) {
               btns.push(<Button 
                  ecId={`${this && this.props && this.props.ecId || ''}_Button@7xrrqn@integrationDatashowNewForm${v.key}`} 
                  type='primary' 
                  disabled={buttonDisabled}
                  onClick={() => this.onRightMenuClick(v.key)}
               >{v.content}</Button>);
            }
         }else {
            btns.push(<Button 
               ecId={`${this && this.props && this.props.ecId || ''}_Button@4kghxz@integrationDatashowNewForm${v.key}`} 
               type='primary' 
               disabled={buttonDisabled}
               onClick={() => this.onRightMenuClick(v.key)}
            >{v.content}</Button>);
         }
      })

      return btns;
   }

   getRightMenu = () => {
      const {
         dataShowStore,
      } = this.props, {
         newForm, 
         status, 
      } = dataShowStore, {
         dataShowFormHiddenFields,
         menus,
         buttonDisabled,
      } = status;
      const formParams = newForm.getFormParams();
      let btnArr = [];

      menus && menus.forEach(v => {
         if('BTN_TEST' === v.key) {
            if(!(formParams.datafrom == '4')) {
               btnArr.push({
                  key: v.key,
                  icon: <i className='icon-coms-Preservation'/>,
                  content: v.content,
                  disabled: buttonDisabled,
                  onClick: () => this.onRightMenuClick(v.key)
               })
            }
         }else if('BTN_GET_SEARCHPAGE' === v.key) {
            if (formParams.showclass == "2" && dataShowFormHiddenFields && dataShowFormHiddenFields.id) {
               btnArr.push({
                  key: v.key,
                  icon: <i className='icon-coms-Preservation'/>,
                  content: v.content,
                  disabled: buttonDisabled,
                  onClick: () => this.onRightMenuClick(v.key)
               });
            }
         }else {
            btnArr.push({
               key: v.key,
               icon: <i className='icon-coms-Preservation'/>,
               content: v.content,
               disabled: buttonDisabled,
               onClick: () => this.onRightMenuClick(v.key)
            });
         }
      }); 

      return btnArr;
   }

   isValidFieldKey = () => {
      const {dataShowStore} = this.props;
      const {newForm} = dataShowStore;
      const formParams = newForm.getFormParams();
      if(formParams.keyfield && formParams.keyfield.trim()) {
         let isValid = /^(requestid|type|fielddbtype|currenttime|workflowid|wfid|billid|isbill|f_weaver_belongto_userid|f_weaver_belongto_usertype|wfTestStr|fieldid|viewtype|fromModule|wfCreate|_random_)$/gi.test(formParams.keyfield);
         if(isValid) {
            newForm.showError('keyfield', `${formParams.keyfield.trim()}${getLabel('519489','不允许作为主键')}`);
            return false;
         }
      }
      return true;
   }

   onRightMenuClick = (type) => {
      const {dataShowStore} = this.props;
      const {newForm, source} = dataShowStore;
      const {dataShowFormHiddenFields, WebserviceMethodParameterDatas, specialDatas, WeaTableEdit_MergedFieldData, esbSearchDatas, esbShowDatas} = toJS(dataShowStore.status);
      const formParams = newForm.getFormParams();
      let {showname, sqltext, searchById, showclass, showtype, datafrom} = formParams;

      if (['BTN_SAVE', 'BTN_TEST'].includes(type)) {
         dataShowStore.setState({type});
         if('BTN_SAVE' === type) {
            dataShowStore.setState({buttonDisabled: true});
         }

         //必填的校验  ESB
         if (formParams.datafrom != '4' || (formParams.datafrom == "4" && formParams.showtype == "3")) {
            let hideFieldKeys = ["esbid", "esbshowid"];
            if(formParams.datafrom == '3' && formParams.showtype == '1' && formParams.unconditionalQuery != '1') {
               hideFieldKeys.push('sqltext1');
            }
            window.e9HideFormFieldKeys = hideFieldKeys;
         }
         if (formParams.datafrom == '4' && formParams.showclass == '2') {
            window.e9HideFormFieldKeys = ["esbshowid"];
         }

         onCheck(newForm, () => {
            // 必填的校验       
            if ((!formParams.customhref) && (formParams.showtype == '3' || formParams.datafrom == '2')) {
               newForm.showError('customhref', getLabel('507143', '“自定义地址”未填写'));
               dataShowStore.setState({buttonDisabled: false});
               return;
            }
   
            if (formParams.datafrom == '3' && (formParams.showtype == '2' || (formParams.showtype == '1' && formParams.unconditionalQuery == '1'))) {
               if (!formParams.sqltext1) {
                  newForm.showError('sqltext1', getLabel('506472', '“无条件查询”未填写'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
               if ((!formParams.searchById1) && formParams.showclass != '2') {
                  newForm.showError('searchById1', getLabel('506473', '“回显查询”未填写'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
            }

            if (formParams.datafrom == '1' && (formParams.showtype != '3')) {
               if (!formParams.sqltext) {
                  newForm.showError('sqltext', getLabel('506474', '“查询SQL语句”未填写'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
            }

            if (formParams.datafrom == '0' && (formParams.showtype != '3')) {
               if (!formParams.wsurl) {
                  newForm.showError('wsurl', getLabel('507142', '“WebService地址”未填写'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
               if (!formParams.wsoperation) {
                  newForm.showError('wsoperation', getLabel('507141', '“WebService方法”未填写'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
            }

            // 当数据来源为数据库时，查询sql不允许以delete开头
            if(datafrom == '1') {
               if(sqltext && sqltext.trim() && (!(sqltext.trim().toLowerCase()).startsWith('select'))) {
                  newForm.showError("sqltext", getLabel('513870','查询SQL语句需要以select开始'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               } 
               if(searchById && searchById.trim() && (!(searchById.trim().toLowerCase()).startsWith('select'))) {
                  newForm.showError("searchById", getLabel('513894','回显SQL语句需要以select开始'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
            }

            // 数据来源datafrom为存储过程3的时候，需要检测回显查询searchById1是否含有不允许的字段
            if (formParams.datafrom == '3') {
               if (formParams.searchById1) {
                  if ((/{?[A-Za-z0-9]}/).test(formParams.searchById1)) {
                     newForm.showError('searchById1', getLabel('506393', '不允许使用人员变量'));
                     dataShowStore.setState({buttonDisabled: false});
                     return;
                  }
               }
            }

            // 主键字段不允许设置的值
            if(!this.isValidFieldKey()) {
               dataShowStore.setState({buttonDisabled: false});
               return;
            } 

            // 校验参数设置必填项validator
            if (formParams.showtype == 1 || formParams.showclass == 2) {
               let result = this.table ? this.table.doValidate() : {};
               this.setState({validatePass: result.pass})
               if (!result.pass) {
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               };
            }

            // 参数设置中显示字段设置必填验证
            if (datafrom == "4" && showtype == "1") {
               // ESB检测ESB查询服务中的查询参数必须存在于字段设置中
               let esbParamName = [], flag = false;
               esbSearchDatas && esbSearchDatas.forEach(data => {
                  if (data.paramtype === "3") {
                     flag = true;
                     if (WeaTableEdit_MergedFieldData && WeaTableEdit_MergedFieldData.find(v => v.new_fieldname === data.paramname)) {
                        if (WeaTableEdit_MergedFieldData.find(v => v.new_fieldname === data.paramname).new_issearch == 0) {
                           esbParamName.push(data.paramname);
                        }
                     } else {
                        esbParamName.push(data.paramname);
                     }
                  }
               })
               if (!flag) {
                  message.error(getLabel('511544', 'ESB查询服务中至少需要配置一个条件查询字段类型'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               } else if (flag && esbParamName && esbParamName.length) {
                  message.error(`${getLabel('511547', '字段设置中需要设置')}【${esbParamName.join(',')}】${getLabel('511549', '查询字段')}`);
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
            }

            //显示标题字段必须要有1个验证
            if (((showclass == "1" && showtype == "1") || showclass == "2")) {
               let hasTitleField = false;
               if (WeaTableEdit_MergedFieldData && WeaTableEdit_MergedFieldData.length > 0) {

                  for (let j = 0, len = WeaTableEdit_MergedFieldData.length; j < len; j++) {
                     let o = WeaTableEdit_MergedFieldData[j];
                     if (o.new_istitle == "1") {
                        hasTitleField = true;
                        break;
                     }
                  }
               }
               if (!hasTitleField) {
                  message.error(getLabel(82993, '请设置标题栏字段'));
                  dataShowStore.setState({buttonDisabled: false});
                  return;
               }
               // 至少设置一个check框可选
               for (let i = 0; i < WeaTableEdit_MergedFieldData.length; i++) {
                  let data = WeaTableEdit_MergedFieldData[i];
                  if (!(Number(data.new_istitle) || Number(data.new_islist) || Number(data.new_issearch))) {
                     message.error(getLabel(389329, '请至少设置查询字段或者显示字段'));
                     dataShowStore.setState({buttonDisabled: false});
                     return;
                  }
               }
            }

            // 判断字段/XML路径重复
            let newLists = [];
            for (let i = 0; i < WeaTableEdit_MergedFieldData.length; i++) {
               let data = WeaTableEdit_MergedFieldData[i];
               if (data.new_islist == '1') {
                  if (newLists.indexOf(data.new_fieldname) != -1) {
                     message.error(getLabel('389333,18082', '字段/XML路径重复'));
                     dataShowStore.setState({buttonDisabled: false});
                     return;
                  } else {
                     newLists.push(data.new_fieldname);
                  }
               }
            }

            // 测试的时候新增的一个判断
            if (type === "BTN_TEST") {
               let flg = true;
               let flg3 = true;
               if (formParams.datafrom === '3' && formParams.showtype === '1' && formParams.searchByName && (/[#]+[_a-zA-Z0-9]+[#]/).test(formParams.searchByName)) {
                  let new_fieldnames = [];
                  let array = formParams.searchByName.match(/[#]+[_a-zA-Z0-9]+[#]/g);
      
                  for (let i = 0; i < WeaTableEdit_MergedFieldData.length; i++) {
                     let data = WeaTableEdit_MergedFieldData[i];
                     new_fieldnames.push(data.new_fieldname);
                     array.map(function (value, index) {
                        value = value.replace(/#/g, "");
                        if (data.new_fieldname == value) {
                           //查询字段
                           if (!Number(data.new_issearch)) {
                              flg3 = false;
                           }
                        }
                     });
                  }
                  //条件查询参数必须在字段设置中字段/XML路径存在
                  array.map(function (value, index) {
                     value = value.replace(/#/g, "");
                     if (new_fieldnames.toString().indexOf(value) <= -1) {
                        flg = false;
                     }
                  });
               }
      
               if (!flg) {
                  message.error(getLabel('510639', '条件查询参数必须在字段设置中字段/XML路径存在'));
                  return;
               }
               if (!flg3) {
                  message.error(getLabel('510639', '条件查询参数需要在字段设置中的查询字段存在'));
                  return;
               }
            }
           
            // 保存的真正逻辑 标识唯一性检查
            let id = dataShowFormHiddenFields.id || "";

            checkUnique({
               tableName: 'datashowset',
               fieldName: 'showname',
               fieldValue: showname.replace(/^(\s*)|(\s*)$/g, ''),
            }, newForm, 'showname', '2', id, () => {
               let params = Object.assign({}, dataShowFormHiddenFields, {
                  ...formParams,
                  sqltext: Base64.encode(sqltext || ""),
                  searchById: Base64.encode(searchById || ""),
                  isPhyPage: formParams.isPhyPage != "1" ? "2" : "1",
                  operator: "save"
               });
               if (source && id == "") {
                  params.typename = source;
               }
               let datas = WeaTableEdit_MergedFieldData && WeaTableEdit_MergedFieldData.map(data => {
                  let transSQL = data.new_transql ? data.new_transql : '';
                  return Object.assign({}, data, {new_transql: Base64.encode(transSQL)});
               })

               let searchDatas = esbSearchDatas.concat(specialDatas).map(v => {
                  if (["pageNo", "startNo", "endNo", "pagesize"].includes(v.paramname.trim())) {
                     return Object.assign({}, v, {paramtype: "5"});
                  } else if(["eventType"].includes(v.paramname.trim())) {
                     return Object.assign({}, v, {paramtype: "6"});
                  } else return v;
               })

               dataShowStore.getDataShowOperation({
                  ...params,
                  type,
                  dtinfo_MergedFieldData: JSON.stringify(datas),
                  dtinfo_WebserviceMethodParameterDatas: JSON.stringify(WebserviceMethodParameterDatas),
                  dtinfo_EsbsearchParameterDatas: JSON.stringify(searchDatas),  // esb相关的数据
                  dtinfo_EsbshowParameterDatas: JSON.stringify(esbShowDatas),   // esb相关的数据
               });
            }, {}, () => {
               dataShowStore.setState({buttonDisabled: false});
            })
         }, () => {
            dataShowStore.setState({buttonDisabled: false});
         });
      } else if (type == "BTN_GET_SEARCHPAGE") {
         this.viewSearchUrl();
      } 
   };

   viewSearchUrl = () => {
      const {dataShowStore} = this.props;
      const {newForm, status} = dataShowStore;
      const {dataShowFormHiddenFields} = toJS(status);

      if (newForm.getFormParams().showclass == "2") {
         confirm({
            content: (window.ecologyContentPath || "") + "/spa/inte/static/index.html#/main/inte/tab/" + dataShowFormHiddenFields.id,
            okText: getLabel("77", "复制"),
            cancelText: getLabel(31129, "取消"),
            onOk: () => {
               if (copy(`${window.ecologyContentPath || ""}/spa/inte/static/index.html#/main/inte/tab/${dataShowFormHiddenFields.id}`)) {
                  message.success(getLabel('126081', '地址已经复制成功，您可以使用Ctrl+v粘贴'));
               }
            },
            onCancle: () => {
            },
         })
      } else {
         message.info(getLabel(32324, '当前展现集成不是查询页面，请重新操作'));
      }
   }

   willEdit = (datas = [], editData) => {
      const {dataShowStore} = this.props;
      const formParams = dataShowStore.newForm.getFormParams();
      const {record, key, index, value} = editData;

      if("new_islist" === key) {
         if(record.new_fieldname && formParams.keyfield && record.new_fieldname.trim() && formParams.keyfield.trim() && record.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase()) {
            datas[index] = {
               ...datas[index],
               new_desensitization: record.new_desensitization ? '0' : '',
               new_secondAuth: record.new_secondAuth ? '0' : '',
            }
         } else {
            if(value == '0') {
               datas[index] = {
                  ...datas[index],
                  new_istitle: '0',
               }
   
               if(record.new_issearch == '1') {
                  datas[index] = {
                     ...datas[index],
                     new_desensitization: record.new_desensitization ? '0' : '',
                     new_secondAuth: record.new_secondAuth ? '0' : '',
                  }
               }
            }
         }
      } else if("new_issearch" === key) {
         if(record.new_fieldname && formParams.keyfield && record.new_fieldname.trim() && formParams.keyfield.trim() && record.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase()) {
            datas[index] = {
               ...datas[index],
               new_desensitization: record.new_desensitization ? '0' : '',
               new_secondAuth: record.new_secondAuth ? '0' : '',
            }
         } else {
            if(value == '0') {
               datas[index] = {
                  ...datas[index],
                  new_isshow: '0',
                  new_istitle: '0',
               }
            } else if(value == '1' && record.new_islist != '1') {
               datas[index] = {
                  ...datas[index],
                  new_desensitization: record.new_desensitization ? '0' : '',
                  new_secondAuth: record.new_secondAuth ? '0' : '',
               }
            }
         }
      } else if("new_istitle" === key) {
         if (value == '1') {
            let preIndex = datas.find(data => data.new_istitle == '1' && data.id != record.id);
            if (preIndex) {
              preIndex.new_istitle = '0';
            }
            datas.forEach((data, index) => {
              if (data.id === record.id) {
                datas[index] = {
                  ...datas[index],
                  new_istitle: '1',
                  new_issearch: '1',
                  new_islist: '1',
                  new_desensitization: record.new_desensitization ? '0' : '',
                  new_secondAuth: record.new_secondAuth ? '0' : '',
                }
              }
             })
         } else {
            if(record.new_fieldname && formParams.keyfield && record.new_fieldname.trim() && formParams.keyfield.trim() && record.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase()) {
               datas[index] = {
                  ...datas[index],
                  new_desensitization: record.new_desensitization ? '0' : '',
                  new_secondAuth: record.new_secondAuth ? '0' : '',
               }
            }
         }
      } else if("new_desensitization" === key) {
         // 没有选择脱敏显示的情况下，【二次身份校验】为禁用
         if(value != '1') {
            datas[index] = {
               ...datas[index],
               new_secondAuth: record.new_secondAuth ? '0' : '',
             } 
         }
      } else if("new_fieldname" === key) {
         // 主键字段不可以进行脱敏显示设置
         if(value && formParams.keyfield && value.trim() && formParams.keyfield.trim() && value.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase()) {
            datas[index] = {
               ...datas[index],
               new_desensitization: record.new_desensitization ? '0' : '',
               new_secondAuth: record.new_secondAuth ? '0' : '',
            } 
         }
      }
      dataShowStore.setState({WeaTableEdit_MergedFieldData: datas});
   };

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

   willEditESB = (allDatas, editDatas, key) => {
      const {dataShowStore} = this.props;
      const {WeaTableEdit_MergedFieldData} = toJS(dataShowStore.status);
      const {key: editKey, value, record} = editDatas;
      let mergedDatas = [...WeaTableEdit_MergedFieldData];
      if (editKey == "paramtype") {
         allDatas && allDatas.forEach((v, index) => {
            if (v.paramname === record.paramname) {
               allDatas[index] = {
                  ...allDatas[index],
                  paramvalue: ""
               }
            }
         })
         if (value === '3' && record.paramtype != '3' && key === "esbid") {
            let index = mergedDatas.findIndex(v => v.new_fieldname === record.paramname && v.new_issearch == '1');
            if (index === -1) {
               mergedDatas.push({
                  id: uuid(),
                  new_fieldname: record.paramname,
                  new_issearch: '1',
                  new_fieldtype: '2'
               })
            }
         }
         if (value != '3' && record.paramtype == '3' && key === "esbid") {
            let index = mergedDatas.findIndex(v => v.new_fieldname === record.paramname && v.new_issearch == '1');
            if (index != -1) {
               mergedDatas.splice(index, 1);
            }
         }
         // 只能有一个主键
         if (key === "esbshowid") {
            if (value === '3') {
               allDatas && allDatas.forEach((v, index) => {
                  if ((v.paramname != record.paramname) && v.paramtype === '3') {
                     allDatas[index] = {
                        ...allDatas[index],
                        paramtype: ''
                     }
                  }
               })
               dataShowStore.newForm.updateFields({keyfield: record.paramname});
            } else {
               let keyField = allDatas && allDatas.find(v => v.paramtype === "3");
               if (keyField) {
                  dataShowStore.newForm.updateFields({keyfield: keyField.paramname});
               } else {
                  dataShowStore.newForm.updateFields({keyfield: ""});
               }
            }
         }
      }
      dataShowStore.setState({[key === "esbid" ? "esbSearchDatas" : "esbShowDatas"]: allDatas});
      if (key === "esbid") {
         dataShowStore.setState({WeaTableEdit_MergedFieldData: mergedDatas});
      }
   };

   getESBColumns = (columns, key) => {
      const {newForm} = this.props.dataShowStore;
      const formParams = newForm.getFormParams();
      columns && columns.forEach(v => {
         if (v.dataIndex === "paramtype" && key === "esbid") {
            let options = [...v.com[0].options];
            if (formParams.showclass === "2") {
               let index = options.findIndex(option => option.key === "2");
               options.splice(index, 1);
            }
            if (formParams.isSupportPaging == 0) {
               let index = options.findIndex(option => option.key === "5");
               options.splice(index, 1);
            }
            v.com[0] = {
               type: "custom",
               key: v.key,
               render: (text, record, index, onEdit) => {
                  if (["pageNo", "startNo", "endNo", "pagesize", "eventType"].includes(record.paramname)) {
                     return <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@ma23gc`}
                        options={options}
                        value={["pageNo", "startNo", "endNo", "pagesize"].includes(record.paramname) ? "5" : "6"}
                        viewAttr={1}
                        hasBorder
                     />
                  } else {
                     let option = options.slice(0);
                     // 去除分页参数
                     let index1 = option.findIndex(v => v.key === "5");
                     if (index1 != -1) {
                        option.splice(index1, 1);
                     }
                     // 去除接口类型
                     let idx = option.findIndex(v => v.key === "6");
                     if (idx != -1) {
                        option.splice(idx, 1);
                     }
                     return <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@0w1bqg`}
                        options={option}
                        value={record.paramtype}
                        viewAttr={2}
                        onChange={value => onEdit({
                           type: "CUSTOM",
                           record,
                           index,
                           key: v.dataIndex,
                           value,
                        })}
                     />
                  }
               }
            }
         } else if (v.dataIndex === "paramvalue") {
            v.com[0] = {
               type: "custom",
               key: v.key,
               render: (text, record, index, onEdit) => {
                  if ((["3", "5"].includes(record.paramtype) && key === "esbid") || (record.paramtype == 3 && key === "esbshowid")) {
                     return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@a8vem1`} value={""} viewAttr={1}/>
                  } else if ((["2", "1", "4"].includes(record.paramtype) && key === "esbid") || (["2", "1"].includes(record.paramtype) && key === "esbshowid")) {
                     let paramvalue = "";
                     try {
                        paramvalue = record.paramvalue ? JSON.parse(record.paramvalue) : "";
                     } catch (err) {
                        paramvalue = "";
                     }
                     return <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@23x5i3`}
                        value={record.paramvalue}
                        onChange={value => onEdit({
                           type: "CUSTOM",
                           record,
                           index,
                           key: v.dataIndex,
                           value
                        })}
                     />
                  }
               }
            }
         }
      })
   };

   getMergedCells = (datas = []) => {
      const {newForm} = this.props.dataShowStore;
      const {
         esbIsTitleOpen, 
         esbIsShowTitleOpen, 
         esbIsSearchOpen, 
         esbInitCells, 
         initCells, 
         isShowTitleOpen, 
         isSearchOpen,
         showClass_is_2_newWorkFlowFieldName,
         new_desensitization_is_1_cells,
         allow_desensitization_cells,
      } = this.state;
      const formParams = newForm.getFormParams();
      let cells = [];

      if (formParams.datafrom == "4" && formParams.showtype != "3") {
         datas && datas.forEach(data => {
            let itemCells = {};
            
            // 优化之前的写法： 相关任务QC699869
            if(formParams.showclass === "2") {

               itemCells = {
                  ...itemCells,
                  new_wokflowfieldname: showClass_is_2_newWorkFlowFieldName,
               }
            }

            // // 主键字段, 标题栏字段不可以进行脱敏显示设置
            // if((data.new_fieldname && formParams.keyfield && data.new_fieldname.trim() && formParams.keyfield.trim() && data.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase()) || data.new_istitle == '1') {
               
            //    itemCells = {
            //       ...itemCells,
            //       ...new_istitle_or_primaryKey_is_1_cells,
            //    }
            // }

            // new_desensitization_is_1,进行二次验证的设置
            if(data.new_desensitization == '1') {

               itemCells = {
                  ...itemCells,
                  ...new_desensitization_is_1_cells,
               }
            }

            if (data.new_istitle == '1' || (data.new_issearch == '1' && data.new_islist == '1')) {
               itemCells = {
                  ...esbIsTitleOpen,
                  ...itemCells,
               }
               if(data.new_istitle != '1' && data.new_issearch == '1' && data.new_islist == '1') {
                  if(!(data.new_fieldname && formParams.keyfield && data.new_fieldname.trim() && formParams.keyfield.trim() && data.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase())) {
                     itemCells = {
                        ...itemCells,
                        ...allow_desensitization_cells,
                     }
                  }
               }
            } else {
               if (data.new_issearch == '1') {
                  itemCells = {
                     ...esbIsSearchOpen,
                     ...itemCells,
                  }
               } else if (data.new_islist == '1') {
                  itemCells = {
                     ...esbIsShowTitleOpen,
                     ...itemCells,
                  };
                  if(!(data.new_fieldname && formParams.keyfield && data.new_fieldname.trim() && formParams.keyfield.trim() && data.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase())) {
                     itemCells = {
                        ...itemCells,
                        ...allow_desensitization_cells,
                     }
                  }
               } else {
                  itemCells = {
                     ...esbInitCells,
                     ...itemCells,
                  };
               }
            }

            if(Object.keys(itemCells) && Object.keys(itemCells).length) {
               cells.push({
                  id: data.id,
                  ...itemCells
               });
            }
         })
      } else {
         datas && datas.forEach(data => {
            let itemCells = {};
            
            // 优化之前的写法： 相关任务QC699869
            if(formParams.showclass === "2") {

               itemCells = {
                  ...itemCells,
                  new_wokflowfieldname: showClass_is_2_newWorkFlowFieldName,
               }
            }

            // // 主键字段, 标题栏字段不可以进行脱敏显示设置
            // if((data.new_fieldname && formParams.keyfield && data.new_fieldname.trim() && formParams.keyfield.trim() && data.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase()) || data.new_istitle == '1') {
               
            //    itemCells = {
            //       ...itemCells,
            //       ...new_istitle_or_primaryKey_is_1_cells,
            //    }
            // }

            // new_desensitization_is_1,进行二次验证的设置
            if(data.new_desensitization == '1') {

               itemCells = {
                  ...itemCells,
                  ...new_desensitization_is_1_cells,
               }
            }
            if (data.new_istitle == '1' || (data.new_islist == '1' && data.new_issearch == '1')) {
               if(data.new_istitle != '1' && data.new_islist == '1' && data.new_issearch == '1') {
                  if(!(data.new_fieldname && formParams.keyfield && data.new_fieldname.trim() && formParams.keyfield.trim() && data.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase())) {
                     itemCells = {
                        ...itemCells,
                        ...allow_desensitization_cells,
                     }
                  }
               }
            } else {
               if (data.new_issearch == '1') {
                  itemCells = {
                     ...isSearchOpen,
                     ...itemCells,
                  }
               } else if (data.new_islist == '1') {
                  itemCells = {
                     ...isShowTitleOpen,
                     ...itemCells,
                  }
                  if(!(data.new_fieldname && formParams.keyfield && data.new_fieldname.trim() && formParams.keyfield.trim() && data.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase())) {
                     itemCells = {
                        ...itemCells,
                        ...allow_desensitization_cells,
                     }
                  }
               } else {
                  itemCells = {
                     ...initCells,
                     ...itemCells,
                  }
               }
            }

            if(Object.keys(itemCells) && Object.keys(itemCells).length) {
               cells.push({
                  id: data.id,
                  ...itemCells
               });
            }
         })
      }

      return cells;
   };

   getESBSearchDatas = (flag) => {
      const {dataShowStore} = this.props;
      const {specialDatas, esbSearchDatas} = toJS(dataShowStore.status);
      let datas = [], special = [];
      if (flag == 0) {
         esbSearchDatas && esbSearchDatas.forEach(v => {
            if (!["pageNo", "startNo", "endNo", "pagesize"].includes(v.paramname.trim())) {
               datas.push(v);
            } else {
               special.push(v);
            }
         })
      } else {
         datas = esbSearchDatas.concat(specialDatas);
         special = [];
      }
      dataShowStore.setState({esbSearchDatas: datas, specialDatas: special});
   }

  getMergedDatas = () => {
    const {dataShowStore} = this.props;
    const {esbSearchDatas, WeaTableEdit_MergedFieldData} = toJS(dataShowStore.status);
    let mergedDatas = [...(WeaTableEdit_MergedFieldData || [])];

    esbSearchDatas && esbSearchDatas.map(record => {
      if(record.paramtype == '3') {
        let index = mergedDatas && mergedDatas.findIndex(v => v.new_fieldname === record.paramname && v.new_issearch == '1');
        if(index == -1) {
          mergedDatas.push({
            id: uuid(),
            new_fieldname: record.paramname,
            new_issearch: '1',
            new_fieldtype: '2'
          })
        }
      }
    })
    dataShowStore.setState({WeaTableEdit_MergedFieldData: mergedDatas});
  }

   getKeyField = () => {
      const {dataShowStore} = this.props;
      const {esbShowDatas} = toJS(dataShowStore.status);
      let keyfield = "";

      if (esbShowDatas && esbShowDatas.length) {
         let keyField = esbShowDatas.find(v => v.paramtype === "3");
         if (keyField) {
            keyfield = keyField.paramname;
         }
      }
      return keyfield;
   }

   onChangeFields = (key, otherParams) => {
      const {dataShowStore} = this.props;
      const {newForm, status} = dataShowStore;
      const datas = status.WeaTableEdit_MergedFieldData;
      const formParams = newForm.getFormParams();
      let keyfield = this.getKeyField();

      if (key === 'wsurl') {
         dataShowStore.getDataShowOperation({wsid: formParams.wsurl, operator: 'getregisteinfo'}, () => {
            newForm.updateFields({wsoperation: ""});
         });
      } else if (key === 'wsoperation') {
         dataShowStore.getDataShowOperation({methodid: formParams.wsoperation, operator: 'getmethodinfo'});
      } else if (key === "esbid") {
         if (formParams.esbid != otherParams.esbid) {
            dataShowStore.setState({WeaTableEdit_MergedFieldData: []});
            if (formParams.esbid) {
               dataShowStore.getDataShowOperation({esbid: formParams.esbid, operator: "getSearchEsbinfo"});
            } else {
               dataShowStore.setState({esbSearchDatas: []});
            }
         }
      } else if (key === "esbshowid") {
         if (formParams.esbshowid != otherParams.esbshowid) {
            newForm.updateFields({keyfield: ""});
            if (formParams.esbshowid) {
               dataShowStore.getDataShowOperation({esbid: formParams.esbshowid, operator: "getEsbinfo"});
            } else {
               dataShowStore.setState({esbShowDatas: []});
            }
         }
      } else if (key === "isSupportPaging") {
         this.getESBSearchDatas(formParams.isSupportPaging);
      } else if (key === 'showclass') {
         if (formParams.datafrom == '4' && formParams.showtype != '3' && formParams.showclass == '1') {
            newForm.updateFields({keyfield});
         }
         if (formParams.showclass == '2') {
            newForm.updateFields({showtype: "1"});
            if (formParams.datafrom == '4') {
               this.getMergedDatas();
            }
         }
         dataShowStore.getOpenPyhStatus();
      } else if (key === 'showname' && formParams.showname != "") {
         let checkParams = {
            tableName: 'datashowset',
            fieldName: 'showname',
            fieldValue: formParams.showname.replace(/^(\s*)|(\s*)$/g, ''),
         };
         checkTableFieldValueUnique(checkParams).then(result => {
            if (result && result.isNotUnique) {
               newForm.showError('showname', getLabel('387654', '标识已存在'));
            }
         });
      } else if (key === 'datafrom') {
         newForm.updateFields({
            sqltext: '',
            searchById: '',
            sqltext1: '',
            searchByName: '',
            searchById1: '',
            wsurl: '',
            wsoperation: '',
            wsworkname: '',
            customhref: ''
         });
         if (formParams.datafrom == '4' && formParams.showtype != '3' && formParams.showclass == '1') {
            newForm.updateFields({keyfield});
         }
         if (formParams.datafrom == "4" && formParams.showtype == '1') {
            this.getMergedDatas();
         } else {
            dataShowStore.setState({WeaTableEdit_MergedFieldData: []})
         }
         dataShowStore.getOpenPyhStatus();
      } else if (key === "showtype") {
         if (formParams.showtype == '2' && formParams.datafrom == '4') {
            newForm.updateFields({isSupportPaging: 0});
            this.getESBSearchDatas(0);
         }
         if (formParams.datafrom == '4' && formParams.showtype != '3' && formParams.showclass == '1') {
            newForm.updateFields({keyfield});
         }
         if (formParams.showtype == '1' && formParams.datafrom == '4') {
            this.getMergedDatas();
         } else {
            dataShowStore.setState({WeaTableEdit_MergedFieldData: []});
         }
         dataShowStore.getOpenPyhStatus();
      } else if ("datasourceid" === key) {
         dataShowStore.getOpenPyhStatus();
      } 
   }

   // 对主键失去焦点后的信息判断
   checkKeyField = () => {
      const {dataShowStore} = this.props;
      const {newForm, status} = dataShowStore;
      const datas = status.WeaTableEdit_MergedFieldData;
      const formParams = newForm.getFormParams();

      if(this.isValidFieldKey()) {
         // 如果字段设置中设置了主键，则不可进行显示设置
         let checkTrue = false;

         datas && datas.forEach((data, index) => {
            if(data.new_fieldname && formParams.keyfield && data.new_fieldname.trim() && formParams.keyfield.trim() && data.new_fieldname.trim().toLowerCase() === formParams.keyfield.trim().toLowerCase()) {
               checkTrue = true;
               datas[index] = {
                  ...datas[index],
                  new_desensitization: data.new_desensitization ? '0' : '',
                  new_secondAuth: data.new_secondAuth ? '0' : ''
               }
            }
         })

         if(checkTrue) {
            dataShowStore.setState({WeaTableEdit_MergedFieldData: datas});
         }
      }
   }

   getHideFields = (key, allParams) => {
      const {showOpenPyh} = this.props.dataShowStore.status;
      let bool = false;

      key === 'showtype' && allParams.showclass == '2' && (bool = true);
      key === 'datafrom' && (allParams.showtype == '3' && allParams.showclass == '1') && (bool = true);
      key === 'datasourceid' && (!['1', '3'].includes(allParams.datafrom) || allParams.showtype == '3') && (bool = true);
      key === 'sqltext' && (allParams.showtype == '3' || allParams.datafrom != '1') && (bool = true);
      key === 'searchById' && (allParams.showtype == '3' || allParams.datafrom != '1' || allParams.showclass == '2') && (bool = true);
      key === 'keyfield' && allParams.showtype == '3' && (bool = true);
      key === 'wsurl' && (allParams.datafrom != '0' || allParams.showtype == '3') && (bool = true);
      key === 'wsoperation' && (allParams.datafrom != '0' || allParams.showtype == '3') && (bool = true);
      key === 'wsworkname' && (allParams.datafrom != '0' || allParams.showtype == '3') && (bool = true);
      key === 'parentfield' && (allParams.showtype != '2' || allParams.showclass == "2") && (bool = true);
      key === 'showfield' && (allParams.showtype != '2' || allParams.showclass == "2") && (bool = true);
      key === 'onlylowestnode' && (allParams.showtype != '2' || allParams.showclass == "2" || (allParams.showtype == '2' && ['3', '4'].includes(allParams.datafrom))) && (bool = true);
      key === 'customhref' && (allParams.showtype != '3' && allParams.datafrom != '2') && (bool = true);
      key === 'sqltext1' && (allParams.datafrom != '3' || allParams.showtype == '3' || (allParams.datafrom == '3' && allParams.showtype == '1' && allParams.unconditionalQuery != '1')) && (bool = true);
      key === 'searchByName' && (allParams.datafrom != '3' || allParams.showtype == '3') && (bool = true);
      key === 'searchById1' && (allParams.datafrom != '3' || allParams.showtype == '3') && (bool = true);
      key === 'characterset' && (allParams.datafrom != '2') && (bool = true);
      key === 'showpageurl' && (allParams.showclass != '1' || allParams.showtype != '1' || allParams.datafrom != '1') && (bool = true);
      key === 'searchById1' && (allParams.showclass == '2' && allParams.datafrom == '3') && (bool = true);
      key === 'unconditionalQuery' && (allParams.showtype == '2') && (bool = true);
      ["isSupportPaging", "esbid", "esbshowid"].includes(key) && (allParams.datafrom != '4' || allParams.showtype == '3') && (bool = true);
      ["esbshowid"].includes(key) && (allParams.showclass === "2") && (bool = true);
      ["isSupportPaging"].includes(key) && (allParams.showtype === "2" && allParams.datafrom == '4') && (bool = true);
      "isPhyPage" === key && (!showOpenPyh) && (bool = true);
      
      return bool;
   }

   getHelpfulTip = (key) => {
      if (key === 'isSupportPaging') {
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@kpzlh5`} style={{position: 'relative', left: 20}} width={400} title={
            <div>
               <p>{getLabel('511394', '需要第三方接口支持分页查询，目前分页方式有三种')}:</p>
               <p>1.{getLabel('511390', '行号方式，最小行号~最大行号；例如 1~20')};</p>
               <p>2.{getLabel('511391', '页码+数量，例如 第3页，每页数量20')};</p>
               <p>3.{getLabel('511392', '行号+数量，例如从第20行起获取20条数据')}。</p>
            </div>
         }/>
      } else if (key === 'sqltext') {
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@y0a6gg`} style={{position: 'relative', left: 20, top: -35}} width={400}
                               title={getLabel('506846', '参数可设置如下内容：当前用户id，格式为{?userid}；当前用户登陆账号，格式为{?loginid}；当前用户姓名，格式为{?username}；当前用户编号，格式为{?workcode}；当前用户密码(MD5格式)，格式为{?password}；当前用户部门id，格式为{?departmentid}；当前用户部门编码，格式为{?departmentcode}；当前用户部门名称，格式为{?departmentname}；当前用户分部id，格式为{?subcompanyid}；当前用户分部编码，格式为{?subcompanycode}；当前用户分部名称，格式为{?subcompanyname}；多语言数据列显示，{？userlanguage}。若联动主表字段，格式为$主表字段名$；若联动明细表字段，格式为$明细表表明_明细表字段名$')}/>
      } else if (key === 'searchById') {
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@p4vg6u`} style={{position: 'relative', left: 20, top: -35}} width={196}
                               title={getLabel('127946', '不设置表示与查询SQL语句相同')}/>
      } else if (key === 'detailpageurl') {
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@0ynf3k`} style={{position: 'relative', left: 20, top: -7}} width={400}
                               title={getLabel('82995,82996,82997,82998,82999', '参数可设置如下内容：当前用户id，格式为{?userid}；当前用户登陆账号，格式为{?loginid}；当前用户姓名，格式为{?username}；当前用户编号，格式为{?workcode}；当前用户密码(MD5格式)，格式为{?password}；当前用户部门id，格式为{?departmentid}；当前用户部门编码，格式为{?departmentcode}；当前用户部门名称，格式为{?departmentname}；当前用户分部id，格式为{?subcompanyid}；当前用户分部编码，格式为{?subcompanycode}；当前用户分部名称，格式为{?subcompanyname}；')}/>
      } else if (key === 'customhref') {
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@m2lu1g`} style={{position: 'relative', left: 20, top: -35}} width={400}
                               title={getLabel('82994,82995,82996,82997,82998,82999', '参数可设置如下内容：当前用户id，格式为{?userid}；当前用户登陆账号，格式为{?loginid}；当前用户姓名，格式为{?username}；当前用户编号，格式为{?workcode}；当前用户密码(MD5格式)，格式为{?password}；当前用户部门id，格式为{?departmentid}；当前用户部门编码，格式为{?departmentcode}；当前用户部门名称，格式为{?departmentname}；当前用户分部id，格式为{?subcompanyid}；当前用户分部编码，格式为{?subcompanycode}；当前用户分部名称，格式为{?subcompanyname}；若联动主表字段，格式为$主表字段名$；若联动明细表字段，格式为$明细表表名_明细表字段名$')}/>
      } else if (key === 'searchById1') {
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@snri0n`} style={{position: 'relative', left: 20, top: -35}} width={400}
                               title={getLabel('506386', '回显查询支持sql语句及存储过程。如果是存储过程则入参必须包含主键参数。sql语句及存储过程不允许使用人员变量，例如：{?useid}。')}/>
      } else if (key === 'searchByName') {
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@dv5ajx`} style={{position: 'relative', left: 20, top: -35}} width={400}
                               title={getLabel('506387', '如果不设置条件查询，则快捷搜索和明细导入无法使用。设置条件搜索时，当查询条件未输入时，如果字段类型为文本则替换成空字符串，如果字段类型为数字，则替换成0。条件查询字段格式#loginid#。')}/>
      } else if (key === 'showpageurl') {
         return <div style={{display: 'inline-block'}}>
            <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@utp4fb`} style={{position: 'relative', left: 20, top: -7}} width={400}
                           title={getLabel('506755', '使用定制开发的页面替换默认生成的自定义浏览框页面，以实现特殊的客户要求。定制开发的页面必须放在OA的服务目录下，示例程序可以点击demo.jsp下载')}/>
            <span style={{marginLeft: 30, top: -7, position: 'relative'}}>{getLabel(506848, '示例下载链接')}：
            <a href={`${window.ecologyContentPath || ""}/interface/demo.zip`} download="demo.zip">demo.zip</a>
          </span>
         </div>
      } else if(key === "keyfield") {
         let title = "";
         if(this.state.regExpValue) {
            title = `${this.state.regExpValue}`.replace(/(\/|\^|\(|\)|\$)/g, '');
            title = title.slice(0, title.length-2).split('|').join('、');
         }
         return <WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@ebdsbu`} style={{lineHeight: "30px", marginLeft: "20px"}} width={400} title={`${title}${getLabel('519489','不允许作为主键')}, ${getLabel('532527','且设置为主键的字段的数据不能为空， 也不能重复， 需要唯一')}`} />;
      } else {
         return null;
      }
   }

   getParamRowSelection = (rowSelection) => {
      const {dataShowStore} = this.props;
      const {esbSearchDatas} = toJS(dataShowStore.status);
      const sel = {...rowSelection};
      let searchKeys = [];
      const formParams = dataShowStore.newForm.getFormParams();
      esbSearchDatas && esbSearchDatas.forEach(data => {
         if (data.paramtype == '3') {
            searchKeys.push(data.paramname);
         }
      })
      sel.getCheckboxProps = record => {
         if (formParams.datafrom == '4' && formParams.showtype == '1' && searchKeys.includes(record.new_fieldname) && record.new_issearch == 1) {
            return {disabled: true};
         } else {
            return {disabled: false};
         }
      };
      return sel;
   }

   getRowSelection = v => false;

   getTableProps = () => {
      return {showEmptyText: false, scroll: {x: "auto"}};
   }

   getWsDataChange = (datas) => this.props.dataShowStore.setState({WebserviceMethodParameterDatas: datas});

   getValidator = () => {
      return {
         rules: {
            new_fieldname: 'required|specialStr',
            new_showname: 'required',
            new_width: 'minNumber',
            new_transql: "sqlValid"
         },
         customRegister: [
            {
               name: 'minNumber',
               rules: (value, requirement, attribute) => {
                  return /^[0-9]*[1-9][0-9]*$/.test(value);
               },
               errorMessage: getLabel('504118', '最小值为1'),
            },
            {
               name: "specialStr",
               rules: (value, record, attr) => {
                  return (!(/^id$/.test(value) || /^href$/.test(value) || /^desc$/.test(value)))
               },
               errorMessage: getLabel('507113', '不能配置此字段')
            },
            {
               name: "sqlValid",
               rules: (value, record, attr) => {
                  return value.trim().startsWith('select')
               },
               errorMessage: getLabel('513895','SQL语句需要以select开始')
            }
         ]
      };
   }

   handleChangeKeyField = v => {
      this.props.dataShowStore.newForm.updateFields({keyfield: v});
      this.isValidFieldKey();
   }

   getSearchs = () => {
      const {
         dataShowStore
      } = this.props, {
         newForm, 
         status,
      } = dataShowStore, {
         dataShowFormFields, 
         WeaTableEdit_WebserviceParameterSet, 
         WebserviceMethodParameterDatas, 
         WeaTableEdit_ESBShowParameterSet, 
         WeaTableEdit_ESBSearchParameterSet, 
         WeaTableEdit_MergedSearchFieldAndListField, 
         WeaTableEdit_MergedFieldData, 
         formLoading, 
         esbShowDatas, 
         esbSearchDatas,
      } = toJS(status), {
         isFormInit,
      } = newForm;
      const formParams = newForm.getFormParams();
      let group = [];

      formLoading && isFormInit && dataShowFormFields && dataShowFormFields.forEach((c, i) => {
         let items = [];
         c && c.items && c.items.forEach(fields => {
            let key = fields.domkey[0];
            const dom = this.getHelpfulTip(key);
            items.push({
               com: (
                  <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@bbycgh@integrationDatashowNewForm${key}`}
                     label={`${fields.label}`}
                     labelCol={{span: `${fields.labelcol}`}}
                     wrapperCol={{span: `${fields.fieldcol}`}}
                     error={newForm.getError(fields)}
                     tipPosition="bottom"
                  >
                     <nobr>
                        {
                           key === "keyfield"
                              ? formParams.datafrom == '4' && formParams.showtype != '3' && formParams.showclass == '1'
                                ? <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@1f85pb@integrationDatashowNewForm${key}`} value={formParams.keyfield} viewAttr={3} disabled={true}
                                          onChange={this.handleChangeKeyField}/>
                                : <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@iny8od@${key}`} value={formParams.keyfield} viewAttr={3} 
                                     onChange={value => newForm.updateFields({keyfield: value})} onBlur={this.checkKeyField}/>
                              : <WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@7cjlzv@integrationDatashowNewForm${key}`} fieldConfig={fields} form={newForm} formParams={formParams}
                                           onChange={v => this.onChangeFields(key, formParams)}/>
                        }
                        {dom}
                     </nobr>
                  </WeaFormItem>),
               colSpan: 1,
               hide: newForm.isHide(fields, (keys, allParams) => {
                  return this.getHideFields(fields.domkey[0], allParams);
               })
            });
            if (getKey(fields) === "wsworkname" && formParams.wsoperation != "" && formParams.datafrom == "0" && formParams.showtype != '3') {
               items.push({
                  com: (
                     <WeaTableEdit ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEdit@vjtu8p@integrationDatashowNewForm${key}`}
                        tableProps={this.getTableProps()}
                        columns={WeaTableEdit_WebserviceParameterSet}
                        datas={WebserviceMethodParameterDatas}
                        draggable={false}
                        showAdd={false}
                        showDelete={false}
                        showCopy={false}
                        getRowSelection={this.getRowSelection}
                        onChange={this.getWsDataChange}
                     />
                  ),
                  hide: newForm.isHide(fields, (keys, allParams) => {
                     return (allParams.datafrom != '0' || WebserviceMethodParameterDatas.length == 0);
                  })
               });
            } else if (((getKey(fields) === "esbid" && formParams.esbid) || (getKey(fields) === "esbshowid" && formParams.esbshowid && formParams.showclass != "2")) && formParams.datafrom == "4" && formParams.showtype != '3') {
               this.getESBColumns(key === "esbid" ? WeaTableEdit_ESBSearchParameterSet : WeaTableEdit_ESBShowParameterSet, key);
               items.push({
                  com: (
                     <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@pp3wam@integrationDatashowNewForm${key}`}
                        rowKey={"paramname"}
                        tableProps={this.getTableProps()}
                        columns={key === "esbid" ? WeaTableEdit_ESBSearchParameterSet : key === "esbshowid" ? WeaTableEdit_ESBShowParameterSet : []}
                        datas={key === "esbid" ? esbSearchDatas || [] : key === "esbshowid" ? esbShowDatas || [] : []}
                        draggable={false}
                        showAdd={false}
                        showDelete={false}
                        showCopy={false}
                        getRowSelection={this.getRowSelection}
                        willEdit={(allDatas, editDatas) => this.willEditESB(allDatas, editDatas, key)}
                        onChange={(datas) => dataShowStore.setState({[key === "esbid" ? "esbSearchDatas" : "esbShowDatas"]: datas})}
                     />
                  ),
                  hide: newForm.isHide(fields, (keys, allParams) => {
                     return (allParams.datafrom != '4' || (esbSearchDatas.length == 0 && key === "esbid") || (key === "esbshowid" && esbShowDatas.length == 0));
                  })
               });
            }
         });
         if (i == 1 && (formParams.showtype == 1 || formParams.showclass == 2)) {
            group.push(<div style={{marginLeft: 24, marginRight: 22}}>
               <WeaTableEditable ecId={`${this && this.props && this.props.ecId || ''}_WeaTableEditable@lvs9l7@integrationDatashowNewForm${i}`}
                  ref={this.getRef}
                  {...this.state.baseConfig}
                  validator={this.getValidator()}
                  title={c.title}
                  getRowSelection={this.getParamRowSelection}
                  tableProps={this.getTableProps()}
                  cells={this.getMergedCells(WeaTableEdit_MergedFieldData)}
                  columns={this.getColumnsTips(WeaTableEdit_MergedSearchFieldAndListField)}
                  datas={WeaTableEdit_MergedFieldData}
                  willDelete={this.willDelete}
                  willEdit={this.willEdit}
                  onChange={this.onTableEditDataChange}
               />
            </div>)
         }
         if (i == 0) {
            group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@pqorm8@integrationDatashowNewForm${i}`} center={i == 0 ? true : false} col={1} needTigger={true} title={c.title}
                                       style={{display: (i == 1 && newForm.getFormParams().showclass == "1" && newForm.getFormParams().showtype != "1") ? "none" : ""}}
                                       showGroup={c.defaultshow} items={items}/>);
         }
      });
      return group;
   }

   getRef = el => this.table = el;

   getColumnsTips = (WeaTableEdit_MergedSearchFieldAndListField=[]) => {
      return WeaTableEdit_MergedSearchFieldAndListField && WeaTableEdit_MergedSearchFieldAndListField.map(c => {
         let title = '';
         if (["new_fieldname", "new_transql", "new_width"].includes(c.dataIndex)) {
            if (c.dataIndex === "new_fieldname") {
               title = getLabel('508146', '不能设置以下三个字段：id，desc，href');
            } else if (c.dataIndex === "new_transql") {
               title = getLabel(131015, "参数可设置如下内容，格式为：select 最终字段 from tablename where 条件字段={?currentvalue}，{?currentvalue}表示当前值");
            } else if (c.dataIndex === "new_width") {
               title = <div><p>{getLabel('504070', '1.只能输入正整数。')}</p>
                  <p>{getLabel('504032', '2.输入列宽，按照输入的值显示。不输入时，会自动均分。')}</p></div>;
            }
            c.title = <div>{c.title}<span className={"wf-backstage-linkAgeViewAttr-helpTip"}
                                          style={{marginLeft: 5}}><WeaHelpfulTip ecId={`${this && this.props && this.props.ecId || ''}_WeaHelpfulTip@mfl688@integrationDatashowNewForm${c.dataIndex}`} title={title}/></span></div>;
         }
         return c;
      })
   }

   onTableEditDataChange = datas => this.props.dataShowStore.setState({WeaTableEdit_MergedFieldData: datas})

   onCancel = () => {
      const {
         dataShowStore,
      } = this.props;

      dataShowStore.initSqlTestForm();
      dataShowStore.setState({showNewFormDialog: false});
      dataShowStore.newForm.reset();
   }

   getTitle = () => {
      const {
         dataShowFormHiddenFields,
      } = toJS(this.props.dataShowStore.status);

      return ((dataShowFormHiddenFields && dataShowFormHiddenFields.id) > 0 ? getLabel('26473', '编辑') : getLabel('365', '新建')) + `${getLabel('32303', '数据展现集成')}`;
   }

   getMoreBtn = () => {
      return {
         datas: this.getRightMenu(),
         collectParams: []
      }
   }

   render() {
      const {
         dataShowStore,
      } = this.props, {
         showNewFormDialog,
         showPreviewDialog,
         showsSqlTextFormDialog2,
         showIndexTestDialog2,
      } = toJS(dataShowStore.status);

      return (
         <div className='wea-integration-single'>
            <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@qrvute`}
               scalable
               title={this.getTitle()}
               icon='icon-coms-integration'
               iconBgcolor='#1a57a0'
               visible={showNewFormDialog}
               hasScroll={true}
               style={this.state.dialogStyle}
               onCancel={this.onCancel}
               buttons={this.getBtns()}
               moreBtn={this.getMoreBtn()}
            >
               <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@ymgela`}
                  datas={this.getRightMenu()}
                  collectParams={[]}
               >
                  {this.getSearchs()}
                  <PreviewDialog ecId={`${this && this.props && this.props.ecId || ''}_PreviewDialog@p1ksyn`} showDialog={showPreviewDialog}/>
                  <SqlTestDialog ecId={`${this && this.props && this.props.ecId || ''}_SqlTestDialog@fuu95g`} showSqlDialog={showsSqlTextFormDialog2}/>
                  <IndexTestDialog ecId={`${this && this.props && this.props.ecId || ''}_IndexTestDialog@czvodu`} showTestVersion={showIndexTestDialog2}/>
               </WeaRightMenu>
            </WeaDialog>
         </div>
      )
   }
}
