import React from 'react'
import { Form, Col, Table, Button, message, Icon, Menu, Alert, Tabs, Popover, Tooltip, Pagination } from 'antd'
import {
  addRuleAndGroups,
  empty,
  getDataFieldValue,
  guid,
  setDataFieldValue,
  extendRule,
  permissionUtils,
  initFilter,
  getPropertyData, getOnlyPropertyData, extend
} from '../../utils/common'
import ComponentBase from "../ComponentBase";
import styles from '../Component.css';
import FormPage from '../../components/FormPage';
import ShowModal from '../../components/common/ShowModal';
import FormModal from '../../components/FormModal'
import { Search, ConfirmButton } from '@woowalker/feui'
import ColumnSetting from '../TableBaseComponent/TableColumnSetting';
import TableModal from '../../components/Table/TableModal';
import CombinationModal from '../../components/Combination/CombinationModal'
import { get, set } from 'lodash'
const TabPane = Tabs.TabPane;

class EditBaseComponent extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      detailPations: {},
      editConfig: {
        head: {
          columns: {}
        },
        details: {
          editCode: {} // 参数参考this.getEditTable参数配置
        }
      },
      localSearch: {
        // field: "",
        // value: ""
      },
      sortDirection: {},                          // 表格排序
      showColumnSetting: null,
      showFilterDropdown: false
    }
    this.loadKey = '';//加载数据key
    this.billStatus = 0;
    this.defaultTreeCode = 'tree';
  };

  componentDidMount() {
    super.componentDidMount();
    if (this.props.form) {
      this.props.form.resetFields();
    }
    this.onLoadData();
    const { data } = this.props;
    let { id, clickKey } = data ? data : {};
    const loadKey = this.loadKey ? this.loadKey : clickKey;
    if (loadKey) {
      if (!id)
        id = '';
      if (this.props.custom[loadKey + id]) {
        if (this.props.form) {
          this.props.form.resetFields();
        }
        this.props.dispatch({
          type: 'custom/save',
          payload: {
            [loadKey + id]: false
          },
        });
      }
    }
  };

  componentWillReceiveProps(NextProps) {
    super.componentWillReceiveProps(NextProps);
    const { data } = this.props;
    let { id, clickKey } = data ? data : {};
    const loadKey = this.loadKey ? this.loadKey : clickKey;
    if (loadKey) {
      if (!id)
        id = '';
      if (NextProps.custom[loadKey + id]) {
        if (this.props.form) {
          this.props.form.resetFields();
        }
        this.onLoadData();
        this.props.dispatch({
          type: 'custom/save',
          payload: {
            [loadKey + id]: false
          },
        });
      }
    } else {
      if (NextProps.data?.homeReload && !this.props.data?.homeReload) {
        if (this.props.form) {
          this.props.form.resetFields();
        }
        this.onLoadData();
      }
    }

  }

  /*
  加载数据 事件
   */
  onLoadData() {
    const state = this.state;
    if (state) {
      const data = {};
      Object.keys(state).forEach(n => {
        if (n.indexOf('deletedDatas') > -1) {
          data[n] = null;
        }
      });
      this.setState(data);
    }

    const treeConfigs = this.onLoadTreeConfigList();
    if (treeConfigs && treeConfigs.length) {
      let treeConfig = this.state.treeConfig;
      if (!treeConfig) {
        treeConfig = {};
      }
      treeConfigs.forEach(t => {
        if (t.treeCode === undefined) {
          t.treeCode = this.defaultTreeCode;
        }
        treeConfig[t.treeCode] = t;
      });
      this.setState({
        treeConfig,
      }, () => {
        const tempTreeConfig = this.state.treeConfig;
        if (tempTreeConfig) {
          Object.keys(tempTreeConfig).forEach((n) => {
            this.onLoadTreeData({
              treeCode: n,
              treeConfig: tempTreeConfig[n],
            });
          });
        }
      });
    }
    this.setState({ btnLoading: false });
    this.billStatus = 0;
  }

  /**
   * 按钮点击日志埋点
   * @param {*} BtnCode
   * @param {*} BtnName
   */
  btnOperateLog = (btnConfig) => {
    const { btnType: BtnCode, label: BtnName } = btnConfig || {}
    if (BtnCode !== undefined && BtnName !== undefined) {
      const { login } = this.props
      const { formData } = this.state
      this.props.dispatch({
        type: 'app/operateLog',
        payload: {
          BtnCode,
          BtnName,
          FormCode: formData.CODE,
          FormName: formData.NAME,
          UserId: login.userId,
          OrgId: login.OrgId
        }
      })
    }
  }

  /*
    设置列配置信息
   */
  setEditConfig({ editCode, editConfig, onComplete }) {
    let temp = { ...this.state.editConfig };
    if (editCode !== undefined && editCode != 'head') {
      if (!temp.details) {
        temp.details = {};
      }
      let old = temp.details[editCode];
      if (!old) {
        old = {};
      }
      temp.details[editCode] = {
        ...old,
        ...editConfig,
      };
      this.setState({
        editConfig: temp,
      }, () => {
        if (typeof onComplete === 'function') {
          onComplete();
        }
      });
      return;
    }

    if (!temp.head) {
      temp.head = {};
    }
    temp.head = {
      ...temp.head,
      ...editConfig,
    };
    this.setState({
      editConfig: temp
    }, () => {
      if (typeof onComplete === 'function') {
        onComplete();
      }
    });
  };

  /*
    获取列配置信息
   */
  getEditConfig(params) {
    const { editCode } = params ? params : {};
    let config = {};
    if (this.state.editConfig) {
      if (editCode === 'head') {
        config = this.state.editConfig.head;
      }
      else if (editCode !== undefined) {
        config = this.state.editConfig && this.state.editConfig.details ? this.state.editConfig.details[editCode] : null;
      }
      else {
        config = this.state.editConfig.head;
      }
    }
    if (!config) {
      config = {};
    }
    return config;
  }

  /*
  设置head配置信息
 */
  setHeadEditConfig({ editConfig }) {
    let config = { ...this.state.editConfig };
    config["head"] = editConfig;
    this.setState({
      editConfig: config
    });


  }

  /*
获取列配置信息
*/
  setMenuName(editConfig, fieldName, enumName) {
    let conf = { ...editConfig };
    var objclos = conf["columns"].find(i => i.field == fieldName);
    if (objclos) {
      objclos.data.enumName = enumName;
    }
    this.setHeadEditConfig({ editConfig: conf })
  }

  /*
    获取序号
   */
  getRowNoByData({ data, editCode, sortField, sortOrder, isRowNo }) {
    if (data && data.length) {
      const compareRecord = (x, y, sortFieldArray, sortOrderArray, sortIndex) => {
        let s = sortFieldArray[sortIndex];
        let o = sortOrderArray[sortIndex];
        if (s === undefined || s === null)
          s = 'ID';
        if (o === undefined || o === null)
          o = 0;
        const xValue = getDataFieldValue(x, s);
        const yValue = getDataFieldValue(y, s);

        if (xValue != null && yValue != null) {
          if (xValue === yValue) {
            return compareRecord(x, y, sortFieldArray, sortOrderArray, sortIndex + 1);
          }
          else {
            return o === 0 ? (xValue > yValue ? 1 : -1) : (xValue > yValue ? -1 : 1);
          }
        }
        else if (xValue != null) {
          return o === 0 ? -1 : 1;
        }
        else if (yValue != null) {
          return o === 0 ? 1 : -1;
        }
        else {
          return o === 0 ? (x.toString() > y.toString() ? 1 : -1) : (x.toString() > y.toString() ? -1 : 1);
        }
      };

      const tableConfig = this.state.editConfig && this.state.editConfig.details ? this.state.editConfig.details[editCode] : null;
      if (tableConfig) {
        sortField = tableConfig.sortField;
        sortOrder = tableConfig.sortOrder;
      }
      if (sortField) {
        const sort = sortField.split(',');
        const orders = [];
        if (sortOrder) {
          const temp = sortOrder.split(',');
          temp.forEach(t => {
            orders.push(+t);
          })
        }
        data.sort((x, y) => {
          return compareRecord(x, y, sort, orders, 0);
        });
      }
      if (isRowNo == undefined || isRowNo) {//wyw 有些排序不能被修改 （BS057 安全检查登记 多个登记人）
        data.forEach((n, i) => {
          n.ROW_NO = (i + 1);
        });
      }
    }
  }

  /*
    保存表头记录
    values：保存值列表 json对象
    complete：保存完成后委托
   */
  saveHeadRecord(values, onComplete) {
    if (values === 0 || !!values) {
      const data = {
        ...this.state.data
      };
      Object.keys(values).forEach((n) => {
        setDataFieldValue(data, n, values[n]);
      });
      this.setState({
        data,
      }, () => {
        if (typeof onComplete === 'function') {
          onComplete();
        }
      });
    }
  }

  /*
  根据编辑编号获取导航字段列表，注：从父到子
  */
  getEditNavFieldByEditCode(editCode, arry) {
    const tableConfig = this.getEditConfig({ editCode });
    if (!tableConfig) return;
    arry.unshift(tableConfig.dataNav);
    if (tableConfig.parentEditCode) {
      this.getEditNavFieldByEditCode(tableConfig.parentEditCode, arry);
    }
  }

  /*
    根据ID获取行记录
  */
  getEditRecordById({ data, id, editCode, onComplete }) {
    const navFieldArray = [];
    this.getEditNavFieldByEditCode(editCode, navFieldArray);
    if (!navFieldArray.length) return;

    const doRecordById = (record, index) => {
      const list = getDataFieldValue(record, navFieldArray[index]);
      if (list && list.length) {
        list.forEach(t1 => {
          if (t1.ID === id) {
            onComplete(t1);
          }
          else {
            doRecordById(t1, index + 1);
          }
        });
      }
    };
    doRecordById(data, 0);
  }

  /*
    保存行记录
   */
  saveRowRecord({ record, parentRecord, onComplete, editCode }) {
    const tableConfig = this.getEditConfig({ editCode });
    if (!tableConfig) return;
    const { dataNav, sortField, sortOrder } = tableConfig;
    const data = { ...this.state.data };
    if (!parentRecord) {
      if (tableConfig.parentEditCode) {
        const parentId = getDataFieldValue(record, tableConfig.parentFieldName);
        if (parentId) {
          this.getEditRecordById({
            data, editCode: tableConfig.parentEditCode, id: parentId,
            onComplete: (p) => {
              parentRecord = p;
            }
          });
        }
      }
      else {
        parentRecord = data;
      }
    }

    let list = getDataFieldValue(parentRecord, dataNav);
    if (!list) {
      list = [];
      setDataFieldValue(parentRecord, dataNav, list);
    }
    const index = list.findIndex(item => record.ID === item.ID);
    const item = list[index];
    if (item) {
      list.splice(index, 1, {
        ...item,
        ...record,
      });
    }
    this.getRowNoByData({ data: list, sortField, sortOrder, });
    this.setState({ data }, () => {
      if (typeof onComplete === 'function') {
        onComplete()
      }
    });
  }

  /*
  设置表头字段的可见性
  params【字段名称】=是否可见
   */
  setHeadFieldVisible(params, editCode) {
    const headColumnConfig = this.getEditConfig();
    const cols = headColumnConfig ? headColumnConfig.columns : [];
    if (cols && cols.length) {
      Object.keys(params).forEach((n) => {
        const temps = cols.filter(t => t.field === n);
        if (temps && temps.length) {
          temps[0].visible = params[n];
        }
      });
    }
    if (!editCode || editCode === 'head') {
      if (headColumnConfig.panels && headColumnConfig.panels.length > 0) {
        headColumnConfig.panels.forEach(panel => {
          if (panel.columns && panel.columns.length > 0) {
            Object.keys(params).forEach((n) => {
              const temps = panel.columns.filter(t => t.field === n);
              if (temps && temps.length) {
                temps[0].visible = params[n];
              }
            });
            // panel.columns.forEach(col => {
            //   if (col.field === params.toString().split(':')[0]) {
            //     col.visible = params.toString().split(':')[1];
            //   }
            // })
          }
        })
      }
      this.setEditConfig({
        editConfig: headColumnConfig,
      });
    }
    else {
      this.setEditConfig({
        editConfig: { columns: cols },
      });
    }
  }

  /*
  设置表头字段的可见性
  params【字段名称】=是否可见
   */
  setRowFieldVisible = (editCode, params) => {
    const detailColumnConfig = this.getEditConfig({ editCode });
    const cols = detailColumnConfig ? detailColumnConfig.columns : [];
    Object.keys(params).forEach((n) => {
      const temps = cols.filter(t => t.field === n);
      if (temps && temps.length) {
        temps[0].visible = params[n];
      }
    });
    this.setEditConfig({
      editConfig: { columns: cols },
      editCode,
    });
  }
  /*
设置表头字段的可见性
params【字段名称显示】
*/
  setRowFieldLabel = (editCode, params) => {
    const detailColumnConfig = this.getEditConfig({ editCode });
    const cols = detailColumnConfig ? detailColumnConfig.columns : [];
    Object.keys(params).forEach((n) => {
      const temps = cols.filter(t => t.field === n);
      if (temps && temps.length) {
        temps[0].label = params[n];
      }
    });
    this.setEditConfig({
      editConfig: { columns: cols },
      editCode,
    });
  }

  /*
设置表头字段的可见性
params【字段名称】=是否可编辑
 */
  setRowFieldDisable = (editCode, params) => {
    const detailColumnConfig = this.getEditConfig({ editCode });
    const cols = detailColumnConfig ? detailColumnConfig.columns : [];
    Object.keys(params).forEach((n) => {
      const temps = cols.filter(t => t.field === n);
      if (temps && temps.length) {
        temps[0].disabled = params[n];
      }
    });
    this.setEditConfig({
      editConfig: { columns: cols },
      editCode,
    });
  }


  /*
设置表头字段的可见性
params【字段属性】=值
*/
  setRowFieldPops = (editCode, pop, params) => {
    const detailColumnConfig = this.getEditConfig({ editCode });
    const cols = detailColumnConfig ? detailColumnConfig.columns : [];
    Object.keys(params).forEach((n) => {
      const temps = cols.filter(t => t.field === n);
      if (temps && temps.length) {
        temps[0][pop] = params[n];
      }
    });
    this.setEditConfig({
      editConfig: { columns: cols },
      editCode,
    });
  }


  onRenderHeadControl({ colConfig, record }) {
    return this.getControl(colConfig, record);
  }

  /*
    重置表头列配置的信息
   */
  setHeadColumnConfig({ colConfig, record }) {
    colConfig.value = getDataFieldValue(record, colConfig.field);
    if (colConfig.field && colConfig.field.indexOf('Nav_SysParams') > -1) {
      colConfig.value = this.getControlValue({
        controlType: colConfig.controlType, value: colConfig.value,
        data: colConfig.data
      });
    }
    colConfig.showFormId = record && colConfig.showIdField ? getDataFieldValue(record, colConfig.showIdField) : null;
    colConfig.onChange = colConfig.onChange ? colConfig.onChange : this.onHeadControlChange;
    colConfig.onBlur = colConfig.onBlur ? colConfig.onBlur : this.onHeadControlBlur;
    if (colConfig.controlType === 9 || colConfig.controlType === 13 || colConfig.controlType === 11 || colConfig.controlType === 17 || colConfig.controlType === 24) {
      if (!colConfig.data) {
        colConfig.data = {};
      }
      colConfig.data.onFilter = colConfig.data.onFilter ? colConfig.data.onFilter.bind(this) : this.onHeadDropDownFilter.bind(this);
      colConfig.data.onSelect = colConfig.data.onSelect ? colConfig.data.onSelect.bind(this) : this.onHeadDropDownSelect.bind(this);
    }
  }

  handleRenderHeadControlEvent(record, colInfo) {

  }

  handleRenderRowControlEvent(record, colInfo) {

  }
  /*
      根据控件配置创建控件组
      配置信息请参考：ComponentBase.getControl信息
   */
  createControls(columns, record, code) {
    let padding = 6;
    let defaultFormItemLayout = {
      labelCol: { span: 24 },
      wrapperCol: { span: 24 - padding },
    };
    if (columns) {
      const { form } = this.props;
      const { getFieldDecorator } = form;
      return columns.map(col => {
        let renderHtml = this.handleRenderHeadControlEvent(record, col);
        if (renderHtml) return renderHtml;
        if (code && col.code !== code) return null;
        this.setHeadColumnConfig({ colConfig: col, record });
        let {
          visible,
          label,
          field,
          controlType,
          data,
          value: colValue,
          isRequire,
          key,
          span,
          ruleExp,
          ruleExpInfo,
          minLen,
          maxLen,
          errVerifyMsg,
          width,
          remark
        } = col;
        if (!key && !field)
          return null;
        if (visible || visible === undefined) {
          let valuePropName = 'value';
          if (controlType === 4 || controlType === 5 && data.enumName) {
            valuePropName = 'checked';
          }
          let defalutWidth = 8, defalutMinWidth = 12;
          const spanCol = { lg: defalutMinWidth, xxl: defalutWidth }; // spanCol为响应式栅格，span为定义栅格
          let customOrResponse = span ? span : spanCol;
          let tmpFormItemLayout = defaultFormItemLayout;


          if (width && width != 0 && width != 1) {
            defalutWidth = (defalutWidth * width > 24 ? 24 : defalutWidth * width);
            defalutMinWidth = (defalutMinWidth * width > 24 ? 24 : defalutMinWidth * width);
            customOrResponse = { lg: defalutMinWidth, xxl: defalutWidth };
            tmpFormItemLayout = {
              labelCol: { span: 24 },
              wrapperCol: { span: 24 - (padding / width) },
            };
          }

          const rulesMethod = [];
          if (isRequire) {
            if (!errVerifyMsg) {
              switch (col.controlType) {
                case 25: errVerifyMsg = "请上传" + label
                  break;
                case 2:
                case 3:
                case 4:
                case 5:
                case 8:
                case 9:
                case 10:
                case 11:
                case 12:
                case 14:
                case 15:
                case 17:
                case 18:
                case 19:
                case 20:
                case 21:
                case 22:
                case 23:
                case 24: errVerifyMsg = "请选择" + label
                  break;
                default: errVerifyMsg = "请输入" + label
                  break;
              }
            }
            rulesMethod.push({
              required: !!isRequire,
              message: errVerifyMsg ? errVerifyMsg : '请输入' + label,
              validator: (rule, value, callback) => {
                var errors = [];
                // var isEmpty = false;
                // if (controlType === 24) {
                //   isEmpty = true;
                //   colValue?.forEach(i => {
                //     if (!i.IS_DELETED) {
                //       isEmpty = true;
                //     }
                //   })
                // }
                if (rule.required && (colValue === undefined || colValue === null || colValue === ''
                  || controlType !== 3 && controlType !== 24 && empty(colValue, true))
                  || controlType === 24 && colValue.filter(i => !i.IS_DELETED).length == 0) {
                  errors.push(rule.message);
                }
                callback(errors);
              }
            })
          }
          if (ruleExp) {
            rulesMethod.push({
              message: errVerifyMsg ? errVerifyMsg : (ruleExpInfo ? ruleExpInfo : '验证不通过'),
              pattern: ruleExp,
              validator: (rule, value, callback) => {
                var errors = [];
                const tempVal = colValue === null || colValue === undefined ? '' : colValue;
                if (rule.pattern && !new RegExp(rule.pattern).test(tempVal)) {
                  errors.push(rule.message);
                }
                callback(errors);
              }
            })
          }
          // 文本与多行文本框、数值类型框加长度校验
          if (controlType === 1 || controlType === 6 || controlType === 7) {
            rulesMethod.push({
              validator: (rule, value, callback) => {
                var errors = [];
                const tempVal = colValue === null || colValue === undefined ? '' : colValue;
                switch (controlType) {
                  case 1:
                  case 6:
                    if (tempVal.length < minLen) {
                      errors.push(errVerifyMsg || `至少输入${minLen}个字符`)
                    } else if (tempVal.length > maxLen && maxLen !== 0) {
                      errors.push(errVerifyMsg || `最多允许${maxLen}个字符`)
                    }
                    break;
                  case 7:
                    {
                      const colValueArr = tempVal.toString().split('.')
                      if (colValueArr[1] && colValueArr[1].length > maxLen && maxLen !== 0) {
                        errors.push(errVerifyMsg || `最多允许${maxLen}个小数位`)
                      }
                    }
                    break;
                  default:
                    break
                }
                callback(errors);
              }
            })
          }

          return <Col key={key ? key : field} {...customOrResponse}>
            <Form.Item
              label={
                <span>
                  <span>{label}</span>
                  {
                    remark
                      ? (
                        <Tooltip title={remark}>
                          <Icon type="question-circle-o" style={{ marginLeft: 2 }} />
                        </Tooltip>
                      )
                      : null
                  }
                </span>
              }
              {...tmpFormItemLayout}
            >
              {
                getFieldDecorator(field, {
                  valuePropName: valuePropName,
                  validateTrigger: 'onBlur',
                  initialValue: colValue,
                  rules: rulesMethod,
                })(this.onRenderHeadControl({ colConfig: col, record }))
              }
            </Form.Item>
          </Col>
        } else { return null }
      });
    }
  }

  /*
  {field,value,colConfig,thisRef}
   */
  onHeadControlChange(params) {
    const { field, value, thisRef } = params ? params : {};
    thisRef.saveHeadRecord({
      [field]: value,
    }, () => {
      thisRef.onAfterHeadControlChange(params);
    });
  }

  /*
  {field,value,colConfig,thisRef}
   */
  onAfterHeadControlChange(params) { }

  /*
    {field,colConfig,thisRef}
   */
  onHeadControlBlur(params) {
    const { field, thisRef } = params ? params : {};
    const { form } = thisRef.props;
    if (form) {
      form.validateFields([field], { force: true });
    }
    thisRef.onAfterHeadControlBlur(params);
  }

  /*
  {field,colConfig,thisRef}
   */
  onAfterHeadControlBlur(params) { }

  /*
    {record,data,colConfig,thisRef}
   */
  onHeadDropDownFillData(params) { }

  /*
    {record,data,colConfig,thisRef}
   */
  onAfterHeadDropDownSelect(params) { }

  /*
    {record,colConfig,thisRef}
   */
  onBeforeHeadDropDownSelect(params) { }

  /*
    {record,complete,colConfig,thisRef}
   */
  onHeadDropDownSelect(params) {
    const { record, complete, colConfig, thisRef } = params ? params : {};
    if (thisRef.onBeforeHeadDropDownSelect({ ...params })) return;
    const { form } = thisRef.props;
    const data = { ...thisRef.state.data };
    const configData = colConfig.data;
    thisRef.fillDropDownSelectRecord({
      record,
      data,
      saveField: configData.saveField,
      labelField: configData.labelField,
      navField: configData.navField,
      field: colConfig.field,
      idField: colConfig.idField,
    });

    thisRef.onHeadDropDownFillData({ ...params, record, data, colConfig });

    thisRef.setState({
      data
    }, () => {
      if (typeof complete === 'function') {
        complete();
      }
      thisRef.onAfterHeadDropDownSelect({ ...params, data, record, colConfig });
      if (form) {
        form.validateFields([colConfig.field], { force: true });
      }
      const saveFields = configData.saveField ? configData.saveField.split(',') : [];
      if (saveFields && saveFields.length) {
        const cols = thisRef.editConfig && thisRef.editConfig.head ? thisRef.editConfig.head.columns : null;
        if (cols && cols.length) {
          saveFields.forEach((n, i) => {
            cols.forEach(item => {
              if (item.field === n) {
                thisRef.onAfterHeadControlChange({ field: n, value: getDataFieldValue(data, n), colConfig: item });
              }
            });
          });
        }
        if (form) {
          form.validateFields(saveFields, { force: true });
        }
      }
    });
  }

  /*
    {params,colConfig,thisRef}
   */
  onHeadDropDownFilter(params) { }

  /*
    {field,value,colConfig,record,dataNav,sortField,sortOrder,thisRef}
   */
  onRowControlChange(params) {
    const { field, value, colConfig, record, dataNav, sortField, sortOrder, editCode, thisRef } = params || {};
    if (record) {
      setDataFieldValue(record, field, value);
      thisRef.saveRowRecord({
        record,
        dataNav,
        editCode,
        onComplete: () => {
          thisRef.onAfterRowControlChange(params);
        },
        sortField,
        sortOrder,
      });
    }
  }

  /*
  {field,value,colConfig,record,dataNav,sortField,sortOrder,thisRef}
   */
  onAfterRowControlChange(params) { }

  /*
  {field,colConfig,record,dataNav,sortField,sortOrder,thisRef}
   */
  onRowControlBlur(params) {
    const { thisRef } = params ? params : {};
    thisRef.onAfterRowControlBlur(params);
  }

  /*
  {field,colConfig,record,dataNav,sortField,sortOrder,thisRef}
   */
  onAfterRowControlBlur(params) { }

  /*
  {record,选中记录
  data,当前数据行项
  colConfig, 列配置信息
  thisRef,当前组件
  }
   */
  onRowDropDownFillData(params) { }

  /*
 {record,complete,colConfig,data,dataNav,sortField,sortOrder,columns,thisRef}
 */
  onBeforeRowDropDownSelect(params) { }

  /*
  {record,complete,colConfig,data,dataNav,sortField,sortOrder,columns,thisRef}
  */
  onAfterRowDropDownSelect(params) { }

  /*
   {record,complete,colConfig,data,dataNav,sortField,sortOrder,columns,thisRef}
   */
  onRowDropDownSelect(params) {
    const { record, complete, colConfig, data, dataNav, sortField, sortOrder, columns, editCode, thisRef } = params || {};
    if (thisRef.onBeforeRowDropDownSelect({ ...params })) return;
    const configData = colConfig.data;
    thisRef.fillDropDownSelectRecord({
      record,
      data,
      saveField: configData.saveField,
      labelField: configData.labelField,
      navField: configData.navField,
      field: colConfig.field,
      idField: colConfig.idField,
    });

    thisRef.onHeadDropDownFillData({ ...params, record, data, colConfig });
    thisRef.saveRowRecord({
      record: data,
      dataNav,
      editCode,
      onComplete: () => {
        if (typeof complete === 'function') {
          complete();
        }
        thisRef.onAfterRowDropDownSelect({ ...params, record, data, colConfig });
        const saveFields = configData.saveField ? configData.saveField.split(',') : [];
        if (saveFields && saveFields.length && columns && columns.length) {
          saveFields.forEach((n, i) => {
            columns.forEach(item => {
              if (item.field === n) {
                thisRef.onAfterRowControlChange({ field: n, value: getDataFieldValue(data, n), colConfig: item, record: data, dataNav, sortField, sortOrder, editCode: editCode });
              }
            });
          });
        }
      },
      sortField,
      sortOrder,
    });
  }

  /*
  {record,colConfig,params,thisRef}
   */
  onRowDropDownFilter(params) { }

  /*
  {editCode,record,isShow,isPermit,getHeadFieldValue}
   */
  onRowEditFormData(params) {
    const { editCode, record, isShow, isPermit, getHeadFieldValue } = params ? params : {};
    return {
      pageCode: editCode,
      record: record,
      onSave: (row) => {
        this.saveRowRecord({ ...params, record: row, });
      },
      isShow: isShow,
      isPermit: isPermit,
      getFieldValue: (field) => { return getHeadFieldValue(field, (this.props.editRef ? this.props.editRef : this)); },
      stateData: this.state.data,
      thisRef: this.props.editRef ? this.props.editRef : this,
    }
  }

  /*
    获取删除数据
   */
  getDeletedData({ editCode }) {
    return this.state['deletedDatas' + editCode];
  }

  /*
    设置删除记录
   */
  setDeletedData({ editCode, deletedDatas }) {
    let temps = this.state['deletedDatas' + editCode];
    if (!temps) {
      temps = [];
    }
    if (deletedDatas && deletedDatas.length) {
      deletedDatas.forEach(t => {
        if (!t.CREATE_TIME) return;
        if (!temps.filter(t1 => t1.ID === t.ID).length) {
          t.IS_DELETED = true;
          temps.push(t);
        }
      });
    }
    this.setState({
      ['deletedDatas' + editCode]: temps,
    });
  }

  /*
    新增行之前 {editCode,srcRecord,thisRef}
   */
  onBeforeAddRow(params) { }

  /*
      新增行之后 {editCode, record, srcRecord,thisRef}
   */
  onAfterAddRow(params) { }

  /*
    删除行之前 {editCode,record,thisRef}
   */
  onBeforeDeleteRow(params) { }

  /*
      删除行之后  {editCode,data,thisRef}
   */
  onAfterDeleteRow(params) { }

  /**
   * 批量添加行
   * @param {*} datas 
   */
  onBatchAddRow(datas, params) {
    if (Array.isArray(datas)) {
      datas.forEach(currData => {
        const currAddRow = this.onAddRow(params, true)

        const { btnConfig, editConfig } = params || {};
        /**
         * ===批量新增按钮面板===
         * 导航字段 btnNavField 对应表单编号的表单列
         * 保存字段 btnSaveField 对应需要编辑表单的表单列对应的字段名称
         */
        const { saveField: btnSaveField, navField: btnNavField } = btnConfig
        const btnSaveFields = btnSaveField ? btnSaveField.split(',') : []
        const btnNavFields = btnNavField ? btnNavField.split(',') : []

        /**
         * 通过 editConfig 获取到编辑表单的 column
         * columns 存有编辑表单字段名称和编辑配置
         */
        const { columns } = editConfig
        const attrs = []
        columns.forEach(col => {
          const { field, data } = col
          const { saveField, navField } = data || {}
          if (saveField && navField) {
            /**
             * 取控件内配置的保存字段名称 saveField，对应到 btnSaveFields，
             * 根据 btnSaveFields 获取到 btnNavFields 路径，
             * 如果在 btnSaveFields 获取不到，则取控件内配置的导航字段 navField 路径
             */
            const saveFields = saveField ? saveField.split(',') : []
            const navFields = navField ? navField.split(',') : []
            saveFields.forEach((sf, i) => {
              const saveFieldIndex = btnSaveFields.indexOf(sf)
              attrs.push({
                fieldKey: sf,
                fieldValuePath: saveFieldIndex !== -1 ? btnNavFields[saveFieldIndex] : navFields[i]
              })
            })
          } else {
            /**
             * 如果控件内没有配置保存字段名称 saveField，
             * 则直接取字段名称 field，对应到 btnSaveFields，
             * 根据 btnSaveFields 获取到 btnNavFields 路径
             */
            const saveFieldIndex = btnSaveFields.indexOf(field)
            attrs.push({
              fieldKey: field,
              fieldValuePath: saveFieldIndex !== -1 ? btnNavFields[saveFieldIndex] : field
            })
          }
        })
        attrs.forEach(att => {
          if (currAddRow) {
            set(currAddRow, att.fieldKey, get(currData, att.fieldValuePath))
          }
        })
      })
    }
  }

  /*
    新增行
   */
  onAddRow(params, immediate) {
    let { parentFieldName, parentId, editCode, parentRecord } = params ? params : {};
    if (this.onBeforeAddRow({
      ...params,
    })) return;
    const tableConfig = this.getEditConfig({ editCode });
    if (!tableConfig) return;
    const { dataNav, sortField, sortOrder, entityOrgType } = tableConfig;
    const tempParentId = (parentId ? parentId : (parentRecord ? parentRecord.ID : this.state.data.ID));
    const data = { ...this.state.data };
    if (!parentRecord) {
      if (tableConfig.parentEditCode) {
        if (tempParentId) {
          this.getEditRecordById({
            data, editCode: tableConfig.parentEditCode, id: tempParentId,
            onComplete: (p) => {
              parentRecord = p;
            }
          });
        }
      }
      else {
        parentRecord = data;
      }
    }

    let list = getDataFieldValue(parentRecord, dataNav);
    if (!list) {
      list = [];
      setDataFieldValue(parentRecord, dataNav, list);
    }
    let newRow = {
      ID: guid(),
      ORG_ID: (this.props.login ? this.props.login.OrgId : null),
      ENTITY_ORG_TPYE: entityOrgType ? entityOrgType : 0,
    };
    if (parentFieldName) {
      newRow[parentFieldName] = tempParentId;
    }

    this.onAfterAddRow({
      ...params,
      record: newRow,
    });
    list.unshift(newRow);
    this.getRowNoByData({ data: list, sortField, sortOrder, });
    immediate && (this.state.data[dataNav] = list);
    this.setState({
      data,
    });
    //定位到第一行
    let pationKey = "table_detail" + editCode;
    this.handlePageChange(1, pationKey);
    return newRow
  }

  /*
    删除行
   */
  onDeleteRow(params) {
    const { editCode, ids } = params ? params : {};
    const tableConfig = this.getEditConfig({ editCode });
    if (!tableConfig) return;
    const { dataNav, sortField, sortOrder } = tableConfig;
    let data = { ...this.state.data };

    const navFieldArray = [];
    this.getEditNavFieldByEditCode(editCode, navFieldArray);
    if (!navFieldArray.length) return;
    const deletedDatas = [];
    const doRecordById = (record, index) => {
      const list = getDataFieldValue(record, navFieldArray[index]);
      if (list && list.length) {
        const tempList = [];
        let hasDeleteRow = false;
        list.forEach(t2 => {
          const isDelete = ids ? ids.filter(t1 => t1 === t2.ID).length > 0 : false;
          if (isDelete) {
            if (!this.onBeforeDeleteRow({
              ...params,
              record: t2,
            })) {
              hasDeleteRow = true;
              deletedDatas.push(t2);
              return;
            }
            tempList.push(t2);
          }
          else {
            doRecordById(t2, index + 1);
            tempList.push(t2);
          }
        });
        if (hasDeleteRow) {
          this.onAfterDeleteRow({
            ...params,
            data: tempList,
          });
          this.getRowNoByData({ data: tempList, sortField, sortOrder, });
          setDataFieldValue(record, navFieldArray[index], tempList);
        }
      }
    };
    doRecordById(data, 0);

    this.setState({
      data,
    });
    if (deletedDatas && deletedDatas.length) {
      this.setDeletedData({ editCode, deletedDatas });
    }
  }

  /*
    表选中配置
   */
  getEditRowSelection = ({ checked, selectEditTableKey }) => {
    if (!checked) return null;
    const selectedRowKeys = this.state[selectEditTableKey];
    const rowSelection = {
      selectedRowKeys,
      onChange: (selectedRowKeys) => {
        this.setState({
          [selectEditTableKey]: selectedRowKeys
        });
      }
    };
    return rowSelection;
  }

  getEditSelectedRecord({ editCode, parentId, parentRecord }) {
    let data = this.getEditTableData({ editCode, parentId, parentRecord });
    let selectedKeys = this.getEditSelectedKeys({ editCode, parentId, parentRecord })
    const selectedRecords = [];
    if (data && data.length) {
      data.forEach(t => {
        if (selectedKeys.filter(t1 => t1 === t.ID).length > 0) {
          selectedRecords.push(t);
        }
      });
    }
    return selectedRecords;
  }

  getEditSelectedKeys({ editCode, parentId, parentRecord }) {
    const temps = this.state['editTableSelectedKeys' + editCode + (parentId ? parentId : '')];
    if (temps && temps.length) {
      return temps;
    }
    return [];
  }

  /*
    渲染表头
   */
  renderEditTableHead = (params, selectEditTableKey) => {
    const { rightBtns, editCode, parentId, parentRecord, btns } = params ? params : {};
    return (
      <div style={{ display: 'flex', marginBottom: 15 }}>
        <div style={{ flex: 1 }} className={styles.antBtns_mr8}>
          {this.getRenderBtns({ ...params, btns, editCode, parentId, parentRecord, type: 1 })}
        </div>
        <div className={styles.antBtns_mr8}>
          {this.getRenderBtns({ ...params, btns: rightBtns, editCode, parentId, parentRecord, type: 2 })}
        </div>
      </div>
    )
  }

  /*
  重置行列配置信息
   */
  setRowColumnConfig({ colConfig, record, params }) {
    colConfig.value = getDataFieldValue(record, colConfig.field);
    if (colConfig.field && colConfig.field.indexOf('Nav_SysParams') > -1) {
      colConfig.value = this.getControlValue({
        controlType: colConfig.controlType, value: colConfig.value,
        data: colConfig.data
      });
    }
    colConfig.showFormId = record && colConfig.showIdField ? getDataFieldValue(record, colConfig.showIdField) : null;
    colConfig.onChange = (changeParam) => {
      this.onRowControlChange({ ...params, ...changeParam, record, colConfig: colConfig });
    };
    colConfig.onBlur = (blurParam) => {
      this.onRowControlBlur({ ...params, ...blurParam, record, colConfig: colConfig, });
    }

    if (colConfig.controlType === 9 || colConfig.controlType === 13 || colConfig.controlType === 17 || colConfig.controlType === 24) {//分页下拉 扫描
      if (!colConfig.data) {
        colConfig.data = {};
      }
      colConfig.data.onSelect = (selectParam) => {
        this.onRowDropDownSelect({
          ...params, ...selectParam,
          complete: selectParam.complete,
          record: selectParam.record,
          data: record,
          colConfig: colConfig,
        });
      };
      colConfig.data.onFilter = (filterParams) => {
        this.onRowDropDownFilter({ ...params, ...filterParams, colConfig: colConfig });
      }
    }
    if (colConfig.editFormCode) {
      if (!colConfig.data) {
        colConfig.data = {};
      }
      colConfig.data.editFormData = this.onRowEditFormData({ ...params, record, });
    }
  }

  /*
  渲染单元格
   */
  onRenderRowControl({ editCode, colConfig, record, text, params, parentId, parentRecord }) {
    let renderHtml = this.handleRenderRowControlEvent(record, colConfig);
    if (renderHtml) return renderHtml;
    let cellText = this.getTableCellText({ col: colConfig, record, text });
    if (colConfig.controlType === 0) {
      return text;
    }
    this.setRowColumnConfig({ colConfig, params, record, parentId, parentRecord });
    let cellControl = this.getControl(colConfig, record);

    const retProps = {
      key: record.id + (colConfig.id || colConfig.field),
      style: {
        width: "100%",
        //textOverflow: "ellipsis",
        whiteSpace: 'pre-wrap',
        overflow: "hidden",
        wordWrap: 'break-word',
        wordBreak: 'break-word'
      }
    };
    //分页下拉多选
    if (colConfig.controlType == 24) {
      cellText = '';
      if (record[colConfig.field] && record[colConfig.field].length > 0) {
        record[colConfig.field].forEach((item) => {
          if (!item.IS_DELETED) {
            cellText += getDataFieldValue(item, colConfig.column.INPUT_LABEL_FIELD) + ",";
          }
        })
        if (cellText) {
          cellText = cellText.substring(0, cellText.length - 1);
        }
      }
    }
    // 转换布尔值为文本
    if (typeof cellText === "boolean") {
      cellText = cellText ? "是" : "否"
    }
    let isUseControl = false;
    /*
     文本输入 = 1,
    日期选择 = 2,
    下拉选择 = 3,
    /// <summary>radio</summary>
    单项选框 = 4,
    /// <summary>check</summary>
    多项选框 = 5,
    长文本域 = 6,
    数值类型 = 7,
    时间类型 = 8,
    分页下拉 = 9,
    日期区间类型 = 10,
    下拉树选择控件=11,
    下拉多选控件 = 12,
    扫描控件=13,
    系统序列号控件=14,
    年月日时分秒控件=15,
    密码控件=16,
    级联组件 = 17,
    月份选择 = 18,
    月份区间 = 19,
    年份选择 = 20,
    年份区间 = 21,
    年月日时分秒区间 = 22,
    年月日时分区间 = 23,
    分页下拉多选 = 24,
    附件上传 = 25,
    文本 = 100,
    布尔文本 = 101,
    日期文本 = 102,
    时间文本 = 103,
    数值文本_2位小数 = 104,
    数值文本_3位小数 = 105,
    文本_最大10字符 = 106,
    百分比 = 107,
    */
    // 新增行 使用控件
    //模式是按照控件显示。除非配置成文本了
    if (!record.CREATE_TIME || (colConfig.column.EDITABLE
      && !colConfig.column.SHOW_TYPE
      // && (colConfig.controlType == 25
      // || colConfig.controlType == 1 || colConfig.controlType == 6
      // || colConfig.controlType == 24 || colConfig.controlType == 3 || colConfig.controlType == 4 || colConfig.controlType == 5
      // || colConfig.controlType == 7 || colConfig.controlType == 9
    )) {
      //cellText = cellControl
      isUseControl = true;
    }

    if (!cellText && cellText !== 0) {
      cellText = "--"
    }

    return (
      <div {...retProps}>
        {
          isUseControl
            ? <span>{cellControl}</span>
            : colConfig.disabled ? <span title={cellText}>{cellText}</span> : (
              <Popover content={cellControl} trigger="click">
                {/* eslint-disable-next-line no-script-url */}
                <a href="javascript:void(0)" title={cellText}>
                  {cellText}
                </a>
              </Popover>
            )
        }
      </div>
    )
  }

  /**
   * 可控的排序设置
   *
   */
  setSortData = (direct, fields) => {
    this.setState({
      sortDirection: {
        ...this.state.sortDirection,
        [fields]: direct
      }
    })
  };

  /**搜索单列 */
  setSearchInfo = (value, fields) => {
    if (value) {
      this.setState({
        localSearch: {
          fields,
          value
        }
      })
    } else {
      this.setState({
        localSearch: {}
      })
    }
  };

  getEditColumns = (params) => {
    const { showColumnSetting, showFilterDropdown } = this.state;
    let { columns, rowBtns, isRowNo, editCode, parentId, parentRecord, editConfig } = params;
    if (!columns) return [];
    const cols = isRowNo ? [{ title: '序号', key: guid(), dataIndex: 'ROW_NO', width: 60 }] : [];
    const tmp = [];
    columns.forEach(col => {
      if (col.visible || col.visible === undefined) {
        const columnObj = {
          title: <>{col.isRequire ? <span style={{ color: 'red' }}>*</span> : null}{col.label}</>,
          key: col.id,
          dataIndex: col.field,
          onHeaderCell: column => {
            return {
              onMouseEnter: () => { // 鼠标移入表头单元格
                this.setState({
                  showColumnSetting: column.key
                })
              }
            };
          },
          filterDropdown: args => {
            return <ColumnSetting
              {...this.props}
              {...args}
              key={col.id}
              setSortData={type => this.setSortData(type, col.field, editCode)}
              setSearchInfo={val => this.setSearchInfo(val, col.field, editCode)}
              tableConfig={editConfig}
              onMouseLeave={() => this.setState({ showFilterDropdown: false, showColumnSetting: null })}
              stateTableConfig={this.state.tableConfig}
              setTableConfig={value => this.setState({ tableConfig: value })}
            />
          },
          filterDropdownVisible: showFilterDropdown && showColumnSetting === col.id,
          filterIcon: filtered => (
            showColumnSetting === col.id
              ? <Icon type="setting" />
              : <div />
          ),
          onFilterDropdownVisibleChange: (visible) => {
            this.setState({
              showFilterDropdown: visible
            })
          },
          render: (text, record) => {
            return this.onRenderRowControl({ editCode, colConfig: col, record, text, params, parentId, parentRecord });
          }
        }
        col.width && (columnObj.width = col.width)
        tmp.push(columnObj);
      }
    });

    if (rowBtns && rowBtns.length) {
      let currRecord = {};
      let l = this.getRenderBtns({ btns: rowBtns, record: currRecord, editCode, parentId, parentRecord, type: 0 }).filter(value => typeof value !== "undefined").length;
      if (l === 0 || l == null) l = 1;
      tmp.push({
        title: '操作',
        key: rowBtns && rowBtns.length ? rowBtns[0].id : '',
        dataIndex: '',
        fixed: 'right',
        width: 32 * l,
        render: (text, record, index) => {
          return this.getRenderBtns({ btns: rowBtns, record, editCode, parentId, parentRecord, type: 0 });
        }
      })
    }

    if (tmp && tmp.length) {
      tmp.forEach((n, i) => {
        cols.push(n);
      });
    }
    return cols;
  };

  getEditTableData({ editCode, parentId, parentRecord }) {
    const editConfig = this.getEditConfig({ editCode });
    if (editConfig) {
      const data = this.state.data;
      if (!parentRecord) {
        if (editConfig.parentEditCode) {
          if (parentId) {
            this.getEditRecordById({
              data, editCode: editConfig.parentEditCode, id: parentId,
              onComplete: (p) => {
                parentRecord = p;
              }
            });
          }
        }
        else {
          parentRecord = data;
        }
      }
      if (parentRecord) {
        return getDataFieldValue(parentRecord, editConfig.dataNav);
      }
    }
  }

  setEditTableData({ editCode, data, isAppend, onComplete, parentId, parentRecord }) {
    const editConfig = this.getEditConfig({ editCode });
    const { dataNav, parentFieldName, sortField, sortOrder, } = editConfig;
    const tempData = { ...this.state.data };
    if (!parentRecord) {
      if (editConfig.parentEditCode) {
        if (parentId) {
          this.getEditRecordById({
            tempData, editCode: editConfig.parentEditCode, id: parentId,
            onComplete: (p) => {
              parentRecord = p;
            }
          });
        }
      }
      else {
        parentRecord = tempData;
      }
    }
    if (!parentRecord) {
      return;
    }

    let list = getDataFieldValue(parentRecord, dataNav);
    if (!list) {
      list = [];
      setDataFieldValue(parentRecord, dataNav, list);
    }
    const dData = [];
    let newData = list;
    if (isAppend) {
      if (data && data.length) {
        data.forEach(t => {
          if (parentFieldName && parentRecord && parentRecord.ID) {
            t[parentFieldName] = parentRecord.ID;
          }
          t.ORG_ID = (this.props.login ? this.props.login.OrgId : null);
          list.push(t);
        });
      }
    }
    else {
      newData.forEach((k, n) => {
        if (!k.CREATE_TIME) return;
        dData.push(k);
      });
      list = data ? data : [];
      setDataFieldValue(parentRecord, dataNav, list);
    }
    this.setDeletedData({ editCode: editCode, deletedDatas: dData });
    this.getRowNoByData({ data: list, sortField, sortOrder, });

    this.setState({
      data: tempData,
    }, () => {
      if (typeof onComplete === 'function') {
        onComplete();
      }
    });
  }

  setBantchEditTableData({ editCode, data, isAppend, onComplete, parentId, parentRecord }) {
    const editConfig = this.getEditConfig({ editCode });
    const { dataNav, parentFieldName, sortField, sortOrder, } = editConfig;
    let list = getDataFieldValue(parentRecord, dataNav);
    if (!list) {
      list = [];
      setDataFieldValue(parentRecord, dataNav, list);
    }
    const dData = [];
    let newData = list;
    if (isAppend) {
      if (data && data.length) {
        data.forEach(t => {
          if (parentFieldName && parentRecord && parentRecord.ID) {
            t[parentFieldName] = parentRecord.ID;
          }
          t.ORG_ID = (this.props.login ? this.props.login.OrgId : null);
          list.push(t);
        });
      }
    }
    else {
      newData.forEach((k, n) => {
        if (!k.CREATE_TIME) return;
        dData.push(k);
      });
      list = data ? data : [];
      setDataFieldValue(parentRecord, dataNav, list);
    }
    this.setDeletedData({ editCode: editCode, deletedDatas: dData });
    this.getRowNoByData({ data: list, sortField, sortOrder, });
  }


  /*
  表身渲染子表
  {record, editCode, editConfig,parentId:当前记录的父记录ID（当前记录为表身记录为空）,parentRecord:当前记录的父记录（当前记录为表身记录为空）}
  */
  onRenderRowSubRow({ record, editCode, editConfig, parentId, parentRecord }) {
    if (!editConfig) {
      editConfig = this.getEditConfig({ editCode });
    }
    if (editConfig.childrenEditCodes && editConfig.childrenEditCodes.length) {
      return editConfig.childrenEditCodes.length === 1 ?
        this.getRenderEditTable({ editCode: editConfig.childrenEditCodes[0], parentId: record.ID, parentRecord: record }) :
        <Tabs defaultActiveKey={editConfig.childrenEditCodes[0]}>
          {
            editConfig.childrenEditCodes.map(t => {
              const tempEditConfig = this.getEditConfig({ editCode: t });
              return <TabPane tab={tempEditConfig.label} key={t}>
                {
                  this.getRenderEditTable({ editCode: t, parentId: record.ID, parentRecord: record })
                }
              </TabPane>
            })
          }
        </Tabs>
    }
  }

  /*
  表身记录展开
  {editCode, editConfig, record:当前记录, expanded:是否展开,parentId：当前记录的父记录ID（当前记录为表身记录为空）,parentRecord:当前记录的父记录（当前记录为表身记录为空）}
  */
  onRowExpandRow({ editCode, editConfig, record, expanded, parentId, parentRecord }) { }

  genDataSource(editCode, tableData, editConfig) { // 生成表格的dataSource
    const { localSearch = {}, sortDirection } = this.state;
    let filterData = []
    if (tableData) {
      if (Object.keys(localSearch).length) {
        filterData = tableData.filter(record => {
          const col = editConfig.columns.filter(t => t.field === localSearch.fields)[0]; // '';//localSearch.fields
          let val = getDataFieldValue(record, col.field);
          const isShowCol = col.controlType === null || col.controlType === undefined || col.controlType === 0 || col.controlType > 100;
          if (isShowCol) {
            if (col.formatFuncName) {
              col.format = (params) => {
                const formatValue = this.onTableRowFormatColumn({ record, text: val, editCode, editConfig, colConfig: params.col });
                setDataFieldValue(record, (col.field ? col.field : col.formatFuncName) + '_formatValue', formatValue);
                val = formatValue;
              };
            }
            val = this.getTableCellText({ col, record, text: val, isReturnString: true });
          }

          //val = getDataFieldValue(record, col.field);
          if (col.field && col.field.indexOf('Nav_SysParams') > -1) {
            val = this.getControlValue({
              controlType: col.controlType, value: col.value,
              data: col.data
            });
          }

          if (val) { // 值
            if (typeof val === "number") {
              val = val.toString()
            }
            if (String(val) === "null") {
              return false
            }
            return val.indexOf(localSearch.value) >= 0;
          }

          return false;
        })
      } else {
        filterData = tableData
      }
    }

    if (editConfig && editConfig.columns && sortDirection) { // 排序
      Object.keys(sortDirection).forEach(i => {
        filterData = filterData.sort((a, b) => {
          if (typeof a[i] === "number") {
            return sortDirection[i] > 0 ? b[i] - a[i] : a[i] - b[i]
          } else if (typeof a === "string") {
            return sortDirection[i] > 0 ? b[i].length - a[i].length : a[i].length - b[i].length
          } else {
            return true
          }
        })
      })
    }
    return filterData
  }


  handlePageChange = (page, pationKey) => {

    if (this.state.detailPations.hasOwnProperty(pationKey)) {
      let pation = { ...this.state.detailPations }
      pation[pationKey].current = page;
      this.setState({
        detailPations: pation
      })
    }
  }
  showTotal = (total, range) => {
    return '共 ' + total + ' 条数据'
  }

  /*
    获取编辑表
    参数如下：
    {dataNav,editCode,columns,sortField,sortOrder,isRowDelete,isRowNo, width,height,isShow,isPermit,parentFieldName,parentId,getHeadFieldValue,expandedRowRender,filterDataFunc}=params?params:{};
  
   */
  getRenderEditTable(params) {
    const {
      editCode,
      parentId,
      parentRecord,
    } = params || {};
    const editConfig = this.getEditConfig({
      editCode
    });
    if (!editConfig) return null;
    const {
      checked,
      rowBtns,
      height,
      filterDataFunc
    } = editConfig;
    let { detailPations = {} } = this.state;
    const selectEditTableKey = `editTableSelectedKeys${editCode}${parentId || ''}`;
    let data = this.getEditTableData({
      editCode,
      parentId,
      parentRecord
    });

    if (typeof filterDataFunc === 'function') {
      const temp = filterDataFunc(data);
      if (temp !== undefined) {
        data = temp;
      }
    }

    const newColumns = this.getEditColumns({ ...params, ...editConfig, editConfig, parentId, parentRecord });

    /**
     * 固定规则：
     * 固定列要设置宽度（操作列除外）
     * 留少数几列不设定宽度
     */
    let isScrollX = () => {
      const totalWidth = newColumns.reduce((a, b) => {
        if (b.width) {
          return a + b.width
        } else {
          return a + 0
        }
      }, 0);
      if (checked || (rowBtns && rowBtns.length)) {
        return { scroll: { x: totalWidth + 200, y: height } }
      } else {
        return false
      }
    };
    //根据规则配置行样式 ：字段1,操作符，值1,样式1|字段2,操作符，值2,样式2
    let rowClassNameConf = (record) => {
      var className = "";
      if (editConfig?.editPage.NAV_ROW_CLASS_FILTER) {
        editConfig.editPage.NAV_ROW_CLASS_FILTER.split('|').forEach(item => {
          const conds = item.split(',')
          if (conds.length == 4) {
            if (conds[1] == 1)//等于
            {
              if (record[conds[0]] == conds[2]) {
                className = conds[3]
              }
            }
          }
        })
      }
      return styles[className];
    }
    let pationKey = "table_detail" + editCode;
    let pation = {
      current: 1,
      defaultPageSize: 10000,
      hideOnSinglePage: true
    }
    //editConfig
    if (editConfig?.editPage?.IS_PAGE) {
      let pageSize = editConfig.editPage.DEFAULT_PAGE_SIZE == 0 ? 10 : editConfig.editPage.DEFAULT_PAGE_SIZE;
      pation = {
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showSizeChanger: true,
        defaultPageSize: pageSize,
        current: 1,
        position: pageSize > 10 ? 'both' : 'bottom',
        hideOnSinglePage: false,
        showQuickJumper: true,
        showTotal: (total, range) => this.showTotal(total, range),
        onChange: page => this.handlePageChange(page, pationKey),
      }
    }
    if (!detailPations.hasOwnProperty(pationKey)) {
      detailPations[pationKey] = pation;
      this.setState({
        detailPations: detailPations
      })
    }

    return (
      <React.Fragment>
        {this.renderEditTableHead({ ...params, ...editConfig, editConfig, parentId, parentRecord }, selectEditTableKey)}
        <Table
          rowKey="ID"
          key={'table_' + editConfig.ID}
          bordered
          pagination={detailPations[pationKey]}
          size="small"
          {...isScrollX()}
          className="editBaseComponent_Table_className"
          rowClassName={record => rowClassNameConf(record)}
          rowSelection={this.getEditRowSelection({ checked, selectEditTableKey })}
          dataSource={this.genDataSource(editCode, data, editConfig)}
          columns={newColumns}
          expandedRowRender={(editConfig.hasChildren ? (record) => {
            return this.onRenderRowSubRow({ record, editCode, editConfig, parentId, parentRecord });
          } : null)}
          onExpand={(expanded, record) => {
            this.onRowExpandRow({ editCode, editConfig, record, expanded, parentId, parentRecord })
          }}
        />
      </React.Fragment>
    )
  }

  onLoadTreeConfigList() {

  }

  onLoadTreeData({ treeCode, searchValue, onComplete }) {
    const treeConfig = this.getTreeConfig({ treeCode });
    if (treeConfig) {
      const { sort, order, relationField, relationId, api, orgType } = treeConfig;
      if (!api) return;
      const treeLoadParam = this.state.treeLoadParam;
      let loadParam = treeLoadParam[treeCode];
      if (!loadParam) {
        loadParam = initFilter(this.props.login.OrgId, '', sort, order);
        extendRule(loadParam, "PARENT_ID", 1, "");
        const rules = this.props && this.props.data && this.props.data.rules ? this.props.data.rules : [];
        if (rules) {
          rules.forEach(item => {
            extendRule(loadParam, item.field, item.operator, item.value, item.isSysParam);
          });
        }
        treeLoadParam[treeCode] = loadParam;
      }
      const json = { ...loadParam };
      if (orgType) {
        json.OrgType = orgType;
      }
      if (searchValue) {
        addRuleAndGroups(json, searchValue);
      }

      //填加关联字段过滤
      if (relationField && relationId) {
        extendRule(json, relationField, 1, relationId);
      }

      this.props.dispatch({
        type: 'app/getTableData',
        payload: json,
        url: api,
        onComplete: (ret) => {
          if (ret) {
            if (!ret.IsSuccessful) {
              message.error(ret.ErrorMessage);
            }
            this.setTreeData({
              treeCode,
              data: ret.Data,
              onComplete,
            }, () => {
              this.onAfterLoadTreeData();
            });
          }
        }
      });
    }
  }

  onAfterLoadTreeData() {

  }

  onLoadTreeChildData({ treeCode, treeNode }) {
    return new Promise((resolve, reject) => {
      if (treeNode.props.dataRef.IS_LEAF) {
        reject();
      } else {
        const treeConfig = this.getTreeConfig({ treeCode });
        if (treeConfig) {
          const { sort, order, api } = treeConfig;
          if (api) {
            let json = initFilter(this.props.login.OrgId, '', sort, order);
            extendRule(json, "PARENT_ID", 1, treeNode.props.dataRef.ID);
            this.props.dispatch({
              type: 'app/getTableData',
              payload: json,
              url: api,
              onComplete: (ret) => {
                if (ret) {
                  if (!ret.IsSuccessful) {
                    message.error(ret.ErrorMessage);
                  }
                  const treeData = this.getTreeData({ treeCode });
                  this.getTreeDataById(treeData, treeNode.props.dataRef.ID, (data) => {
                    if (!data.Children) {
                      data.Children = [];
                    }
                    if (ret.Data) {
                      ret.Data.forEach(t => {
                        data.Children.push(t);
                      });
                    }
                  });
                  this.setTreeData({
                    treeCode,
                    data: treeData,
                  });
                }
              }
            });
          }
        }
        resolve();
      }
    });
  }

  /*
  获取树配置
   */
  getTreeConfig(params) {
    const { treeCode = this.defaultTreeCode } = params ? params : {};
    let treeConfig = this.state.treeConfig;
    if (!treeConfig) {
      treeConfig = {};
    }
    return treeConfig[treeCode];
  }

  /*
  设置树配置
   */
  setTreeConfig(params) {
    const { treeConfig, onComplete } = params ? params : {};
    let tempTreeConfig = this.state.treeConfig;
    if (!tempTreeConfig) {
      tempTreeConfig = {};
    }
    if (treeConfig.treeCode === undefined) {
      treeConfig.treeCode = this.defaultTreeCode;
    }
    tempTreeConfig = {
      ...tempTreeConfig,
      [treeConfig.treeCode]: treeConfig,
    };
    this.setState({
      treeConfig: tempTreeConfig
    }, () => {
      if (typeof onComplete === 'function') {
        onComplete();
      }
    })
  }

  /*
  获取树数据
   */
  getTreeData(params) {
    const { treeCode = this.defaultTreeCode } = params ? params : {};
    let data = this.state.treeData;
    if (!data) {
      data = {};
    }
    return data[treeCode];
  }

  /*
  设置树数据
   */
  setTreeData({ treeCode, data, onComplete }) {
    let tempData = this.state.treeData;
    if (!tempData) {
      tempData = {};
    }
    if (treeCode === undefined) {
      treeCode = this.defaultTreeCode;
    }
    tempData = {
      ...tempData,
      [treeCode]: data,
    };
    this.setState({
      treeData: tempData,
    }, () => {
      if (typeof onComplete === 'function') {
        onComplete();
      }
    });
  }

  /*
  获取选中节点ID
   */
  getSelectedNodeId(params) {
    const { treeCode = this.defaultTreeCode } = params ? params : {};
    let treeSelectedNodeId = this.state.treeSelectedNodeId;
    if (!treeSelectedNodeId) {
      treeSelectedNodeId = {};
    }
    return treeSelectedNodeId[treeCode];
  }

  /*
  设置选中节点ID
   */
  setSelectedNodeId({ treeCode, id, onComplete }) {
    let treeSelectedNodeId = this.state.treeSelectedNodeId;
    if (!treeSelectedNodeId) {
      treeSelectedNodeId = {};
    }
    if (treeCode === undefined) {
      treeCode = this.defaultTreeCode;
    }
    treeSelectedNodeId = {
      ...treeSelectedNodeId,
      [treeCode]: id
    };
    this.setState({
      treeSelectedNodeId
    }, () => {
      if (typeof onComplete === 'function') {
        onComplete();
      }
    });
  }

  getTreeNodeTitle({ treeCode, titleColumns, data }) {
    if (data.isAdd) {
      return '新增节点';
    }
    if (!titleColumns) {
      const treeConfig = this.getTreeConfig({ treeCode });
      if (treeConfig) {
        titleColumns = treeConfig.titleColumns;
      }
    }
    if (titleColumns && titleColumns.length) {
      let title = '';
      titleColumns.forEach(t => {
        let tmpValue = getDataFieldValue(data, t.field);
        tmpValue = tmpValue == null || tmpValue === undefined ? '' : tmpValue;
        title += tmpValue + "/";
      });
      title = title.substring(0, title.length - 1);
      return title;
    }
  }

  /*
  树拖拽
  {treeCode:树编号,dragId：当前拖拽的节点ID,dragParentId：拖拽后节点父节点ID,
    originDragParentId：原始节点父节点ID,dropId：拖拽到节点ID（一般不用）}
  */
  onTreeDrop({ treeCode, dragId, dragParentId, originDragParentId, dropId }) {

  }

  /*
  获取选中树节点标题
   */
  getTreeNodeSelectedTitle(params) {
    const { treeCode = this.defaultTreeCode } = params ? params : {};
    let data = null;
    const selectId = this.getSelectedNodeId({ treeCode });
    const treeConfig = this.getTreeConfig({ treeCode });
    if (selectId) {
      const treeData = this.getTreeData({ treeCode });
      this.getTreeDataById(
        treeData,
        selectId,
        (nodeData) => {
          data = nodeData;
        }
      );
    }
    if (data) {
      if (data.isAdd) {
        return '新增节点';
      }
      if (treeConfig && treeConfig.titleColumns && treeConfig.titleColumns.length) {
        return this.getTreeNodeTitle({ treeCode, titleColumns: treeConfig.titleColumns, data });
      }
      return data.NAME;
    }
  }

  /*
  选中树节点
   */
  selectTreeNode = (params) => {
    const { treeCode = this.defaultTreeCode, id } = params ? params : {};
    if (id) {
      const treeData = this.getTreeData({ treeCode });
      this.getTreeDataById(treeData, id, (ret) => {
        this.setSelectedNodeId({
          treeCode,
          id,
          onComplete: () => {
            this.onSelectedTreeNode({
              ...params,
              treeCode,
              data: ret,
            });
          }
        });
      });
    }
    else {
      this.setSelectedNodeId({
        treeCode,
        id,
        onComplete: () => {
          this.onSelectedTreeNode({
            ...params,
            treeCode,
            data: null,
          });
        }
      });
    }
  };

  /*
  选中树节点事件
   */
  onSelectedTreeNode(params) {
    // const {treeCode, id, data} = params ? params : {};
  }

  /*
  设置展开树键值
   */
  setTreeExpandedKeys({ treeCode, expandedKeys, onComplete }) {
    if (treeCode === undefined) {
      treeCode = this.defaultTreeCode;
    }
    let treeExpandedKeys = this.state.treeExpandedKeys;
    if (!treeExpandedKeys) {
      treeExpandedKeys = {};
    }
    treeExpandedKeys = {
      ...treeExpandedKeys,
      [treeCode]: expandedKeys,
    };
    this.setState({
      treeExpandedKeys
    }, () => {
      if (typeof onComplete === 'function') {
        onComplete();
      }
    });
  }

  /*
  获取右键菜单
   */
  getTreeNodeContextMenu(params) {
    const { data, treeCode = this.defaultTreeCode } = params ? params : {};
    const treeConfig = this.getTreeConfig({ treeCode });
    const selectId = this.getSelectedNodeId({ treeCode });
    if (treeConfig) {
      //添加同级菜单按钮到列表中
      if (treeConfig.btns) {
        const index = treeConfig.btns.findIndex(t => t.btnType === 3);
        const index2 = treeConfig.btns.findIndex(t => t.btnType === 3 && t.isAddChild);
        if (index !== -1 && index2 === -1) {
          const item = treeConfig.btns[index];
          treeConfig.btns.splice(index, 0, { ...item, id: guid(), pId: item.id, isAddChild: true });
        }
      }
      return <Menu className={styles.contextMenuList}>
        {
          treeConfig.btns ? treeConfig.btns.map(t => {
            if (t.btnType === undefined) return null;
            if (t.isRule && !permissionUtils(this.props.login).checkBtn(treeConfig.formId, (t.pId ? t.pId : t.id))) return null;
            if (t.btnType === 3) {//新增
              if (t.isAddChild) {
                return <Menu.Item key="sibling" onClick={() => this.addTreeNode({ treeCode, level: 'parent', id: data.ID })} disabled={data.isAdd || t.disabled || selectId !== data.ID}>
                  <Icon type="plus" />新增同级
                </Menu.Item>
              }
              return <Menu.Item key="next" onClick={() => this.addTreeNode({ treeCode, level: 'childred', id: data.ID })} disabled={data.isAdd || t.disabled || selectId !== data.ID}>
                <Icon type="plus" />新增下级
              </Menu.Item>
            }
            else if (t.btnType === 4) {//删除
              return <Menu.Item key="del" onClick={() => this.deleteTreeNode({ treeCode, id: data.ID })} disabled={t.disabled || selectId !== data.ID}>
                <Icon type="delete" />删除
              </Menu.Item>
            }
            else if (t.btnType === 10) {//复制新增
              return <Menu.Item key={'copy'} onClick={() => this.addTreeNode({ treeCode, level: 'parent', id: data.ID, isCopy: true })}
                disabled={data.isAdd || !selectId || t.disabled || selectId !== data.ID}>
                <Icon type="copy" />复制新增
              </Menu.Item>
            }
            return null;
          }) : null
        }
        {
          this.onTreeNodeContextMenu({ ...params, treeConfig })
        }
      </Menu>;
    }
  }

  /*
    获取树节点右击菜单
    {
    data, //节点数据
    treeCode,//树编号
    treeConfig//树配置信息
    }
   */
  onTreeNodeContextMenu(params) {
    // const {data,treeCode,treeConfig}=params?params:{};
  }


  /*
  新增树节点
   */
  addTreeNode({ treeCode, isCopy, level, id }) {
    const treeData = this.getTreeData({ treeCode });
    const newId = guid();
    const menuKey = 'treeNodeMenuKey_' + treeCode + '_' + id;//右击菜单键值  用于菜单隐藏
    const data = { ID: newId, IS_LEAF: true, isAdd: true, ORG_ID: this.props.login.OrgId };
    let treeExpandedKeys = this.state.treeExpandedKeys;//展开键值列表
    if (!treeExpandedKeys) {
      treeExpandedKeys = {};
    }
    let parentId = null;
    if (level === 'parent') {//新增当前节点同级
      this.getTreeParentById(treeData, id, (parent) => {
        if (parent) {
          parentId = parent.ID;
        }
      });
    }
    else if (level === 'childred') {//新增当前节点下级
      parentId = id;
    }

    // 删除前一次增加未保存项
    function delAdding(loop) {
      loop.forEach((item, key) => {
        if (item.hasOwnProperty("isAdd") && item["isAdd"]) {
          loop.splice(key, 1);
        }
        if (item.Children) {
          delAdding(item.Children)
        }
      })
    }

    delAdding(treeData);

    //添加到树数据中
    this.addTreeDataByParentId(treeData, parentId, data);

    if (parentId) {
      let tempKeys = treeExpandedKeys[treeCode];
      if (!tempKeys) {
        tempKeys = [];
      }
      tempKeys.push(parentId);
      treeExpandedKeys = {
        ...treeExpandedKeys,
        [treeCode]: tempKeys,
      };
    }
    let copySrcId = '';
    if (isCopy) {
      copySrcId = id;
    }
    data.PARENT_ID = parentId;
    let num = 0;
    treeData.forEach((n, i) => {
      if (n.NUM && n.NUM > num) {
        num = n.NUM;
      }
    });
    num++;
    data.NUM = num;
    this.setState({
      treeExpandedKeys,
      [menuKey]: false,
      copySrcId,
    }, () => {
      this.setTreeData({
        treeCode, data: treeData, onComplete: () => {
          this.selectTreeNode({ treeCode, isAdd: true, id: newId });
        }
      });
      this.onAfterAddTreeNode({ treeCode, newId, parentId, id, isCopy, newData: data, });
    });
  }

  /*
    新增树节点 后
    treeCode,
    newId, //新增节点ID
    parentId,//新增节点的父节点ID
    id,//来源节点ID  可能为空
    isCopy,//是否拷贝
    newData,//新增节点数据
   */
  onAfterAddTreeNode(params) {
    // const {treeCode,newId,parentId,id,isCopy,newData}=params;
  }

  /*
  删除树节点
   */
  deleteTreeNode(params) {
    const { treeCode = this.defaultTreeCode, id } = params ? params : {};
    const menuKey = 'treeNodeMenuKey_' + treeCode + '_' + id;//右击菜单键值  用于菜单隐藏
    this.setState({
      [menuKey]: false,
    });
    const treeConfig = this.getTreeConfig({ treeCode });
    if (treeConfig) {
      const { deleteApi } = treeConfig;
      const doDeleteTreeNode = () => {
        const treeData = this.getTreeData({ treeCode });
        let nodeData = null;
        this.deleteTreeDataById(treeData, id, null, (d) => {
          nodeData = d;
        });
        if (deleteApi) {
          this.addDeleteLog({ formCode: treeConfig.formCode, ids: id, formId: treeConfig.formId, extData: ('删除数据，详情：' + (nodeData ? JSON.stringify(nodeData) : '')) });
        }
        this.setState({
          parentId: '',
        }, () => {
          this.selectTreeNode({ treeCode, id: null, isDelete: true });
          this.onAfterDeleteTreeNode({ treeCode, id });
        });
      };
      if (deleteApi) {
        this.props.dispatch({
          type: 'app/deleteItemBatch',
          payload: {
            ids: id
          },
          url: deleteApi,
          onComplete: (ret) => {
            if (ret) {
              message.success('删除成功');
              doDeleteTreeNode();

            }
          }
        })
      }
      else {
        doDeleteTreeNode();
      }
    }
  }

  /*
  删除树节点 后
  {
  treeCode,树编号
  id//删除节点ID
  }
   */
  onAfterDeleteTreeNode(params) {
    // const {treeCode,id}=params?params:{};
  }

  /*
  根据树编号渲染树
   */
  getRenderTreeByConfig(treeCode) {
    if (treeCode === undefined) {
      treeCode = this.defaultTreeCode;
    }
    const treeConfig = this.getTreeConfig({ treeCode });
    if (treeConfig) {
      const treeData = this.getTreeData({ treeCode });
      const hasData = treeData && treeData.length;
      const { formCode, queryCode, sort, order, titleColumns, draggable } = treeConfig;
      const title = this.getTreeNodeSelectedTitle({ treeCode });
      const expandedKeys = this.state.treeExpandedKeys ? this.state.treeExpandedKeys[treeCode] : null;
      const selectedId = this.getSelectedNodeId({ treeCode });
      return <div className={styles.treeBox}>
        {formCode ? <Search formCode={formCode} code={queryCode} onSearch={(value) => this.onLoadTreeData({ treeCode, searchValue: value })} layout={{ span: 24 }} /> : null}
        {
          hasData
            ? <div className={styles.tipToContextMenu}>右键[添加/修改]</div>
            : <div className={`${styles.tipToContextMenu} ${styles.addNode}`} onClick={() => this.addTreeNode({ treeCode, level: 'all', id: null })}><Icon type="plus" />新增</div>
        }
        {
          title
          && <Alert message={<span>当前选中：{title}</span>} type="success" />
        }
        {
          hasData
            ? this.getRenderTree({
              data: treeData,  //数据
              treeCode,//树编号
              onLoadData: (({ treeCode: tempTreeCode, treeNode }) => {//加载数据事件
                return this.onLoadTreeChildData({
                  treeCode: tempTreeCode,
                  treeNode
                });
              }),
              onSelect: (params => {//选中节点事件
                this.selectTreeNode(params);
              }),
              expandedKeys,//已展开直接列表
              selectedId,//当前选中节点ID
              onExpand: ({ expandedKeys }) => {//展开事件
                this.setTreeExpandedKeys({ treeCode, expandedKeys });
              },
              sort,//排序字段
              order,//排序类型
              onContextMenu: (params) => {//获取节点右击菜单列表事件
                return this.getTreeNodeContextMenu({ ...params, treeCode });
              },
              getTreeNodeTitle: ({ data }) => {//获取节点标题函数
                return this.getTreeNodeTitle({ treeCode, titleColumns, data });
              },
              draggable,//是否拖拽
              onDrop: (updateData, dragId, dragParentId, dropId, originDragParentId) => {//拖拽事件
                this.setTreeData({
                  treeCode, data: updateData, onComplete: () => {
                    this.onTreeDrop({ treeCode, dragId, dragParentId, dropId, originDragParentId });
                  }
                });
              },
            }) : <div style={{ textAlign: "center" }}>无数据</div>
        }
      </div>
    }
  }

  /*
  保存
  params={
    btn:保存按钮对象
  }
   */
  save(params) {
    this.props.form.resetFields();
    const { onCheckBeforeSave } = params ? params : {};//btn:保存按钮对象
    const editConfig = this.getEditConfig();
    const { saveApi } = editConfig ? editConfig : {};
    if (!saveApi) return;
    if (this.onBeforeSave()) return;
    const { form, } = this.props;
    const { validateFieldsAndScroll } = form;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;
      let tmpIsError = this.onCheckBeforeSave({ ...params, errors });
      if (tmpIsError) return;
      const saveData = this.onGetSaveData(params);
      if (typeof onCheckBeforeSave === 'function') {
        const isError = onCheckBeforeSave({ saveData: saveData });
        if (isError) return;
      }
      this.doSave(saveApi, saveData, params);
    })
  }

  /*
    保存前检验有效性
  */
  onCheckBeforeSave(params) {
    const { errors } = params;
    if (errors) {
      return true;
    }
    let tmpIsError = false;
    const tmpStateData = this.state.data;
    const detailConfigs = this.state.editConfig ? this.state.editConfig.details : null;
    if (detailConfigs) {
      const checkDataVal = (data, editCode) => {
        const detailConfig = this.getEditConfig({ editCode });
        if (!detailConfig) return;
        const tempSubData = getDataFieldValue(data, detailConfig.dataNav);
        let hasRow = false;
        if (tempSubData && tempSubData.length) {
          tempSubData.forEach((k, n) => {
            if (detailConfig.editColumns && detailConfig.editColumns.length) {
              detailConfig.editColumns.forEach((n1, i1) => {
                if (n1.REQUIRED && n1.IS_DEFAULT) {//必填字段检查
                  const v = getDataFieldValue(k, (n1.CONTROL_TYPE === 9 && n1.INPUT_ID_FIELD ? n1.INPUT_ID_FIELD : n1.FIELD_NAME), null);
                  if (empty(v, true) && !tmpIsError) {
                    message.error('序号' + (n + 1) + ': 请填写' + n1.LABEL);
                    tmpIsError = true;
                  }
                }
                if (n1.VERIFY_EXPRESS) { // 正则表达式验证
                  const v = getDataFieldValue(k, (n1.CONTROL_TYPE === 9 && n1.INPUT_ID_FIELD ? n1.INPUT_ID_FIELD : n1.FIELD_NAME), null);
                  const tempVal = v === null || v === undefined ? '' : v;
                  if (!new RegExp(n1.VERIFY_EXPRESS).test(tempVal)) {
                    message.error('序号' + (n + 1) + ':' + n1.LABEL + (n1.VERIFY_ERROR_INFO ? n1.VERIFY_ERROR_INFO : '验证不通过'));
                    tmpIsError = true;
                  }
                }

                hasRow = true;
              });
            }
            if (detailConfig && detailConfig.childrenEditCodes && detailConfig.childrenEditCodes.length) {
              detailConfig.childrenEditCodes.forEach(t2 => {
                const config = this.getEditConfig({ editCode: t2 });
                let list = getDataFieldValue(k, config.dataNav);
                if (list && list.length) {
                  checkDataVal(list, t2);
                }
              });
            }
          });
        }
        if (detailConfig.isDetailRequired && hasRow) {
          message.error('至少需要输入一笔记录');
          tmpIsError = true;
        }
      }

      Object.keys(detailConfigs).forEach((n) => {
        const detailConfig = detailConfigs[n];
        if (detailConfig.parentEditCode) return;
        checkDataVal(tmpStateData, n);
      });
    }
    if (tmpIsError) {
      return true;
    }
  }

  /*
  保存前
   */
  onBeforeSave(params) {

  }

  /*
  保存之后
   */
  onAfterSave(params) {

  }

  /*
  获取保存数据
   */
  onGetSaveData(params) {
    const { onHandleRow } = params ? params : {};
    const tmpStateData = { ...this.state.data };
    const editConfig = this.getEditConfig();
    let updateData = getOnlyPropertyData(tmpStateData, true);
    if (editConfig.editPage && editConfig.editPage.IS_CONTAINS_NAV) {
      updateData = { ...this.state.data };
    }
    if (this.props.extraSaveData) {
      updateData = {
        ...updateData,
        ...this.props.extraSaveData
      }
    }
    //let updateData = getOnlyPropertyData(tmpStateData, true);
    if (!updateData.ORG_ID) {
      updateData.ORG_ID = this.props.login.OrgId;
    }
    if (typeof onHandleRow === 'function') {
      onHandleRow({ editCode: editConfig.editCode, record: updateData, srcRecord: tmpStateData });
    }

    const detailConfigs = this.state.editConfig ? this.state.editConfig.details : null;
    if (detailConfigs) {
      const doGetChildrenDeletedData = (data, editCode) => {
        const editConfig = this.getEditConfig({ editCode });
        if (editConfig && editConfig.childrenEditCodes && editConfig.childrenEditCodes.length) {
          data.forEach(t4 => {
            editConfig.childrenEditCodes.forEach(t2 => {
              const config = this.getEditConfig({ editCode: t2 });
              const tempDs = this.getDeletedData({ editCode: t2 });
              let list = getDataFieldValue(t4, config.dataNav);
              if (!list) {
                list = [];
                setDataFieldValue(t4, config.dataNav, list);
              }
              else {
                doGetChildrenDeletedData(list, t2);
              }
              if (tempDs && tempDs.length) {
                const realDs = tempDs.filter(t5 => t5[config.parentFieldName] === t4.ID);
                if (realDs && realDs.length) {
                  realDs.forEach(t7 => {
                    const r = getPropertyData(t7, true);
                    list.push(r);
                  });
                }
              }
            });
          });
        }
      }

      Object.keys(detailConfigs).forEach((n) => {
        const detailConfig = detailConfigs[n];
        if (detailConfig.parentEditCode) return;
        const tempSubData = getDataFieldValue(tmpStateData, detailConfig.dataNav);
        let subTableNewData = []; // 从表数据
        if (tempSubData && tempSubData.length) {
          tempSubData.forEach((k, n) => {
            const obj = getPropertyData(k);
            if (!obj.ORG_ID) {
              obj.ORG_ID = this.props.login.OrgId;
            }
            if (detailConfig.editColumns && detailConfig.editColumns.length) {
              detailConfig.editColumns.forEach((n1, i1) => {

                if (typeof onHandleRow === 'function') {
                  onHandleRow({ editCode: detailConfig.editCode, record: obj, srcRecord: k });
                }
              });
            }

            subTableNewData.push(obj);
          });
        }
        doGetChildrenDeletedData(subTableNewData, n);
        const deleteRows = this.getDeletedData({ editCode: detailConfig.editCode });
        if (deleteRows && deleteRows.length) { // 加入删除数据
          deleteRows.forEach((k1, n) => {
            const obj1 = getPropertyData(k1, true);
            subTableNewData.push(obj1);
          });
        }
        setDataFieldValue(updateData, detailConfig.dataNav, subTableNewData);
      });
    }
    return updateData;
  }

  /*
  实际调用API保存数据
   */
  doSave = (api, saveData, params) => {
    this.setState({ btnLoading: true });
    let that = this;
    this.props.dispatch({
      type: 'app/getDataByPost',
      payload: saveData,
      url: api,
      onComplete: (ret) => {
        var delay = 2000
        if (ret) {
          if (that.props.data?.onCancel) {
            that.props.data.onCancel();
          }
          if (that.props.data?.close) {
            //wyw onCancel 在 ShowModal 被赋值 只能添加 close 来处理窗体关闭事件需要的执行（刷新主界面信息）
            that.props.data.close();
          }
          delay = 500//如果需要请求api刷新页面数据 2000感觉太卡了
          message.success('执行成功');
        }
        this.onAfterSave({ ...params, isSuccess: ret, saveData });
        setTimeout(() => { this.setState({ btnLoading: false }) }, delay);
      }
    });
  };

  /*
       btn={
        id:按钮ID
        btnType:按钮类型
        code:按钮编号
        label:显示名称
        icon:按钮图标
        css:按钮样式
        formCode:表单编号
        api:API
        isConfirm:是否需确认
        checkSelected:检查选中
        isAddLog:是否需添加日志
       }
       type:0-行按钮  1-按钮  2-右侧按钮
     */
  getRenderBtn(params) {
    const { editCode, editConfig, record, btnConfig, type, parentId, parentRecord } = params ? params : {};
    const isRow = record;
    const isHeadBtn = btnConfig.isHeadBtn;
    //const selectKeys= this.state['editTableSelectedKeys'+editCode+(parentId?parentId:'')];

    if (btnConfig.btnType === 0 || btnConfig.btnType === 13) { //自定义弹窗、批量新增
      const closeFunc = (fun) => {
        const data = {};
        data['closeModelFunc' + (record ? (record.ID + btnConfig.id) : btnConfig.id)] = fun;
        this.setState(data);
      };
      const showData = {
        regClose: closeFunc,
      };
      const close = (type, data) => {
        if (type === undefined || type === 0) {
          const tmpFunc = this.state['closeModelFunc' + (record ? (record.ID + btnConfig.id) : btnConfig.id)];
          if (tmpFunc) {
            tmpFunc();
          }
        }
        if (btnConfig.btnType === 13) {
          this.onBatchAddRow(data, { ...params, thisRef: this })
        }
      };
      let btnParam = this.onEditBtnParam({ ...params, close });
      if (!btnParam) {
        btnParam = {};
      }
      let { disabled, click, onBtnDisabled, content } = btnParam ? btnParam : {};
      const getIds = () => {
        if (record) {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(record);
          }
          if (d) return;
          return record.ID;
        }
        const selectRecords = this.getEditSelectedRecord({ editCode, parentId, parentRecord });// this.state['editTableSelectedKeys'+editCode+(parentId?parentId:'')];
        const tempSelectRecordIds = [];
        selectRecords.forEach(t => {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(t);
          }
          if (d) return;
          tempSelectRecordIds.push(t.ID);
        });
        if (tempSelectRecordIds.length) {
          return tempSelectRecordIds.join(',');
        }
      };
      if (!content && btnParam) {
        const that = this;
        const clickKey = btnConfig.code ? btnConfig.code : btnConfig.id;
        const regClick = async function () {
          const ids = getIds();
          let isError = false;
          if (!ids && !isRow && btnConfig.checkSelected) {
            message.error('请选择记录');
            isError = true;
          }
          if (!isError) {
            await that.props.dispatch({
              type: 'custom/save',
              payload: {
                [clickKey + (record ? record.ID : '')]: true
              },
            });
          }
          that.btnOperateLog(btnConfig)
          return {
            isReturn: isError
          }
        };
        let tempData = {
          id: (record ? record.ID : ''),
          parentRecord: record,
          clickKey,
          close,
          getIds,
          onSave: () => {
            close();
            //this.onAfterBtnCallApi({...params});
          },
          onCancel: () => {
            close();
          },
          onRegDestroyCacheDataFunc: (ret) => {
            if (!this.regDestroyCacheDataFunc) {
              this.regDestroyCacheDataFunc = {};
            }
            this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')] = ret;
          },
          btnTypeBatchAdd: btnConfig.btnType === 13
        };
        if (btnParam.data) {
          tempData = {
            ...tempData,
            ...btnParam.data,
          }
        }
        if (btnConfig.customParams) {
          if (btnConfig.customParams.indexOf(',') == -1) {
            if (this.props.data && this.props.data.record && this.props.data.record.ID) {
              let rule = [
                {
                  field: btnConfig.customParams,
                  operator: 1,
                  value: this.props.data.record.ID
                }
              ];
              tempData.rules = [...rule];
            } else if (btnConfig.customParams != null && btnConfig.customParams.indexOf('parentRecord') > -1) {
              //wyw BS057 弹窗 BS077 传递父项信息 到页面
              let rule = [
                {
                  field: "parentRecord",
                  operator: 1,
                  value: this.state.data
                }
              ];
              tempData.rules = [...rule];
            }
          } else {
            let cParams = btnConfig.customParams.split('&');
            let rules = [];
            let cRules = cParams.forEach(item => {
              let ruleary = item.split(',');
              let val = ruleary[2];
              let index = val.indexOf("@head.");
              if (index == 0) {
                const field = val.substring(6);
                val = getDataFieldValue(this.props.data.record, field);
              }
              let rule = {
                field: ruleary[0],
                operator: ruleary[1],
                value: val
              }
              rules.push(rule);
            })
            tempData.rules = rules;
          }
        }



        btnParam.content = <FormPage formCode={btnConfig.formCode} data={tempData} />;
        btnParam.click = () => { return regClick() };
        showData.close = () => {
          if (this.regDestroyCacheDataFunc && this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')]) {
            this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')]();
          }
        }
      }
      if (btnParam) {
        extend(showData, btnParam);
      }
      const tempSelectKeys = this.getEditSelectedKeys({ editCode, parentId, parentRecord });
      return <ShowModal key={record ? (record.ID + btnConfig.id) : btnConfig.id} title={btnConfig.label} data={showData}>
        {isHeadBtn ?
          <Button type={btnConfig.css} icon={btnConfig.icon} disabled={disabled || !getIds()}>{btnConfig.label}</Button>
          : (isRow
            ? (
              btnConfig.btn.IS_SHOWLAB ? <Button type={btnConfig.css} icon={btnConfig.icon} title={btnConfig.label} disabled={disabled || !getIds()} >{btnConfig.label}</Button>
                : <Button type={btnConfig.css} icon={btnConfig.icon} title={btnConfig.label} size="small" disabled={disabled || !getIds()} />
            )
            : <Button type={btnConfig.css} icon={btnConfig.icon} disabled={disabled || (!tempSelectKeys || !tempSelectKeys.length) && !isRow && btnConfig.checkSelected}>{btnConfig.label}</Button>)}
      </ShowModal>;
    }
    else if (btnConfig.btnType === 1) {
      // const isShow = this.props.data ? this.props.data.isShow : false;
      // const isPermit = this.props.data ? this.props.data.isPermit : false;
      if (btnConfig.isHidden) return;//SAVE_CLOSE_TYPE

      // wyw 非 待办 进入  "保存并" 不显示   (editConfig.formCode.indexOf("BS")>-1||editConfig.formCode.indexOf("CM")>-1) 模块方式限制  && editConfig.editCode!='T_SC_MT_MEETING'  表单方式限制
      if (this.props.data != null && (this.props.data.TaskID == null || (this.props.data.tableKey != "1" && this.props.data.tableKey != "4")) && btnConfig.customParams && btnConfig.label.indexOf("保存并") > -1 && this.props.data.id != null && this.props.data.id != '' && (editConfig.editCode.indexOf("_AE_") > -1 || editConfig.editCode.indexOf("_BS_") > -1 || editConfig.editCode.indexOf("_MT_") > -1 || editConfig.editCode.indexOf("_OH_") > -1 || editConfig.editCode.indexOf("_TI_") > -1 || editConfig.editCode.indexOf("_TL_") > -1)) return;//wyw 列表 编辑 进入 不加载 提交按钮 
      return <Button key={btnConfig.id} type={btnConfig.css} icon={btnConfig.icon} loading={this.state.btnLoading}
        // disabled={!this.state.data||!this.state.data.ID||btnConfig.disabled}
        disabled={!this.state.data || !Object.keys(this.state.data).length || btnConfig.disabled}
        onClick={() => {
          if (typeof this.onSave === 'function') {
            this.onSave(btnConfig.saveCloseType, btnConfig.saveClearType, btnConfig.customParams);
          }
          else {
            this.save();
          }
          this.btnOperateLog(btnConfig)
        }}>{btnConfig.label}</Button>;
    }
    //  else if (btnConfig.btnType === 2) { // 刷新
    //     if(!isRow) {
    //       return <Button onClick={()=>{this.loadTableData({tableCode})}} icon="reload" key={btnConfig.id}>刷新</Button>;
    //     }
    //   }
    else if (btnConfig.btnType === 3) {
      if (btnConfig.isHeadBtn) {
        const btnParam = this.onEditBtnParam({ ...params });
        let { disabled, } = btnParam ? btnParam : {};
        disabled = disabled ? disabled : btnConfig.disabled;
        return (
          <Button
            type="primary"
            icon="plus"
            onClick={() => {
              this.btnOperateLog(btnConfig)
              this.onLoadData()
            }}
            disabled={disabled}
          >新增</Button>
        )
      }
      if (btnConfig.isDetailBtn) {
        const btnParam = this.onEditBtnParam({ ...params });
        let { disabled, } = btnParam ? btnParam : {};
        disabled = disabled ? disabled : btnConfig.disabled;
        return (
          <Button
            onClick={() => {
              this.btnOperateLog(btnConfig)
              this.onAddRow({ ...params, editConfig, thisRef: this })
            }}
            type="primary"
            icon="plus"
            disabled={disabled}
          >新增</Button>
        )
      }
      return;
    }
    else if (btnConfig.btnType === 4) { //删除
      const btnParam = this.onEditBtnParam({ ...params });
      let { disabled, onBtnDisabled } = btnParam ? btnParam : {};
      const getIds = () => {
        if (record) {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(record);
          }
          if (d) return;
          return record.ID;
        }
        const selectRecords = this.getEditSelectedRecord({ editCode, parentId, parentRecord });// this.getTableSelectedRecord({tableCode});
        const tempSelectRecordIds = [];
        selectRecords.forEach(t => {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(t);
          }
          if (d) return;
          tempSelectRecordIds.push(t.ID);
        });
        if (tempSelectRecordIds.length) {
          return tempSelectRecordIds.join(',');
        }
      };
      const doDelete = (json = {}) => {
        const api = btnConfig.api;
        if (!api) {
          if (btnConfig.isDetailBtn) {
            const tempIds = getIds();
            if (tempIds) {
              this.onDeleteRow({ ...params, ids: tempIds.split(','), });
            }
            return;
          }
          message.error('请配置删除API');
          return;
        }
        this.props.dispatch({
          type: 'app/deleteItem',
          payload: json,
          url: api,
          onComplete: (ret) => {
            if (ret) {
              message.success('删除成功');
              this.onAfterBtnCallApi({ ...params });
              if (btnConfig.isAddLog) {
                const formId = (editConfig.formId ? editConfig.formId : (editConfig.formData ? editConfig.formData.ID : this.props.formId));
                const formCode = editConfig.formCode ? editConfig.formCode : (editConfig.formData ? editConfig.formData.CODE : this.props.formCode);
                this.addDeleteLog({ formCode, ids: getIds(), formId, extData: ('删除数据，详情：' + JSON.stringify(record)) });
              }
            }
          }
        })
      }
      disabled = disabled ? disabled : btnConfig.disabled;
      if (btnConfig.isDetailBtn) {
        if (!isRow) {
          const tempSelectKeys = this.getEditSelectedKeys({ editCode, parentId, parentRecord });
          return (
            <Button
              onClick={() => {
                this.btnOperateLog(btnConfig)
                doDelete();
              }}
              type={btnConfig.css}
              icon={btnConfig.icon}
              disabled={disabled || !tempSelectKeys || !tempSelectKeys.length}
            >
              删除
            </Button>
          )
        }
      }
      if (isRow) {
        return (
          <ConfirmButton
            key={btnConfig.id}
            isConfirm={true}
            onClick={() => {
              this.btnOperateLog(btnConfig)
              doDelete({ id: getIds() })
            }}
            type={btnConfig.css} icon={btnConfig.icon}
            title="删除"
            size={isHeadBtn ? null : "small"}
            confirmTitle={'是否确定删除?'}
            disabled={disabled || !getIds()}
          />
        )
      }
      else {
        const tempSelectKeys = this.getEditSelectedKeys({ editCode, parentId, parentRecord });
        return (
          <ConfirmButton
            key={btnConfig.id}
            isConfirm={true}
            onClick={() => {
              this.btnOperateLog(btnConfig)
              doDelete({ ids: getIds() })
            }}
            type={btnConfig.css}
            icon={btnConfig.icon}
            title="删除"
            confirmTitle={'是否确定删除?'}
            disabled={disabled || !tempSelectKeys || !tempSelectKeys.length}
          />
        )
      }
    }
    else if (btnConfig.btnType === 6) {//自定义点击
      const btnParam = this.onEditBtnParam({ ...params });
      let { disabled, click, } = btnParam ? btnParam : {};
      const regClick = () => {
        let tempBtnParam = null;
        if (typeof click === 'function') {
          tempBtnParam = click();
        }
        let { json, onBtnDisabled, onClick } = tempBtnParam ? tempBtnParam : {};
        const getIds = () => {
          if (record) {
            let d = false;
            if (typeof onBtnDisabled === 'function') {
              d = onBtnDisabled(record);
            }
            if (d) return;
            return record.ID;
          }
          const selectRecords = this.getEditSelectedRecord({ editCode, parentId, parentRecord });
          const tempSelectRecordIds = [];
          selectRecords.forEach(t => {
            let d = false;
            if (typeof onBtnDisabled === 'function') {
              d = onBtnDisabled(t);
            }
            if (d) return;
            tempSelectRecordIds.push(t.ID);
          });
          if (tempSelectRecordIds.length) {
            return tempSelectRecordIds.join(',');
          }
        };
        const ids = getIds();
        if (!ids && (isRow || !isRow && btnConfig.checkSelected)) {
          message.error('请选择记录或者记录无效');
          return;
        }
        if (btnConfig.api) {
          const filter = initFilter(this.props.login.OrgId, ids);
          const temJson = json ? { ...filter, ...json } : filter;
          if (typeof onClick === 'function') {
            if (onClick(temJson, ids)) {
              return;
            }
          }
          this.props.dispatch({
            type: 'app/getDataByPost',
            payload: temJson,
            url: btnConfig.api,
            onComplete: (ret) => {
              if (ret) {
                this.onAfterBtnCallApi({ ...params });
                message.success('执行成功');
                //添加日志
                if (btnConfig.isAddLog) {
                  const formId = (editConfig.formId ? editConfig.formId : (editConfig.formData ? editConfig.formData.ID : this.props.formId));
                  const formCode = editConfig.formCode ? editConfig.formCode : (editConfig.formData ? editConfig.formData.CODE : this.props.formCode);
                  const title = '用户【' + this.props.login.user.NAME + '】:执行按钮' + btnConfig.title;
                  const data = 'ID:' + ids;
                  const extData = "Json:" + JSON.stringify(temJson);
                  this.addOtherLog({ formCode, formId, title, data, extData });
                }
              }
            }
          })
          this.btnOperateLog(btnConfig)
        }
      };
      const tempSelectRecords = this.getEditSelectedRecord({ editCode, parentId });
      disabled = disabled ? disabled : (((isRow && false || !isRow && (!tempSelectRecords || !tempSelectRecords.length) && btnConfig.checkSelected)) ? true : false);
      return (
        <ConfirmButton
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          onClick={regClick}
          isConfirm={btnConfig.isConfirm}
          type={btnConfig.css}
          icon={btnConfig.icon}
          title={btnConfig.label}
          size={isRow && !isHeadBtn ? 'small' : null}
          confirmTitle={'是否确认执行?'}
          disabled={disabled}
        />
      )
    }
    else if (btnConfig.btnType === 7) {//自定义
      const btnParam = this.onEditBtnParam({ ...params });
      let { disabled, json, onBtnDisabled, content, onClick } = btnParam ? btnParam : {};
      const getIds = () => {
        if (record) {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(record);
          }
          if (d) return;
          return record.ID;
        }
        const selectRecords = this.getEditSelectedRecord({ editCode, parentId });
        const tempSelectRecordIds = [];
        selectRecords.forEach(t => {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(t);
          }
          if (d) return;
          tempSelectRecordIds.push(t.ID);
        });
        if (tempSelectRecordIds.length) {
          return tempSelectRecordIds.join(',');
        }
      };
      if (content) {
        return content;
      }
      if (btnConfig.api) {
        const regClick = () => {
          const ids = getIds();
          if (!ids && !isRow && btnConfig.checkSelected) {
            message.error('请选择记录');
            return;
          }
          const filter = initFilter(this.props.login.OrgId, ids);
          const temJson = json ? { ...filter, ...json } : filter;
          if (typeof onClick === 'function') {
            if (onClick(temJson, ids)) {
              return;
            }
          }
          this.props.dispatch({
            type: 'app/getDataByPost',
            payload: temJson,
            url: btnConfig.api,
            onComplete: (ret) => {
              if (ret) {
                // this.loadTableData({tableCode});
                this.onAfterBtnCallApi({ ...params });
                message.success('执行成功');
                //添加日志
                if (btnConfig.isAddLog) {
                  const formId = (editConfig.formId ? editConfig.formId : (editConfig.formData ? editConfig.formData.ID : this.props.formId));
                  const formCode = editConfig.formCode ? editConfig.formCode : (editConfig.formData ? editConfig.formData.CODE : this.props.formCode);
                  const title = '用户【' + this.props.login.user.NAME + '】:执行按钮' + btnConfig.title;
                  const data = 'ID:' + ids;
                  const extData = "Json:" + JSON.stringify(temJson);
                  this.addOtherLog({ formCode, formId, title, data, extData });
                }
              }
            }
          })
          this.btnOperateLog(btnConfig)
        };
        const tempSelectKeys = this.getEditSelectedKeys({ editCode, parentId, parentRecord });
        disabled = disabled ? disabled : ((isRow && !getIds() || (!isRow && (!tempSelectKeys || !tempSelectKeys.length) && btnConfig.checkSelected)) ? true : false);
        return (
          <ConfirmButton
            key={record ? (record.ID + btnConfig.id) : btnConfig.id}
            onClick={regClick}
            isConfirm={btnConfig.isConfirm}
            type={btnConfig.css}
            icon={btnConfig.icon}
            title={btnConfig.label}
            size={isRow && !isHeadBtn ? 'small' : null}
            confirmTitle={'是否确认执行?'}
            disabled={disabled}
          />
        )
      }
    }
    else if (btnConfig.btnType === 10) {
      this.copySrcId = this.state.data && this.state.data.CREATE_TIME ? this.state.data.ID : null;
      const btnParam = this.onEditBtnParam({ ...params });
      let { disabled, } = btnParam ? btnParam : {};
      disabled = disabled ? disabled : btnConfig.disabled;
      disabled = disabled ? disabled : !this.copySrcId;
      return (
        <Button
          onClick={() => {
            this.btnOperateLog(btnConfig)
            this.onLoadData()
          }}
          type="primary"
          icon="copy"
          disabled={disabled}
        >复制新增</Button>
      )
    }
    // 列表查看
    else if (btnConfig.btnType === 12) {
      return (
        <TableModal
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          formCode={btnConfig.formCode}
          id={record.ID}
          customParams={btnConfig.customParams}
          data={record}
          title={btnConfig.label}
          parentId={btnConfig.btnType === -1 ? record.parent_id : record.ID}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof this.click === 'function') {
              this.click(visible)
            }
          }}>
          <Icon type={btnConfig.icon} title={btnConfig.label} />
        </TableModal>
      )
    }  // 组合表单
    else if (btnConfig.btnType === 14) {
      return (
        <CombinationModal
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          formCode={btnConfig.formCode}
          id={record.ID}
          customParams={btnConfig.customParams}
          data={record}
          title={btnConfig.label}
          parentId={btnConfig.btnType === -1 ? record.parent_id : record.ID}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof this.click === 'function') {
              this.click(visible)
            }
          }}>
          <Icon type={btnConfig.icon} title={btnConfig.label} />
        </CombinationModal>
      )
    }
    // 自定义弹窗
    else if (btnConfig.btnType === 0) {
      return (
        <FormModal
          key={record ? (record.id + btnConfig.id) : btnConfig.id}
          formCode={btnConfig.formCode}
          id={record.id}
          customParams={btnConfig.customParams}
          data={record}
          title={btnConfig.label}
          parentId={btnConfig.btnType === -1 ? record.parent_id : record.id}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof this.click === 'function') {
              return this.click(visible)
            }
          }}>
          <Icon type={btnConfig.icon} title={btnConfig.label} />
        </FormModal>
      )
    }

    return isRow && !btnConfig.isHeadBtn ?
      <Button type={btnConfig.css} icon={btnConfig.icon} size="small" title={btnConfig.label} /> :
      <Button type={btnConfig.css} icon={btnConfig.icon} >{btnConfig.label}</Button>;
  }

  /*
  在按钮调用API之后调用
  */
  onAfterBtnCallApi(params) {
    this.onLoadData();
  }

  /*
      参数：{
        editCode,editConfig,record,btnConfig,
        type:0-行按钮  1-按钮  2-右侧按钮
        按钮类型：
           0://自定义弹窗
             close 关闭事件,selectRecords：选中行项函数
           6://自定义点击事件
             selectRecords：选中行项函数
           7://自定义
             selectRecords：选中行项函数
       }
       返回值：{
         按钮类型：
             0://自定义弹窗
              disabled 按钮是否失效,click：点击事件,onBtnDisabled：按钮失效事件,content：弹窗中显示的文本DOM
             3，5,8，10：// 新增 编辑 查看 复制新增
                disabled:按钮是否失效,click:点击事件
             4:删除
                 disabled:按钮是否失效
              6:自定义点击事件
                 disabled 按钮是否失效,click：点击事件,onBtnDisabled：按钮失效事件,json：点击调用参数
              7:自定义
                disabled 按钮是否失效,content：弹窗中显示的文本DOM,onBtnDisabled：按钮失效事件,json：点击调用参数
       }
   */
  onEditBtnParam(params) {
    // const { editCode, editConfig, record, btnConfig } = params || {};
    return {};
  }

  // onRenderBtns(btns,code) {
  //   return btns && btns.length ? btns.map((item, key) => {
  //     if(!(code && item.code === code || !code&!item.code))return null;
  //     if (item.ENABLE_STATUS === 1) return false;
  //     if (item.IS_RULE && !permissionUtils(this.props.login).checkBtn(this.state.formData.ID, item.ID)) {
  //       return false;
  //     }
  //     return this.onRenderBtn({ btn: item });
  //   }) : null;
  // }

  onRenderBtn(params) {
    return this.getRenderBtn(params);
  }

  getRenderBtns = (params) => { // 加载按钮
    let { btns, code, parentRecord, editCode, editConfig, record } = params ? params : {};
    const filterBtns = []
    if (btns && btns.length) {
      btns.forEach(btn => {
        const { BTN_CONDITION } = btn.btn || {}
        if (BTN_CONDITION) {
          const conditions = BTN_CONDITION.split('|').map(item => {
            const conds = item.split(',')
            return {
              field: conds[0],
              operate: conds[1],
              value: conds[2]
            }
          })
          const find = conditions.find(cond => {
            const { field, operate, value } = cond
            switch (Number(operate)) {
              case 1:
                // 编辑表单表格上方的按钮显示条件数据来源为onRenderHeadControls渲染出的表单数据
                // record 为编辑表单回显获取到的值，this.state.data为新增表单时输入的值，一般情况下，这两个值是一样的
                const targetRecord = record || this.state.data || {}
                const keypaths = field.split('.')

                let hasOwnProperty = false
                if (keypaths.length === 1) {
                  hasOwnProperty = targetRecord.hasOwnProperty(keypaths[0])
                } else {
                  const keypath = keypaths.filter((item, index, arr) => index < arr.length - 1).reduce(function (a, b) { return a + '.' + b })
                  const targetObj = get(targetRecord, keypath) || {}
                  hasOwnProperty = targetObj.hasOwnProperty(keypaths[keypaths.length - 1])
                }
                // 如果配了显示条件，但记录中没有对应的 field 属性，则认为此条配置无效，按钮正常显示
                return !hasOwnProperty || get(targetRecord, field) == value
              default:
                return false
            }
          })
          find && filterBtns.push(btn)
        } else {
          filterBtns.push(btn)
        }
      })
    }
    return filterBtns.map((item, key) => {
      //按钮配置了编码，为何要通过编码去过滤，和查询条件分组一个道理，可是编辑页不存在此情况
      if (!(code && item.code === code || !code & !item.code)) return null;
      if (!editConfig) {
        editConfig = this.getEditConfig({ editCode });
      }
      return this.onRenderBtn({ ...params, btnConfig: item, btn: item.btn, editConfig, parentRecord });
    });
  };

  render() {
    return (
      <div>
      </div>
    )
  }
}

export default EditBaseComponent;
