import React from 'react'
import {
  extendRule,
  getDataFieldValue,
  getParseValue,
  guid,
  initFilter,
  permissionUtils,
  setDataFieldValue,
  extendInclude,
  getCustomParams,
  extendIgnoreDataRule
} from '../../utils/common'
import { message, Collapse, Button, Row, Form, Dropdown, Tabs } from 'antd';
import EditBaseComponent from "../EditBaseComponent";
import styles from '../Component.css';
import CustomFieldsManage from '../../components/common/CustomFieldsManage';
import classNames from 'classnames'

const Panel = Collapse.Panel;
const TabPane = Tabs.TabPane;

class EditComponent extends EditBaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      initData: {
        ENABLE_STATUS: 0
      },
      columns: [],
      editData: {},
      btnData: [],
      formData: {},
      jsFile: '',
      loading: false,
      subTable: [],
      isRegSaveFunc: false,
      btnLoading: false,          // 触发按钮loading
      cusLoading: false,          // 触发自定义按钮loading
    };
    this.billStatus = 0;
    this.getparentinfo = false;
  };
  componentDidMount() {
    super.componentDidMount();
    this.billStatus = 0;
  };

  componentWillReceiveProps(NextProps) {
    super.componentWillReceiveProps(NextProps);
  }

  onLoadData() {
    super.onLoadData();
    this.billStatus = 0;
    this.getEditConfigByPage({ formCode: this.props.formCode });
  }


  /*
      获取动态函数
   */
  getDynJsFunc(funcName) {
    let func = null;
    //取静态公共方法
    if (!func) {
      const jsFile = this.getStaticJsFunc();
      func = jsFile[funcName];
    }
    //取props中的动态js方法
    if (!func && this.props.dynJsFunc) {
      func = this.props.dynJsFunc[funcName];
    }

    //取加载data中的动态方法
    if (!func && this.props && this.props.data && this.props.data.dynJsFunc) {
      func = this.props.data.dynJsFunc[funcName];
    };
    //取动态js中的动态方法
    if (this.state.jsFile || this.props.jsFile) {
      const jsFiles = this.state.jsFile ? this.state.jsFile.split(',') : [];
      const tmpJs = this.props.jsFile ? this.props.jsFile.split(',') : [];
      if (tmpJs && tmpJs.length) {
        tmpJs.forEach(t => {
          jsFiles.push(t);
        });
      };
      if (jsFiles) {
        jsFiles.forEach(t => {
          if (func) return;
          const jsFile = require('../../files/edit/' + t).default;
          func = jsFile[funcName];
        });
      }
    }


    return func;
  };


  setStateData(val) {
    this.setState({
      data: val
    })
  }
  getStaticJsFunc() {
    return {
    };
  };

  /*
    根据编辑页列信息获取控件配置信息
    col：编辑页列信息
    record：数据记录
   */
  getControlConfigByEditCol({ col, onChange, onBlur }) {
    const { CONTROL_TYPE: controlType } = col;
    const promptInfo = col.PROMPT_INFO ? col.PROMPT_INFO : (col.LABEL + (controlType === 13 ? ',回车填充' : ''));
    const isShow = (this.props.data && this.props.data.isShow) ? this.props.data.isShow : false;
    const isPermit = (this.props.data && this.props.data.isPermit) ? this.props.data.isPermit : false;
    const disabled = !col.EDITABLE || isShow || isPermit && !col.PERMIT_EDITABLE;
    let tmpData = {};
    // 下拉
    if (controlType === 3) {
      tmpData = {
        enumName: col.ENUM,
      }
    }
    // 多选控件
    else if (controlType === 5) {
      tmpData = {
        enumName: col.ENUM,
      }
    }
    // 数值
    else if (controlType === 7) {
      tmpData = {
        maxVal: col.MAX_VAL || 0,//最大值
        minVal: col.MIN_VAL || 0, //最小值
        isCheckMax: col.IS_CHECK_MAX,//是否开启最大值校验
        isCheckMin: col.IS_CHECK_MIN,//是否开启最小值校验
        step: col.STEP,//步长
      }
    }
    // 分页下拉 树选择 扫描 级联
    else if (controlType === 9 || controlType === 13 || controlType === 11 || controlType === 17 || controlType == 24) {
      const extIncludeFields = [];
      // 填充导航属性
      if (col.Nav_FillMaps) {
        col.Nav_FillMaps.forEach(t => {
          if (t.SRC_NAV) {
            extIncludeFields.push(t.SRC_NAV);
          }
          if (t.Nav_Details) {
            t.Nav_Details.forEach(s => {
              if (s.SRC_FIELD_NAME && s.SRC_FIELD_NAME.indexOf('.') > 0) {
                let pos = s.SRC_FIELD_NAME.lastIndexOf('.');
                let includeField = s.SRC_FIELD_NAME.substring(0, pos);
                extIncludeFields.push(t.SRC_NAV + '.' + includeField);
              }
            });
          }
        });
      }

      tmpData = {
        api: col.INPUT_DATA_API,
        showField: col.INPUT_SHOW_FIELD,
        showLevel: col.INPUT_DATA_LEVEL,
        onlyLeaf: col.IS_ONLY_CHECK_LEAF,
        navField: col.INPUT_NAV_FIELD,
        labelField: col.INPUT_LABEL_FIELD,
        selectLabelField: col.SELECTD_LABEL_FIELD,
        filterField: col.INPUT_FILTER_FIELD,
        sortField: col.INPUT_SORT_FIELD,
        sortOrder: col.INPUT_SORT_ORDER,
        saveField: col.INPUT_SAVE_FIELD,
        idField: col.INPUT_ID_FIELD,
        extIncludeFields: extIncludeFields,
        filterOrgType: col.INPUT_FILTER_ORG_TYPE,
        isKeepValueByClear: col.INPUT_KEEP_VALUE_BY_NO_SRC,
        authOrgCodes: col.AUTH_ORG_CODES,
        isIgnoreTenant: col.IS_IGNORE_TENANT
      }
    }
    // 下拉多选
    else if (controlType === 12) {
      tmpData = {
        enumName: col.ENUM,
      }
    }
    // 系统序列号控件
    else if (controlType === 14) {
      tmpData = {
        codeRuleType: col.CODE_RULE_TYPE,
        onGetCodeRule: (save, codeType) => {
          const json = initFilter(this.props.login.OrgId);
          json.Count = 1;
          json.CodeType = codeType;
          this.props.dispatch({
            type: 'app/genSystemCode',
            payload: json,
            onComplete: (ret) => {
              if (ret) {
                save(ret);
                this.saveUseCodeRule(codeType, ret);
              }
            }
          });
        }
      }
    }

    return {
      id: col.ID,
      controlType,
      code: col.CODE,
      visible: col.IS_DEFAULT,
      field: col.FIELD_NAME,
      disabled: disabled,
      isRequire: col.REQUIRED,
      label: col.LABEL,
      promptInfo,
      onChange,
      ruleExp: col.VERIFY_EXPRESS,
      ruleExpInfo: col.VERIFY_ERROR_INFO,
      width: col.WIDTH,
      height: col.HEIGHT,
      showFormCode: col.SHOW_FORM_CODE,
      showIdField: col.SHOW_ID_FIELD,
      showFormParms: col.CUSTOM_PARAMS,
      editFormCode: col.EDIT_FORM_CODE,
      editFormFilter: col.EDIT_FORM_FILTER,
      editFormFilterValue: col.EDIT_FORM_FILTER_VALUE,
      data: tmpData,
      onBlur,
      span: this.props.isTree ? { span: 12 } : null,
      column: col,
      caseType: col.CASE,
      minLen: col.MIN_LEN || 0,
      maxLen: col.MAX_LEN || 0, // 0 表示不限制最大长度
      maxVal: col.MAX_VAL || 0,//最大值
      minVal: col.MIN_VAL || 0, //最小值
      isCheckMax: col.IS_CHECK_MAX,//是否开启最大值校验
      isCheckMin: col.IS_CHECK_MIN,//是否开启最小值校验
      step: col.STEP,//步长
      errVerifyMsg: col.VERIFY_MSG,
      remark: col.REMARK
    }
  }



  /*
    根据编辑页列信息填充记录默认值
   */
  fillEditColumnDefaultValue({ record, cols, getHeadFieldValue }) {
    cols.forEach(n => {
      if (n.DEFAULT_VALUE != null && n.DEFAULT_VALUE !== '') {
        let v = getParseValue(n.DEFAULT_VALUE, this.props.login.user, getHeadFieldValue);
        v = this.getControlValue({ controlType: n.CONTROL_TYPE, data: { enumName: n.ENUM }, value: v });
        setDataFieldValue(record, n.FIELD_NAME, v);
      };
    });
  }


  /*
      根据编辑页列信息初始化列配置信息
   */
  initColumnConfigByEditCols({ editColumns, editPanels, customHidCols, customCols, columns, panels, customCfg, onChange, onBlur, getFieldValue, onDropDownFilter, onSelect, isBatchEdit }) {
    if (editColumns && editColumns.length) {
      let isNeedSort = false;
      editColumns.forEach(n1 => {
        n1.DB_NUM = n1.DB_NUM !== undefined && n1.DB_NUM !== null ? n1.DB_NUM : n1.NUM;
        n1.DB_LABEL = n1.DB_LABEL !== undefined && n1.DB_LABEL !== null ? n1.DB_LABEL : n1.LABEL;
        if (n1.LABEL !== n1.DB_LABEL) {
          n1.LABEL = n1.DB_LABEL;
        }
        if (n1.NUM !== n1.DB_NUM) {
          n1.NUM = n1.DB_NUM;
          isNeedSort = true;
        }
        const temps = customCols ? customCols.filter(t => t.EDIT_COLUMN_ID === n1.ID) : null;//自定义列信息 如显示名称、顺序
        if (temps && temps.length) {
          const col = temps[0];
          if (col.LABEL) {
            n1.LABEL = col.LABEL;
          }
          if (col.NUM !== undefined && col.NUM !== null) {
            n1.NUM = col.NUM;
            isNeedSort = true;
          }
        }
      });
      if (isNeedSort) {
        editColumns.sort((x, y) => x.NUM > y.NUM ? 1 : -1);
      }
      const tmpColumns = [];
      editColumns.forEach(col => {
        if (!col.IS_DEFAULT || isBatchEdit && (!col.IS_CAN_BATCH_EDIT || !col.EDITABLE)) {
          return;
        }
        const isSysParam = col.FIELD_NAME ? col.FIELD_NAME.indexOf('Nav_SysParams') > -1 : false;
        let isHidden = false;
        if (customHidCols) {
          isHidden = customHidCols.filter(t => t.EDIT_COLUMN_ID === col.ID).length > 0;
        }
        if (customCfg && !isSysParam) {
          customCfg.push({//填充自定义
            ID: col.ID,
            EDIT_COLUMN_ID: col.ID,
            title: col.LABEL,
            isCheck: !isHidden,
            isRequire: col.REQUIRED,
            num: col.NUM,
            dbTitle: col.DB_LABEL,
            dbNum: col.DB_NUM,
          });
        }
        if (isHidden) {
          return;
        }
        const colConfig = this.getControlConfigByEditCol({ col: col });
        tmpColumns.push(colConfig);
      });

      if (tmpColumns && tmpColumns.length) {
        tmpColumns.forEach(t => {
          let isGet = false;
          if (editPanels && editPanels.length && panels) {
            const temps = editPanels.filter(t1 => t1.ID === t.column.PAGE_EDIT_PANEL_ID);
            if (temps != null && temps.length) {
              isGet = true;
              const temps2 = panels.filter(t2 => t2.id === temps[0].ID);
              if (!temps2 || !temps2.length) {
                panels.push({
                  panel: temps[0],
                  id: temps[0].ID,
                  columns: [t],
                  num: temps[0].NUM,
                  editColumns: [t.column],
                });
              }
              else {
                temps2[0].columns.push(t);
                temps2[0].editColumns.push(t.column);
              }
            }
          }
          if (!isGet) {
            columns.push(t);
          }
        });
      }
    }
  }



  getCustomCols(cuCfg, field, value) {
    if (field === 'title') {
      if (cuCfg.dbTitle !== value) {
        return { EDIT_COLUMN_ID: cuCfg.ID, LABEL: value };
      }
    }
    else if (field === 'num') {
      if (cuCfg.dbNum !== value) {
        return { EDIT_COLUMN_ID: cuCfg.ID, NUM: value };
      }
    }
    return null;
  }

  saveCustomConfig = (dbCustomCfg, pageEditId) => { // 保存配置字段
    const hiddenTmps = [];
    const colTmps = [];
    if (dbCustomCfg && dbCustomCfg.length) {
      dbCustomCfg.forEach((n, i) => {
        if (!n.isCheck) {
          hiddenTmps.push(n.ID);
        }
        const titleJson = this.getCustomCols(n, 'title', n.title);
        const numJson = this.getCustomCols(n, 'num', n.num);
        if (titleJson || numJson) {
          let json = titleJson ? titleJson : {};
          if (numJson) {
            json = { ...json, ...numJson };
          }
          colTmps.push(json)
        }
      });
    }

    const json = {
      UserId: this.props.login.userId,
      OrgId: this.props.login.OrgId,
      PageEditId: pageEditId,
      HiddenEditColumnIds: hiddenTmps,
      EditColumns: colTmps,
    };
    this.props.dispatch({
      type: 'editPage/saveUserCustomConfig',
      payload: json,
      onComplete: (ret) => {
        if (ret) {
          message.success('执行成功');
        }
      }
    });
  }

  clearCustomConfig(pageEditId, editCode, editColumns, editPanels) { //重置自定义信息
    const columns = [], panels = [], customCfg = [];
    this.initColumnConfigByEditCols({ editColumns, editPanels, columns, panels, customCfg });
    this.setEditConfig({ editCode, editConfig: { columns: columns, customCfg, panels } });
    const json = {
      UserId: this.props.login.userId,
      OrgId: this.props.login.OrgId,
      PageEditId: pageEditId,
    };
    this.props.dispatch({
      type: 'editPage/saveUserCustomConfig',
      payload: json,
      onComplete: (ret) => {
        if (ret) {
          message.success('执行成功');
        }
      }
    });
  }


  handleCustomFieldChange(dbCustomCfg, field, value, cuCfg, editCode, editColumns, editPanels) {//自定义字段发生改变
    const isHidden = field === 'check';
    const tmp = [...dbCustomCfg];
    const columns = [], panels = [], customCfg = [], customHidCols = [], customCols = [];
    tmp.forEach((n1, i1) => {
      if (n1.ID !== cuCfg.ID) {
        if (!n1.isCheck) {
          customHidCols.push(n1);
        }
      }
      const titleJson = this.getCustomCols(n1, 'title', isHidden || n1.ID !== cuCfg.ID || n1.ID === cuCfg.ID && field !== 'title' ? n1.title : value);
      const numJson = this.getCustomCols(n1, 'num', isHidden || field !== 'num' || value[n1.ID] === undefined ? n1.num : value[n1.ID]);
      if (titleJson || numJson) {
        let json = titleJson ? titleJson : {};
        if (numJson) {
          json = { ...json, ...numJson };
        }
        customCols.push(json)
      }
    });
    if (isHidden && !value) {
      customHidCols.push(cuCfg);
    }
    this.initColumnConfigByEditCols({ editColumns, editPanels, customHidCols, customCols, columns, panels, customCfg });
    this.setEditConfig({ editCode, editConfig: { columns: columns, customCfg, panels } });
  }

  getTreeConfigByTreePage(ret) {
    const isShow = (this.props.data && this.props.data.isShow) ? this.props.data.isShow : false;
    const isPermit = (this.props.data && this.props.data.isPermit) ? this.props.data.isPermit : false;
    const treeConfig = {
      formCode: ret.Nav_Form.CODE,
      formId: ret.Nav_Form.ID,
      api: ret.Nav_PageTree.QUERY_API_URL,
      deleteApi: ret.Nav_PageTree.BATCH_DEL_API_URL,
      relationField: ret.Nav_PageTree.RELATION_FIELD,
      relationId: this.props.data ? this.props.data.id : null,
      sort: ret.Nav_PageTree.SORT,
      order: ret.Nav_PageTree.ORDER,
      titleColumns: [],
      btns: [],
    };
    if (ret.Nav_Columns && ret.Nav_Columns.length) {
      ret.Nav_Columns.forEach(t => {
        treeConfig.titleColumns.push({
          field: t.FIELD_NAME,
        });
      });
    }
    if (ret.Nav_Btns && ret.Nav_Btns.length) {
      ret.Nav_Btns.forEach(t => {
        if (t.ENABLE_STATUS === 1) return;//不启用
        treeConfig.btns.push({
          btnType: t.BTN_TYPE,
          id: t.ID,
          isRule: t.IS_RULE,
          disabled: isShow || isPermit,
          btn: t,
        });
      });
    }
    return treeConfig;
  }


  getFieldValue(field, thisRef) {
    if (thisRef) {
      return getDataFieldValue(thisRef.state.data, field);
    }
    return getDataFieldValue(this.state.data, field);
  };

  setFieldValue = (field, value, thisRef) => {
    if (thisRef) {
      thisRef.setFieldValueByBatch([{ field, value }]);
    }
    else {
      this.setFieldValueByBatch([{ field, value }]);
    }

  };


  setFieldValueByBatch(fieldValues, thisRef) {
    if (!fieldValues) return;
    if (!thisRef) {
      thisRef = this;
    }
    const headColumnConfig = thisRef.getEditConfig();
    const cols = headColumnConfig ? headColumnConfig.columns : [];
    const data = {};
    fieldValues.forEach((n, i) => {
      let value = n.value;
      let field = n.field;
      if (!field) return;
      let col = null;
      cols.forEach(item => {
        if (item.field === field) {
          n.col = col;
        }
      });
      if (headColumnConfig.panels && headColumnConfig.panels.length > 0) {
        headColumnConfig.panels.forEach(panel => {
          if (panel.columns && panel.columns.length > 0)
            panel.columns.forEach(col => {
              n.col = col;
            })
        })
      }
      if (col) {
        value = thisRef.getControlValue({ controlType: col.controlType, value, data: col.data });
        setDataFieldValue(data, field, value);
      }
      else {
        setDataFieldValue(data, field, value);
      }

      n.col = col;
    });
    thisRef.saveHeadRecord(data, () => {
      fieldValues.forEach((n, i) => {
        if (n.col && n.col.column) {
          thisRef.handleFieldChangeEvent(n.value, n.col.column);
        }
      });
    });
  };

  setFieldEditable(field, editable, thisRef, editCode) {
    if (!thisRef) {
      thisRef = this;
    }
    const headColumnConfig = thisRef.getEditConfig({ "editCode": editCode });
    const cols = headColumnConfig ? headColumnConfig.columns : [];
    cols.forEach(col => {
      if (col.field === field) {
        col.disabled = !editable;
      }
    });
    if (!editCode || editCode === 'head') {
      if (headColumnConfig.panels && headColumnConfig.panels.length > 0) {
        headColumnConfig.panels.forEach(panel => {
          if (panel.columns && panel.columns.length > 0)
            panel.columns.forEach(col => {
              if (col.field === field) {
                col.disabled = !editable;
              }
            })
        })
      }
      thisRef.setEditConfig({
        editConfig: headColumnConfig,
      });
    } else {
      thisRef.setEditConfig({
        editCode: editCode,
        editConfig: cols,
      });
    }

  };


  setFieldRequired(field, required, thisRef) {
    if (!thisRef) {
      thisRef = this;
    }
    const headColumnConfig = thisRef.getEditConfig();
    const cols = headColumnConfig ? headColumnConfig.columns : [];
    cols.forEach(col => {
      if (col.field === field) {
        col.isRequire = required;
      }
    });
    if (headColumnConfig.panels && headColumnConfig.panels.length > 0) {
      headColumnConfig.panels.forEach(panel => {
        if (panel.columns && panel.columns.length > 0)
          panel.columns.forEach(col => {
            if (col.field === field) {
              col.isRequire = required;
            }
          })
      })
    }
    thisRef.setEditConfig({
      editConfig: headColumnConfig,
    });
  };



  setFieldVisible = (field, visible, thisRef) => {
    if (thisRef) {
      thisRef.setFieldVisibleByBatch([{ field, visible }], thisRef);
    }
    else {
      this.setFieldVisibleByBatch([{ field, visible }]);
    }

  };

  setFieldVisibleByBatch = (list, thisRef) => {
    if (!list || list.length === 0) return;
    if (!thisRef) {
      thisRef = this;
    }
    const params = {};
    list.forEach(t => {
      params[t.field] = t.visible;
    });
    thisRef.setHeadFieldVisible(params);
  };

  getEditConfigByPage({ formCode, onComplete }) {
    const { dispatch, login, form } = this.props;
    const { OrgId: ORG_ID } = login;
    if (form != null) {
      form.resetFields();
    }
    const json = initFilter(ORG_ID, formCode, '', 0);
    dispatch({
      type: 'editPage/getEditPageConfigInfo',
      payload: json,
      onComplete: (ret) => {
        if (ret) {
          this.getEditUserCustomConfigInfo(ret, onComplete);
        }
      }
    })
  }

  getEditUserCustomConfigInfo = (ret, onComplete) => {
    const { login } = this.props;
    if (ret.Nav_PageEdit && ret.Nav_PageEdit.Nav_PageEdit) {
      let json2 = initFilter(login.OrgId, ret.Nav_PageEdit.Nav_PageEdit.ID, "NUM", 0, 1, login.user.ID);
      this.props.dispatch({
        type: 'editPage/getUserCustomConfigInfo',
        payload: json2,
        onComplete: (ret2) => {
          ret.Nav_CustomHiddenEditCols = ret2 ? ret2.Nav_CustomHiddenEditCols : null;
          ret.Nav_CustomCols = ret2 ? ret2.Nav_CustomCols : null;
          this.doGetEditConfigByPage(ret, onComplete);
        }
      });
    }
    else {
      this.doGetEditConfigByPage(ret, onComplete);
    }
  };

  doGetEditConfigByPage = (ret, onComplete) => {
    let editData = {};
    let btnData = [], columns = [], customCfg = [], allColumns = [], navFields = [], allPanels = [], panels = [],
      activePanelIds = [], detailEditCodes = [], rowBtns = [], btns = [];
    const subTable = [];
    if (ret.Nav_PageEdit) {
      editData = ret.Nav_PageEdit.Nav_PageEdit;
      btnData = ret.Nav_PageEdit.Nav_Btns;
      allColumns = ret.Nav_PageEdit.Nav_Columns;
      allPanels = ret.Nav_PageEdit.Nav_EditPanels;
      if (allColumns && allColumns.length) {
        allColumns.forEach(t => {
          if (t.FIELD_NAME && t.FIELD_NAME.indexOf('.') > 0) {
            let pos = t.FIELD_NAME.lastIndexOf('.');
            if (pos >= 0) {
              let includeTable = t.FIELD_NAME.substring(0, pos);
              navFields.push(includeTable);
            }
          }
          if (t.CONTROL_TYPE == 24)//分页下拉多选
          {
            navFields.push(t.FIELD_NAME);
            if (t.INPUT_LABEL_FIELD && t.INPUT_LABEL_FIELD.indexOf('.') > 0) {
              let pos = t.INPUT_LABEL_FIELD.lastIndexOf('.');
              if (pos >= 0) {
                let includeTable = t.INPUT_LABEL_FIELD.substring(0, pos);
                navFields.push(t.FIELD_NAME + "." + includeTable);
              }
            }
          }
        });
      }
      // 针对横向树结构的复制，赋值
      const childsetfield = editData.CHILD_SET_FIELD;
      const parentcopyfield = editData.PARENT_COPY_FIELD;
      if (childsetfield && parentcopyfield && childsetfield.split(',').length === parentcopyfield.split(',').length) {
        this.getparentinfo = true;
        const childsetfields = childsetfield.split(',');
        const parentcopyfields = parentcopyfield.split(',');
        for (const childset of childsetfields) {
          if (childset.indexOf('.') > 0) {
            let pos = childset.lastIndexOf('.');
            if (pos >= 0) {
              let includeTable = childset.substring(0, pos);
              navFields.push(includeTable);
            }
          }
        }
        for (const parentcopy of parentcopyfields) {
          if (parentcopy.indexOf('.') > 0) {
            let pos = parentcopy.lastIndexOf('.');
            if (pos >= 0) {
              let includeTable = parentcopy.substring(0, pos);
              navFields.push(includeTable);
            }
          }
        }
      }
    }
    if (ret.Nav_SubPageEdits && ret.Nav_SubPageEdits.length) {
      ret.Nav_SubPageEdits.forEach(t => {
        const tmpCols = t.Nav_Columns;
        t.Nav_PageEdit.editColumns = tmpCols;
        t.Nav_PageEdit.btns = t.Nav_Btns;
        t.Nav_PageEdit.isDetail = t.Nav_ParentPageDetailModel === null || t.Nav_ParentPageDetailModel === undefined;
        t.Nav_PageEdit.Nav_SubPageEdits = t.Nav_SubPageEdits;
        t.Nav_PageEdit.Nav_ParentPageDetailModel = t.Nav_ParentPageDetailModel;
        subTable.push(t.Nav_PageEdit);
        navFields.push(t.NavFields);
        if (t.Nav_PageEdit.isDetail) {
          detailEditCodes.push(t.Nav_PageEdit.CODE);
        }

        if (tmpCols && tmpCols.length) {
          tmpCols.forEach(t1 => {
            if (t1.FIELD_NAME && t1.FIELD_NAME.indexOf('.') > 0) {
              let pos = t1.FIELD_NAME.lastIndexOf('.');
              if (pos >= 0) {
                let includeTable = t1.FIELD_NAME.substring(0, pos);
                navFields.push(t.NavFields + "." + includeTable);
              }
            }
          });
        }
      });
    }


    if (btnData && btnData.length) {
      const isShow = (this.props.data && this.props.data.isShow) ? this.props.data.isShow : false;
      const isPermit = (this.props.data && this.props.data.isPermit) ? this.props.data.isPermit : false;
      btnData.forEach(t => {
        if (t.ENABLE_STATUS === 1) return;
        //为添加权限预留
        if (!this.props.data?.homeReload) {
          if (t.IS_RULE && !permissionUtils(this.props.login).checkBtn(ret.Nav_Form.ID, t.ID)) return;
        }

        // if(t.BTN_FUN_TYPE===1){
        //   this.getBtnConfigByPageBtn(t,rowBtns);
        // }
        // else{
        //   this.getBtnConfigByPageBtn(t,btns,true);
        // }
        const btnConfig = this.getBtnConfigByPageBtn(t, btns, true);
        if (btnConfig) {
          if (btnConfig.btnType === 1) {
            btnConfig.isHidden = isShow || isPermit;
          }
        }
      });
    }

    this.initColumnConfigByEditCols({ editColumns: allColumns, editPanels: allPanels, customHidCols: ret.Nav_CustomHiddenEditCols, customCols: ret.Nav_CustomCols, columns, panels, customCfg });

    if (panels && panels.length) {
      panels.forEach(p => {
        if (p.panel && p.panel.IS_DEFAULT_EXPAND) {
          activePanelIds.push(p.panel.ID);
        }
      });
    }
    this.setState({
      jsFile: ret.Nav_Form.JS_FILES,
      activePanelIds,
      formData: ret.Nav_Form,
      btnLoading: false,
    }, () => {
      this.setEditConfig({
        editConfig: {
          columns: columns,
          id: editData.ID,
          saveApi: editData.API_URL,
          batchSaveApi: editData.BATCH_UPDATE_API,
          customCfg,
          getApi: editData.QUERY_API_URL,
          batchGetApi: editData.BATCH_QUERY_API,
          editCode: editData.CODE,
          editPage: editData, btns, formData: ret.Nav_Form, detailEditCodes, rowBtns,
          formId: ret.Nav_Form.ID, formCode: ret.Nav_Form.CODE,
          authOrgCodes: ret.Nav_Form.AUTH_ORG_CODES,
          editColumns: allColumns, editPanels: allPanels, panels, allNavFields: navFields
        }, onComplete: () => {
          let i = 0;
          if (subTable && subTable.length) {
            subTable.forEach(t => {
              this.getEditTableConfigByPage({
                editPage: t, onComplete: () => {
                  i++;
                  if (i === subTable.length) {
                    this.onGetEntityData(allColumns, navFields);
                  }
                }
              });
            });
          }
          else {
            this.onGetEntityData(allColumns, navFields);
          }
          if (typeof onComplete === 'function') {
            onComplete();
          }
        }
      });
    });
  };


  getEditTableConfigByPage({ editPage, onComplete }) {
    let json2 = initFilter(this.props.login.OrgId, editPage.ID, "NUM", 0, 1, this.props.login.userId);
    this.props.dispatch({
      type: 'editPage/getUserCustomConfigInfo',
      payload: json2,
      onComplete: (ret2) => {
        this.doGetEditTableConfigByPage(editPage, ret2 ? ret2.Nav_CustomHiddenEditCols : null, ret2 ? ret2.Nav_CustomCols : null, onComplete);
      }
    })
  }

  getBtnConfigByPageBtn = (btn, btnConfigs, isHeadBtn, isDetailBtn) => {
    const btnConfig = {
      id: btn.ID,
      code: btn.CODE,
      label: btn.LABEL,
      btnType: btn.BTN_TYPE,
      isRule: btn.IS_RULE,
      clickEventFunName: btn.CLICK_EVENT,
      css: btn.CSS,
      icon: btn.ICON,
      formCode: btn.FORM_CODE,
      customParams: btn.CUSTOM_PARAMS,
      checkSelected: btn.SELECT_SHOW,
      isConfirm: btn.IS_COMFIRM,
      api: btn.API_URL,
      num: btn.NUM,
      saveClearType: btn.SAVE_CLEAR_TYPE,
      saveCloseType: btn.SAVE_CLOSE_TYPE,
      saveField: btn.INPUT_SAVE_FIELD,
      navField: btn.INPUT_NAV_FIELD,
      btn,
      isAddLog: true,
      isHeadBtn,
      isDetailBtn,
      enableStatus: btn.ENABLE_STATUS
    };
    btnConfigs.push(btnConfig);
    return btnConfig;
  };

  doGetEditTableConfigByPage = (editPage, customHidCols, customCols, onComplete) => {
    const isShow = (this.props.data && this.props.data.isShow) ? this.props.data.isShow : false;
    const isPermit = (this.props.data && this.props.data.isPermit) ? this.props.data.isPermit : false;
    const formId = this.state.formData.ID;
    const columns = [], customCfg = [], btns = [], rowBtns = [], rightBtns = [];
    let checked = editPage.SHOW_CHECK;
    this.initColumnConfigByEditCols({ editColumns: editPage.editColumns, customHidCols, customCols, columns, customCfg });
    // let isAddBtnVisible = false;
    // let isDeleteVisible = false;
    // let isRowDeleteVisible = false;
    if (editPage.btns && editPage.btns.length) {
      editPage.btns.forEach(t => {
        if (t.ENABLE_STATUS === 1) return;
        //为添加权限预留
        if (!this.props.data?.homeReload) {
          if (t.IS_RULE && !permissionUtils(this.props.login).checkBtn(formId, t.ID)) return;
        }
        let btnConfig = null;
        if (t.BTN_FUN_TYPE === 1) {
          btnConfig = this.getBtnConfigByPageBtn(t, rowBtns, false, true);
        }
        else {
          btnConfig = this.getBtnConfigByPageBtn(t, btns, false, true);
        }
        if (btnConfig) {
          if (btnConfig.btnType === 1) {
            btnConfig.isHidden = isShow || isPermit;
          }
          else if (btnConfig.btnType === 3) {
            btnConfig.disabled = isShow || isPermit && !editPage.IS_PERMIT_ADD_ROW || editPage.IS_SUB_ADD_BTN_DISABLED;
          }
          else if (btnConfig.btnType === 4) {
            if (t.BTN_FUN_TYPE === 0) {
              checked = true;
            }
            btnConfig.disabled = isShow || isPermit && !editPage.IS_PERMIT_DEL_ROW || editPage.IS_SUB_DELETE_BTN_DISABLED;
          }
        }
      });
    }
    rightBtns.push({
      id: 'customBtn' + editPage.ID,
      btnType: 7,
      code: 'customConfigBtn',
    });

    var isShowRowNO = true
    if (editPage.IS_SHOWROWNO != undefined && editPage.IS_SHOWROWNO != null && editPage.IS_SHOWROWNO == false) {
      isShowRowNO = false
    }
    const editConfig = {
      id: editPage.ID,
      editColumns: editPage.editColumns,
      label: editPage.LABEL_NAME,
      editPage,
      formId: this.state.formData.ID,
      authOrgCodes: this.state.formData.AUTH_ORG_CODES,
      formCode: this.state.formData.CODE,
      formData: this.state.formData,
      editCode: editPage.CODE,
      columns: columns,
      sortField: editPage.SORT_FIELDS,
      sortOrder: editPage.SORT_ORDERS,
      isRowNo: isShowRowNO,
      width: editPage.WIDTH,
      height: editPage.HEIGHT,
      checked,
      isShow,
      dataNav: editPage.NAV_PROPERTY,
      isDetailRequired: editPage.IS_DETAIL_REQUIRED,
      isPermit,
      parentFieldName: editPage.RELATION_FIELD,
      getHeadFieldValue: (field) => { return this.getFieldValue(field); },
      customCfg,
      entityOrgType: editPage.EDIT_PAGE_ENTITY_ORG_TYPE,
      btns,
      rowBtns,
      rightBtns,
      childrenEditCodes: [],
      hasChildren: editPage.Nav_SubPageEdits && editPage.Nav_SubPageEdits.length > 0,
      parentEditCode: (editPage.Nav_ParentPageDetailModel && editPage.Nav_ParentPageDetailModel.Nav_PageEdit ?
        editPage.Nav_ParentPageDetailModel.Nav_PageEdit.CODE : null),
    };
    if (editPage.Nav_SubPageEdits && editPage.Nav_SubPageEdits.length) {
      editPage.Nav_SubPageEdits.forEach(t1 => {
        if (t1.Nav_PageEdit) {
          editConfig.childrenEditCodes.push(t1.Nav_PageEdit.CODE);
        }
      });
    }
    setTimeout(() => {
      this.setEditConfig({ editCode: editConfig.editCode, editConfig, onComplete });
    }, 500);
  };


  onCollapseChange(e) {
    this.setState({ activePanelIds: e });
  }

  // 渲染表头区域
  onRenderPanel() {
    const ediTableConfig = this.getEditConfig();
    if (ediTableConfig && ediTableConfig.panels && ediTableConfig.panels.length) {
      return (
        <Collapse
          activeKey={this.state.activePanelIds}
          onChange={(e) => this.onCollapseChange(e)}
          style={{ marginBottom: 15 }}
        >
          {
            ediTableConfig.panels.map(t => {
              return <Panel header={t.panel.LABEL} key={t.id}>
                {
                  this.createControls(t.columns, this.state.data)
                }
              </Panel>
            })
          }
        </Collapse>
      )
    }
  }

  // 在获取完编辑配置信息后，根据配置获取实体数据
  onGetEntityData(allColumns, navFields) {
    let { id: ID, copySrcId, login, data } = this.props
    if (!copySrcId) {
      copySrcId = this.copySrcId;
      this.copySrcId = null;
    }
    if (!ID && !data.isInoreId) {
      ID = data.id;
    }
    if (copySrcId) {
      this.billStatus = 2;
      const json = initFilter(login.OrgId);
      extendRule(json, 'ID', 1, copySrcId);
      this.getCopyEntityData(json, navFields, allColumns);
    }
    else if (ID && !this.props.isAddH) {
      this.billStatus = 1;
      const json = initFilter(login.OrgId);
      extendRule(json, 'ID', 1, ID);
      this.getEntityData(json, navFields);
    }
    // 分页下拉组件快捷编辑表单添加的过滤条件，通过此过滤条件，达到表单编辑的效果，而不是新增效果
    else if (data.editFormFilter && data.editFormFilterValue) {
      this.billStatus = 1;
      const json = initFilter(login.OrgId);
      extendRule(json, data.editFormFilter, 1, data.editFormFilterValue);
      this.getEntityData(json, navFields);
    }
    else {
      this.billStatus = 0;
      if (ID && this.getparentinfo && this.props.isAddH) {
        const json = initFilter(login.OrgId);
        extendRule(json, 'ID', 1, ID);
        this.getNewCopyEntityData(json, navFields, allColumns);
        return;
      }
      this.getNewEntityData(allColumns);
    }
  }

  getNewEntityData = (allColumns, copydatas = {}) => {
    let newData = {};
    if (this.props.data && this.props.data.newData) {
      newData = this.props.data.newData;
    }
    //填充默认值
    const nArr = this.getDefaultValue(allColumns);
    const editConfig = this.getEditConfig();
    let newDataObj = {
      ID: guid(),
      ORG_ID: this.props.login.OrgId,
      FORM_ID: this.state.formData.ID,
      ENTITY_ORG_TPYE: editConfig.editPage ? editConfig.editPage.EDIT_PAGE_ENTITY_ORG_TYPE : 0,
      ...nArr,
      PARENT_ID: this.props.parentId,
      ...this.state.initData,
      ...newData,
      ...copydatas
    };
    if (this.props.data.TreeSelected && this.props.data.TreeSelected.length > 0 && this.props.data.TreeSelectId) {
      newDataObj[this.props.data.TreeSelectId] = this.props.data.TreeSelected[0];
    }
    if (this.props.customParams) {
      Object.keys(this.props.customParams).forEach((n) => {
        newDataObj[n] = this.props.customParams[n];
      });
    }
    this.setState({
      data: newDataObj,
      oldEditData: null,
    }, () => {
      if (editConfig.editPage && editConfig.editPage.CODE_FIELD_NAME) {
        this.getCodeRule(editConfig.editPage.CODE_RULE_TYPE, editConfig.editPage.CODE_FIELD_NAME);
      }
      if (allColumns && allColumns.length) {
        allColumns.forEach(t => {
          if (t.CONTROL_TYPE === 14) {
            this.getCodeRule(t.CODE_RULE_TYPE, t.FIELD_NAME);
          }
        });
      }
      this.handleBeforeEditEvent(true, false, null);
    });
  };

  getCopyEntityData = (json, navFields, allColumns) => {
    const editConfig = this.getEditConfig();
    if (!editConfig || !editConfig.editPage || !editConfig.editPage.QUERY_API_URL) return;
    let type = 'app/getDataByPost';
    const tmp = [...new Set(navFields)];
    tmp.forEach((n, i) => {
      extendInclude(json, n);
    });
    let newData = {};
    if (this.props.data && this.props.data.newData) {
      newData = this.props.data.newData;
    }

    const getCopyEntity = (columns, entity) => {
      const copyEntity = {};
      const copyFields = [];
      const copyStatics = {
        PARENT_ID: false,
        IS_LEAF: false,
        ORG_ID: false,
      };
      columns.forEach((n, i) => {
        if (n.CONTROL_TYPE === 9) {
          if (n.IS_COPY) {
            if (n.FIELD_NAME) {
              const a = n.FIELD_NAME.split('.');
              if (a && a.length) {
                copyFields.push(a[0]);
              }
            }
            if (n.INPUT_ID_FIELD) {
              copyFields.push(n.INPUT_ID_FIELD);
            }
          }
        }
        else {
          if (n.IS_COPY) {
            if (n.FIELD_NAME && n.FIELD_NAME.indexOf('.') === -1) {
              copyFields.push(n.FIELD_NAME);
            }
          }
          const tmp = copyStatics[n.FIELD_NAME];
          if (tmp !== undefined) {
            copyStatics[n.FIELD_NAME] = true;
          }
        }
      });

      Object.keys(copyStatics).forEach((n) => {
        if (!copyStatics[n]) {
          copyFields.push(n);
        }
      });
      if (copyFields && copyFields.length) {
        copyFields.forEach((n, i) => {
          const v = getDataFieldValue(entity, n);
          if (v !== undefined && v !== null) {
            setDataFieldValue(copyEntity, n, v);
          }
        });
      }
      return copyEntity;
    };


    const nArr = this.getDefaultValue(allColumns);
    const { dispatch } = this.props;
    //debugger// extendIgnoreDataRule(json)
    dispatch({
      type: type,
      payload: json,
      url: editConfig.editPage.QUERY_API_URL,
      onComplete: (ret) => {
        if (ret) {
          let copyEntity = {
            ID: guid(),
            ORG_ID: this.props.login.OrgId,
            ...this.state.initData,
            ...newData,
            ...nArr,
          };
          if (allColumns) {
            const tmp = getCopyEntity(allColumns, ret);
            copyEntity = {
              ...copyEntity,
              ...tmp,
            }
          }
          const editConfig = this.getEditConfig();
          if (editConfig && editConfig.detailEditCodes && editConfig.detailEditCodes.length) {
            const doCopyDetail = (editCodes, tempData, parentData) => {
              if (editCodes && editCodes.length) {
                editCodes.forEach(t => {
                  const config = this.getEditConfig({ editCode: t });
                  if (!config) return;
                  const tmps = getDataFieldValue(tempData, config.dataNav);
                  const copyTmps = [];
                  if (tmps && tmps.length) {
                    tmps.forEach(n => {
                      let tmpCopyEntity = {
                        ID: guid,
                        ORG_ID: this.props.login.OrgId,
                      };
                      if (config.editColumns) {
                        this.fillEditColumnDefaultValue({ record: tmpCopyEntity, cols: config.editColumns });
                        const tmpCopy = getCopyEntity(config.editColumns, n);
                        tmpCopyEntity = {
                          ...tmpCopyEntity,
                          ...tmpCopy,
                        }
                      }
                      tmpCopyEntity[config.parentFieldName] = parentData.ID;
                      copyTmps.push(tmpCopyEntity);
                      if (config.childrenEditCodes && config.childrenEditCodes.length) {
                        doCopyDetail(config.childrenEditCodes, n, tmpCopyEntity);
                      }
                    });
                  }
                  this.getRowNoByData({ data: copyTmps, sortField: config.sortField, sortOrder: config.sortOrder, });
                  setDataFieldValue(copyEntity, config.dataNav, copyTmps);
                });
              }
            };

            doCopyDetail(editConfig.detailEditCodes, ret, copyEntity);
          }
          this.setState({
            data: copyEntity,
            oldEditData: null,
          }, () => {
            if (editConfig.editPage.CODE_FIELD_NAME) {
              this.getCodeRule(editConfig.editPage.CODE_RULE_TYPE, editConfig.editPage.CODE_FIELD_NAME);
            }
            if (allColumns && allColumns.length) {
              allColumns.forEach(t => {
                if (t.CONTROL_TYPE === 14) {
                  this.getCodeRule(t.CODE_RULE_TYPE, t.FIELD_NAME);
                }
              });
            }
            if (editConfig && editConfig.detailEditCodes && editConfig.detailEditCodes.length) {
              editConfig.detailEditCodes.forEach(t => {
                const config = this.getEditConfig({ editCode: t });
                const editCode = t;
                if (config.editColumns && config.editColumns.length) {
                  config.editColumns.forEach(t2 => {
                    if (t2.CONTROL_TYPE === 14) {
                      const table = this.getEditTableData({ editCode });
                      if (table && table.length) {
                        table.forEach(t1 => {
                          this.getCodeRule(t2.CODE_RULE_TYPE, t2.FIELD_NAME, t1.ID, editCode);
                        });
                      }
                    }
                  });
                }
              });
            }
            this.handleBeforeEditEvent(true, true, ret);
          });
        }
      }
    });
  };

  getNewCopyEntityData = (json, navFields, allColumns) => {
    const editConfig = this.getEditConfig();
    if (!editConfig || !editConfig.editPage || !editConfig.editPage.QUERY_API_URL) return;
    const tmp = [...new Set(navFields)];
    tmp.forEach((n, i) => {
      extendInclude(json, n);
    });
    const { dispatch } = this.props;
    //debugger// extendIgnoreDataRule(json)
    dispatch({
      type: 'app/getDataByPost',
      payload: json,
      url: editConfig.editPage.QUERY_API_URL,
      onComplete: (ret) => {
        if (ret) {
          const copydatas = {};
          const parentcopyfields = editConfig.editPage.PARENT_COPY_FIELD.split(',');
          const childsetfields = editConfig.editPage.CHILD_SET_FIELD.split(',');
          for (let i = 0; i < parentcopyfields.length; i++) {
            setDataFieldValue(copydatas, childsetfields[i], getDataFieldValue(ret, parentcopyfields[i]))
            // copydatas[childsetfields[i]] = getDataFieldValue(ret, parentcopyfields[i])
          }
          this.getNewEntityData(allColumns, copydatas);
        }
      }
    });
  }

  getEntityData = (json, navFields) => {
    const editConfig = this.getEditConfig();
    if (!editConfig || !editConfig.editPage || !editConfig.editPage.QUERY_API_URL) return;
    const tmp = [...new Set(navFields)];
    tmp.forEach((n, i) => {
      extendInclude(json, n);
    });
    const { dispatch } = this.props;
    if (this.props.homeLoad) {
      json["IgnoreDataRule"] = true;
    }
    //debugger
    // extendIgnoreDataRule(json)
    dispatch({
      type: 'app/getDataByPost',
      payload: json,
      url: editConfig.editPage.QUERY_API_URL,
      onComplete: (ret) => {
        if (ret) {
          const resetData = (editCodes, tempData) => {
            if (editCodes && editCodes.length) {
              editCodes.forEach(t => {
                const config = this.getEditConfig({ editCode: t });
                const tmps = getDataFieldValue(tempData, config.dataNav);
                if (tmps && tmps.length) {
                  this.getRowNoByData({ data: tmps, sortField: config.sortField, sortOrder: config.sortOrder, isRowNo: config.isRowNo });//wyw 是否显示序号
                  if (config.childrenEditCodes && config.childrenEditCodes.length) {
                    tmps.forEach(r => {
                      resetData(config.childrenEditCodes, r);
                    });
                  }
                }
              });
            }
          }
          const editConfig = this.getEditConfig();
          if (editConfig && editConfig.detailEditCodes && editConfig.detailEditCodes.length) {
            resetData(editConfig.detailEditCodes, ret);
          }

          this.setState({
            data: ret,
            oldEditData: JSON.parse(JSON.stringify(ret)),
          }, () => {
            this.handleBeforeEditEvent(false, false, null);
          });
        } else {
          this.handleBeforeEditEvent(false, false, null);
        }
      }
    });
  };

  checkRowDiff = (list, srcRow, destRow, columns) => {
    if (columns && columns.length) {
      let x = '';
      columns.forEach(t => {
        if (t.field === 'ROW_NO') return;
        const src = getDataFieldValue(srcRow, t.field);
        const dest = getDataFieldValue(destRow, t.field);
        if (src !== dest) {
          x += (t.label + ":新值【" + dest + "】旧值【" + src + "】,");
        }
      });
      if (x) {
        list.push('编辑行项记录，详情:' + x);
      }
    }
    else {
      let x = '';
      Object.keys(srcRow).forEach((n) => {
        if (n === 'Nav_SysParams') {

          return;
        }
        if (n.indexOf('.') !== -1) return;
        if (typeof (srcRow[n]) !== "object") {
          if (n === 'ROW_NO') return;
          const src = getDataFieldValue(srcRow, n);
          const dest = getDataFieldValue(destRow, n);
          if (src !== dest) {
            x += (n + ":新值【" + (dest === undefined || dest === null ? '' : dest) +
              "】旧值【" + (src === undefined || src === null ? '' : src) + "】,");
          }
        }
      });

      Object.keys(destRow).forEach((n) => {
        if (n === 'Nav_SysParams') {

          return;
        }
        if (n.indexOf('.') !== -1) return;
        if (typeof (destRow[n]) !== "object") {
          if (n === 'ROW_NO') return;
          const src = getDataFieldValue(srcRow, n);
          const dest = getDataFieldValue(destRow, n);
          if (src === undefined && src !== dest) {
            x += (n + ":新值【" + (dest === undefined || dest === null ? '' : dest) +
              "】旧值【" + (src === undefined || src === null ? '' : src) + "】,");
          }
        }
      });
      if (x) {
        list.push('编辑行项记录，详情:' + x);
      }
    }
  }
  checkTableDiff = (list, srcTable, destTable, columns) => {
    const getRowData = (r) => {
      if (columns && columns.length) {
        let x = '';
        columns.forEach(t => {
          const y = getDataFieldValue(r, t.field);
          x += (t.label + ":" + y + ",");
        });
        Object.keys(r).forEach((n) => {
          if (r[n] && r[n].length) {
            x += (n + ":" + JSON.stringify(r[n]));
          }
        });
        return x;
      }
      return JSON.stringify(r)
    };
    if (srcTable && srcTable.length) {
      srcTable.forEach(t => {
        const destRow = destTable?.filter(t1 => t1.ID === t.ID)[0];
        if (destRow) {
          this.checkRowDiff(list, t, destRow, columns);
        }
        else {
          list.push("删除行项,行项数据：" + getRowData(t))
        }
      });
    }
    if (destTable && destTable.length) {
      destTable.forEach(t => {
        const srcRow = srcTable?.filter(t1 => t1.ID === t.ID)[0];
        if (!srcRow) {
          list.push("新增行项,行项数据：" + getRowData(t))
        }
      });
    }
  }

  checkEditDataDiff = (srcData, destData) => {
    const list = [];
    const doDiffTable = (editCodes, tempSrcData, tempDestData) => {
      if (editCodes && editCodes.length) {
        editCodes.forEach(t => {
          const config = this.getEditConfig({ editCode: t });
          const srctmps = getDataFieldValue(tempSrcData, config.dataNav);
          const desttmps = getDataFieldValue(tempDestData, config.dataNav);
          this.checkTableDiff(list, srctmps, desttmps, config.columns);
          if (config.childrenEditCodes && config.childrenEditCodes.length) {
            if (srctmps && srctmps.length) {
              srctmps.forEach(t2 => {
                const destRow = desttmps.filter(t1 => t1.ID === t2.ID)[0];
                if (destRow) {
                  doDiffTable(config.childrenEditCodes, t2, destRow);
                  //    this.checkRowDiff(list,t,destRow,columns);
                }
              });
            }
          }

        });
      }
    }
    const editConfig = this.getEditConfig();
    this.checkRowDiff(list, srcData, destData, (editConfig ? editConfig.columns : null));
    if (editConfig && editConfig.detailEditCodes && editConfig.detailEditCodes.length) {
      doDiffTable(editConfig.detailEditCodes, srcData, destData);
    }
    return list.join(';');
  }

  getDefaultValue = (allColumns) => {
    let nArr = {};
    this.fillEditColumnDefaultValue({ record: nArr, cols: allColumns });
    if (this.props.setData) {
      this.props.setData.forEach((n) => {
        if (n.length === 2) {
          setDataFieldValue(nArr, n[0], n[1]);
        }
      })
    }
    return nArr;
  };

  saveUseCodeRule(codeRuleType, code) {
    if (!this.useCodeRules) {
      this.useCodeRules = {};
    }
    if (!this.useCodeRules[codeRuleType]) {
      this.useCodeRules[codeRuleType] = [];
    }
    this.useCodeRules[codeRuleType].push(code);
  }

  doGetCodeRule = (field, id, editCode, ret) => {
    if (id) {
      const table = this.getEditTableData({ editCode });
      if (table && table.length) {
        table.forEach(t => {
          if (t.ID === id) {
            setDataFieldValue(t, field, ret);
            this.saveRowRecord({ record: t, editCode });
          }
        });
      }
    }
    else {
      this.setFieldValue(field, ret);
    }
  }

  getCodeRule = (codeRuleType, field, id, editCode) => {
    if (!field) return;
    if (!codeRuleType) {
      if (this.props.login.OrgCode)
        this.doGetCodeRule(field, id, editCode, this.props.login.OrgCode);
      return;
    }
    const json = initFilter(this.props.login.OrgId);
    json.Count = 1;
    json.CodeType = codeRuleType;
    this.props.dispatch({
      type: 'app/genSystemCode',
      payload: json,
      onComplete: (ret) => {
        if (ret) {
          this.doGetCodeRule(field, id, editCode, ret);
          this.saveUseCodeRule(codeRuleType, ret);
        }
      }
    });
  };


  onAfterSave(params) {
    super.onAfterSave(params);
    const stateData = JSON.parse(JSON.stringify(this.state.data));
    const stateOldData = this.state.oldEditData ? JSON.parse(JSON.stringify(this.state.oldEditData)) : null;
    const { isSuccess, closeType, clearType, saveData: updateData } = params;
    if (isSuccess) {
      let { onSave, onCancel, formCode, data } = this.props;
      if (!onSave && data) {
        onSave = data.onSave;
      }
      if (!onCancel && data) {
        onCancel = data.onCancel;
      }
      this.useCodeRules = null;
      if (typeof onSave === 'function') {
        onSave(this.state.data);
      }
      if (closeType === 1 && this.billStatus === 1 ||//仅编辑时关闭
        closeType === 2 && this.billStatus !== 1 ||//仅新增时关闭
        closeType !== 1 && closeType !== 2 ||//全部都关闭
        closeType === undefined) {
        onCancel && onCancel();
      }
      else {
        if (!clearType || clearType === 0) {
          this.props.form.resetFields();
          this.onLoadData();//重新渲染
        }
      }
      //添加日志
      if (this.billStatus === 1) {
        this.addEditLog({
          formCode,
          ids: updateData.ID,
          codes: updateData.CODE,
          extData: ("编辑数据，详情：" + this.checkEditDataDiff(stateOldData, stateData))
        });
      }
      else {
        this.addAddLog({
          formCode,
          ids: updateData.ID,
          codes: updateData.CODE,
          extData: ("新增数据，详情：" + JSON.stringify(stateData))
        });
      }
    }

  }

  onSave(closeType, clearType, customParams) {
    this.save({
      closeType, clearType,
      onCheckBeforeSave: ({ saveData }) => {
        return this.handleBeforeSaveEvent(saveData);
      },
      onHandleRow: ({ editCode, record, srcRecord }) => {
        this.handleBeforeSaveHandleRecordEvent(editCode, record, srcRecord, customParams);
      }
    });
  };

  onEditBtnParam(params) {
    const { btnConfig, editConfig, record, editCode, parentId, parentRecord } = params ? params : {};
    const { btnType, clickEventFunName, btn, btnCustomParams } = btnConfig ? btnConfig : {};
    let { onCancel, } = this.props;
    if (btn.code === 'customConfigBtn') {
      return {
        content: <Dropdown overlay={this.getCustomFieldMange(editCode)} trigger={['click']} placement="bottomRight">
          <Button icon="bars" />
        </Dropdown>
      }
    }
    if (btnType === 0) {//自定义弹窗
      const clickEventFun = this.getDynJsFunc(clickEventFunName);
      if (typeof clickEventFun === 'function') {
        const btnParam = clickEventFun({
          record,
          parentRecord: editConfig,
          dispatch: this.props.dispatch,
          close: params.close,
          login: this.props.login,
          custom: this.props.custom,
          editCode: editConfig.editCode,
          stateData: this.state.data,
          onCancel: onCancel,
          btn,
          saveHeadRecord: (values, onComplete) => { return this.saveHeadRecord(values, onComplete); },
          saveRowRecord: (params) => { this.saveRowRecord(params); },
          getSelectedRecords: () => { return this.getEditSelectedRecord({ editCode, parentId }); },
          btnCustomParams: getCustomParams(btnCustomParams),
          pageTableCustomParams: getCustomParams(editConfig.customParams),
        });
        if (btnParam) {
          btnParam.disabled = btnParam.isReturn;
        }
        return btnParam;
      }
    }
    // else if(btnType === 5|| btnType=== 3 || btnType === 8|| btnType === 10){//编辑 新增 查看 复制新增
    //   const clickEventFun=this.getDynJsFunc(clickEventFunName);
    //   if(typeof clickEventFun==='function') {
    //     const btnParam = clickEventFun({
    //       record,
    //       parentRecord:tableConfig.parentRecord,
    //       dispatch: this.props.dispatch,
    //       login: this.props.login,
    //       custom:this.props.custom,
    //       pageCode: tableConfig.pageTable.CODE,
    //     });
    //     if (btnParam) {
    //       btnParam.disabled = btnParam.isReturn;
    //     }
    //     return btnParam;
    //   }
    // }
    else if (btnType === 4) {//删除
      const clickEventFun = this.getDynJsFunc(clickEventFunName);
      if (typeof clickEventFun === 'function') {
        const btnParam = clickEventFun({
          record,
          dispatch: this.props.dispatch,
          login: this.props.login,
          custom: this.props.custom,
          editCode: editConfig.editCode,
          stateData: this.state.data,
          onCancel: onCancel,
          saveHeadRecord: (values, onComplete) => { return this.saveHeadRecord(values, onComplete); },
          saveRowRecord: (params) => { this.saveRowRecord(params); },
        });
        if (btnParam) {
          btnParam.disabled = btnParam.isReturn;
        }
        return btnParam;
      }
    }
    else if (btnType === 6) {//自定义点击
      const { validateFieldsAndScroll } = this.props.form;
      return {
        click: (json) => {
          const clickEventFun = this.getDynJsFunc(clickEventFunName);
          if (typeof clickEventFun === 'function') {
            const btnParam = clickEventFun({
              record,
              parentRecord: parentRecord,
              dispatch: this.props.dispatch,
              loadData: () => { this.onLoadData(); },
              login: this.props.login,
              custom: this.props.custom,
              stateData: this.state.data,
              json,
              resetFields: () => this.props.form?.resetFields(),
              validateFieldsAndScroll,
              setState: (data) => {
                this.setState(data);
              },
              setStateFunc: (datas, func) => {
                this.setState({ data: datas }, func());
              },
              addOtherLog: (ids, json) => {
                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(json);
                this.addOtherLog({ formCode, formId, title, data, extData });
              },
              editCode: editConfig.editCode,
              getSelectedRecords: () => { return this.getEditSelectedRecord({ editCode, parentId }); },
              data: this.props.data,
              btnCustomParams: getCustomParams(btnCustomParams),
              pageTableCustomParams: getCustomParams(editConfig.customParams),
              onCancel: onCancel,
              saveHeadRecord: (values, onComplete) => { return this.saveHeadRecord(values, onComplete); },
              saveRowRecord: (params) => { this.saveRowRecord(params); },
            });
            return btnParam;
          }
        }
      };
    }
    else if (btnType === 7) {//自定义
      const clickEventFun = this.getDynJsFunc(clickEventFunName);
      const { validateFieldsAndScroll } = this.props.form;
      if (typeof clickEventFun === 'function') {
        const btnParam = clickEventFun({
          record,
          parentRecord: parentRecord,
          dispatch: this.props.dispatch,
          loadData: () => { this.onLoadData() },
          login: this.props.login,
          custom: this.props.custom,
          btn,
          validateFieldsAndScroll,
          setState: (data) => {
            this.setState(data);
          },
          getState: (key) => {
            return this.state[key];
          },
          addOtherLog: (ids, json) => {
            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(json);
            this.addOtherLog({ formCode, formId, title, data, extData });
          },
          editCode: editConfig.editCode,
          formId: (editConfig.formId ? editConfig.formId : (editConfig.formData ? editConfig.formData.ID : this.props.formId)),
          formCode: editConfig.formCode ? editConfig.formCode : (editConfig.formData ? editConfig.formData.CODE : this.props.formCode),
          getSelectedRecords: () => { return this.getEditSelectedRecord({ editCode, parentId }); },
          data: this.props.data,
          stateData: this.state.data,
          btnCustomParams: getCustomParams(btnCustomParams),
          pageTableCustomParams: getCustomParams(editConfig.customParams),
          onCancel: onCancel,
          saveHeadRecord: (values, onComplete) => { return this.saveHeadRecord(values, onComplete); },
          saveRowRecord: (params) => { this.saveRowRecord(params); },
        });
        if (btnParam) {
          btnParam.disabled = btnParam.isReturn;
        }
        return btnParam;
      }
    }
  }


  onRenderHeadControls(code, isTree) {
    const headColumnConfig = this.getEditConfig();
    const columns = headColumnConfig ? headColumnConfig.columns : [];
    const tempCols = [];
    if (columns && columns.length) {
      columns.forEach(t => {
        if (code && t.code === code || !code & !t.code) {
          tempCols.push(t);
        }
        if (isTree) t.span = { sm: 24, md: 12 }
      });
    }
    return this.createControls(tempCols, this.state.data)
  }

  handleRenderHeadControlEvent = (record, colInfo) => {
    const func = this.getDynJsFunc('handleRenderHeadControl');
    if (typeof func === 'function') {
      const editConfig = this.getEditConfig();
      return func({
        record,
        colConfig: colInfo,
        setRowFieldVisible: this.setRowFieldVisible,
        setRowFieldLabel: this.setRowFieldLabel,
        setRowFieldDisable: this.setRowFieldDisable,
        setRowFieldPops: this.setRowFieldPops,
        resetFields: () => this.props.form?.resetFields(),
        getFieldValue: (field) => { return this.getFieldValue(field, this); },
        setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
        setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this); },
        setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this); },
        pageCode: editConfig.editPage.CODE,
        setFieldVisible: (field, visible) => { this.setFieldVisible(field, visible, this) },
        setFieldVisibleByBatch: (list) => { this.setFieldVisibleByBatch(list, this); },
        login: this.props.login,
        custom: this.props.custom,
        dispatch: this.props.dispatch,
        setFieldRequired: (field, required) => { this.setFieldRequired(field, required, this); },
        updateSubTableData: ({ pageCode, data, isAppend }) => { this.setEditTableData({ editCode: pageCode, data, isAppend }) },
        getSubTableData: ({ pageCode }) => { return this.getEditTableData({ editCode: pageCode }) },
      });
      this.props.form?.resetFields();
    }
    return '';
  };

  handleRenderRowControlEvent = (record, colInfo) => {
    const func = this.getDynJsFunc('handleRenderRowControl');
    if (typeof func === 'function') {
      const editConfig = this.getEditConfig();
      return func({
        record,
        colConfig: colInfo,
        setRowFieldVisible: this.setRowFieldVisible,
        setRowFieldLabel: this.setRowFieldLabel,
        setRowFieldDisable: this.setRowFieldDisable,
        setRowFieldPops: this.setRowFieldPops,
        resetFields: () => this.props.form?.resetFields(),
        getFieldValue: (field) => { return this.getFieldValue(field, this); },
        setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
        setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this); },
        setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this); },
        pageCode: editConfig.editPage.CODE,
        setFieldVisible: (field, visible) => { this.setFieldVisible(field, visible, this) },
        setFieldVisibleByBatch: (list) => { this.setFieldVisibleByBatch(list, this); },
        login: this.props.login,
        custom: this.props.custom,
        dispatch: this.props.dispatch,
        stateData: this.state.data,
        saveRowRecord: (r) => {
          this.saveRowRecord({ record: r, editCode: editConfig.editPage.CODE })
        },
        setStateData: (val) => { this.setStateData(val) },
        setFieldRequired: (field, required) => { this.setFieldRequired(field, required, this); },
        updateSubTableData: ({ pageCode, data, isAppend }) => { this.setEditTableData({ editCode: pageCode, data, isAppend }) },
        getSubTableData: ({ pageCode }) => { return this.getEditTableData({ editCode: pageCode }) },
      });

    }
    return '';
  };


  handleFieldChangeEvent = (value, colInfo) => {
    const func = this.getDynJsFunc('onChange');
    if (typeof func === 'function') {
      const editConfig = this.getEditConfig();
      func({
        value,
        colInfo,
        setRowFieldVisible: this.setRowFieldVisible,
        setRowFieldLabel: this.setRowFieldLabel,
        setRowFieldDisable: this.setRowFieldDisable,
        setRowFieldPops: this.setRowFieldPops,
        resetFields: () => this.props.form?.resetFields(),
        getFieldValue: (field) => { return this.getFieldValue(field, this); },
        setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
        setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this); },
        setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this); },
        pageCode: editConfig.editPage.CODE,
        stateData: this.state.data,
        setFieldVisible: (field, visible) => { this.setFieldVisible(field, visible, this) },
        setFieldVisibleByBatch: (list) => { this.setFieldVisibleByBatch(list, this); },
        setState: (data, callback) => {
          this.setState({ data: data }, callback);
        },
        login: this.props.login,
        custom: this.props.custom,
        dispatch: this.props.dispatch,
        setFieldRequired: (field, required) => { this.setFieldRequired(field, required, this); },
        updateSubTableData: ({ pageCode, data, isAppend }) => { this.setEditTableData({ editCode: pageCode, data, isAppend }) },
        getSubTableData: ({ pageCode }) => { return this.getEditTableData({ editCode: pageCode }) },
      });
      this.props.form?.resetFields();
    }
  };

  handleBeforeEditEvent = (isNew, isCopy, copySrcData) => {
    const func = this.getDynJsFunc('onBeforeEdit');
    const editConfig = this.getEditConfig();
    if (typeof func === 'function') {
      func({
        isNew,
        isCopy,
        copySrcId: this.copySrcId ? this.copySrcId : this.props.copySrcId,
        copySrcData: copySrcData,
        setRowFieldVisible: this.setRowFieldVisible,
        setRowFieldLabel: this.setRowFieldLabel,
        setRowFieldDisable: this.setRowFieldDisable,
        setRowFieldPops: this.setRowFieldPops,
        getFieldValue: (field) => { return this.getFieldValue(field, this); },
        setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
        setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this) },
        setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this); },
        pageCode: editConfig.editPage.CODE,
        setFieldVisible: (field, visible) => { this.setFieldVisible(field, visible, this) },
        setFieldVisibleByBatch: (list) => { this.setFieldVisibleByBatch(list, this); },
        setRowFieldVisible: this.setRowFieldVisible,
        login: this.props.login,
        app: this.props.app,
        custom: this.props.custom,
        data: this.props.data,
        stateData: this.state.data,
        dispatch: this.props.dispatch,
        tableKey: this.props.data.tableKey,
        editConfig: editConfig,
        setEditConfig: (editConfig) => { this.setHeadEditConfig({ editConfig }) },
        setMenuName: (editConfig, fieldName, enumName) => { this.setMenuName(editConfig, fieldName, enumName) },
        updateSubTableData: ({ pageCode, data, isAppend }) => { this.setEditTableData({ editCode: pageCode, data, isAppend }) },
        getSubTableData: ({ pageCode }) => { return this.getEditTableData({ editCode: pageCode }) },
        saveUseCodeRule: (codeRuleType, code) => { this.saveUseCodeRule(codeRuleType, code); },
        setFieldRequired: (field, required) => { this.setFieldRequired(field, required, this); },
      });
    }
    this.onBeforeEdit({
      isNew,
      isCopy,
      copySrcId: this.copySrcId ? this.copySrcId : this.props.copySrcId,
      copySrcData,
      getFieldValue: (field) => { return this.getFieldValue(field, this); },
      setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
      setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this) },
      setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this); },
      setRowFieldLabel: this.setRowFieldLabel,
      pageCode: editConfig.editPage.CODE,
      setFieldVisible: (field, visible) => { this.setFieldVisible(field, visible, this) },
      setFieldVisibleByBatch: (list) => { this.setFieldVisibleByBatch(list, this); },
      login: this.props.login,
      app: this.props.app,
      custom: this.props.custom,
      data: this.props.data,
      stateData: this.state.data,
      dispatch: this.props.dispatch,
      tableKey: this.props.data.tableKey,
      editConfig: editConfig,
      setEditConfig: (editConfig) => { this.setHeadEditConfig({ editConfig }) },
      setMenuName: (editConfig, fieldName, enumName) => { this.setMenuName(editConfig, fieldName, enumName) },
      updateSubTableData: ({ pageCode, data, isAppend }) => { this.setEditTableData({ editCode: pageCode, data, isAppend }) },
      getSubTableData: ({ pageCode }) => { return this.getEditTableData({ editCode: pageCode }) },
      saveUseCodeRule: (codeRuleType, code) => { this.saveUseCodeRule(codeRuleType, code); },
      setFieldRequired: (field, required) => { this.setFieldRequired(field, required, this); },
    });
  };
  onBeforeEdit(params) {
    // const { isNew, isCopy, copySrcData } = params ? params : {};
  }

  handleBeforeSaveEvent = (data) => {
    const func = this.getDynJsFunc('onBeforeSave');
    if (typeof func === 'function') {
      const editConfig = this.getEditConfig();
      return func({
        data: this.props.data,
        stateData: data,
        getFieldValue: (field) => { return this.getFieldValue(field, this); },
        setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
        setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this) },
        pageCode: editConfig.editPage.CODE,
        custom: this.props.custom,
      });
    }
  };



  onBeforeSaveHandleRecord(params) {
    // const { editCode, record, srcRecord } = params ? params : {};
  }

  handleBeforeSaveHandleRecordEvent = (pageCode, record, srcRecord, customParams) => {
    const func = this.getDynJsFunc('onBeforeSaveHandleRecord');
    if (typeof func === 'function') {
      func({
        record,
        srcRecord,
        customParams,
        data: this.props.data,
        pageCode,
        login: this.props.login,
        custom: this.props.custom,
        stateData: this.state.data,
        dispatch: this.props.dispatch,
      });
    }
    this.onBeforeSaveHandleRecord({ editCode: pageCode, record, srcRecord, customParams });
  };





  onHeadDropDownFilter(params) {
    const { params: filterParams, colConfig, thisRef } = params ? params : {};
    if (filterParams && colConfig && colConfig.column) {
      if (colConfig.column.Nav_Filters && colConfig.column.Nav_Filters.length) {
        colConfig.column.Nav_Filters.forEach(t => {
          const v = getParseValue(t.VALUE, thisRef.props.login.user, (field) => { return thisRef.getFieldValue(field, thisRef) });
          if (v !== null && v !== undefined) {
            if (t.IS_CUSTOM) {
              filterParams[t.FIELD_NAME] = v;
            }
            else {
              extendRule(filterParams, t.FIELD_NAME, t.OPERATION, v, t.IS_SYS_PARAM);
            }
          }
        });
      }
      const onFetchAutoFilterFunc = thisRef.getDynJsFunc('onFetchAutoFilter');
      if (typeof onFetchAutoFilterFunc === 'function') {
        const editConfig = thisRef.getEditConfig();
        onFetchAutoFilterFunc({
          colInfo: colConfig.column,
          params: params,
          getFieldValue: (field) => { return thisRef.getFieldValue(field, thisRef) },
          pageCode: editConfig.editPage.CODE,
        });
      };
    }
  }
  onAfterHeadControlChange(params) {
    const { value, colConfig } = params ? params : {};
    if (colConfig && colConfig.column) {
      this.handleFieldChangeEvent(value, colConfig.column);
    }
  }
  onAfterHeadDropDownSelect(params) {
    const { value, record, colConfig, thisRef } = params ? params : {};
    const col = colConfig ? colConfig.column : null;
    if (colConfig && colConfig.column) {
      this.handleFieldChangeEvent(value, colConfig.column);
    }

    //填充明细
    if (col && col.Nav_FillMaps) {
      if (record) {
        const editConfig = thisRef.getEditConfig();
        const doFillMapRecords = (fillMaps, editCodes, parentRecord, tempSrcRecord) => {
          if (!parentRecord) {
            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;
              }
            }
          }
          fillMaps.forEach(t1 => {
            if (t1.SRC_NAV && t1.DEST_NAV) {
              if (t1.Nav_Details && t1.Nav_Details.length) {
                editCodes.forEach(code => {
                  const config = thisRef.getEditConfig({ editCode: code });
                  if (config.dataNav === t1.DEST_NAV || config.editCode === t1.DEST_NAV) {
                    const list = getDataFieldValue(tempSrcRecord, t1.SRC_NAV);
                    if (list && list.length) {
                      let num = 1;
                      const result = [];
                      list.forEach(r => {
                        if (thisRef.onBeforeAddRow({ editCode: config.editCode, srcRecord: r, })) return;
                        const newRow = {
                          ID: guid(), ORG_ID: thisRef.props.login.OrgId, NUM: num,
                          ENTITY_ORG_TPYE: config.entityOrgType,
                          srcRecord: r,
                        };
                        t1.Nav_Details.forEach(st => {
                          if (st.DEST_FIELD_NAME && st.SRC_FIELD_NAME) {
                            setDataFieldValue(newRow, st.DEST_FIELD_NAME, getDataFieldValue(r, st.SRC_FIELD_NAME));
                          }
                        });
                        thisRef.onAfterAddRow({ editCode: config.editCode, record: newRow, srcRecord: r, });
                        num++;
                        result.push(newRow);
                      });
                      //this.setEditTableData({ editCode: config.editCode, data: result, isAppend: false, parentRecord });
                      this.setBantchEditTableData({ editCode: config.editCode, data: result, isAppend: false, parentRecord });
                      this.setState({
                        data: parentRecord,
                      }, () => {
                        if (typeof onComplete === 'function') {
                          onComplete();
                        }
                      });
                      if (result && result.length && t1.Nav_ChildrenMaps && t1.Nav_ChildrenMaps.length &&
                        config.childrenEditCodes && config.childrenEditCodes.length) {
                        result.forEach(newRow => {
                          doFillMapRecords(t1.Nav_ChildrenMaps, config.childrenEditCodes, newRow, newRow.srcRecord);
                        });
                      }
                    }
                  }
                });
              }
            }
          });
        }
        if (editConfig.detailEditCodes && editConfig.detailEditCodes.length) {
          doFillMapRecords(col.Nav_FillMaps, editConfig.detailEditCodes, null, record);
        }
      }
      else {
        const editConfig = thisRef.getEditConfig();
        col.Nav_FillMaps.forEach(t1 => {
          if (t1.SRC_NAV && t1.DEST_NAV) {
            if (t1.Nav_Details && t1.Nav_Details.length && editConfig && editConfig.detailEditCodes) {
              editConfig.detailEditCodes.forEach(code => {
                const config = thisRef.getEditConfig({ editCode: code });
                if (config.dataNav === t1.DEST_NAV || config.editCode === t1.DEST_NAV) {
                  this.setEditTableData({ editCode: config.editCode, data: [], isAppend: false });
                }
              });
            }
          }
        });
      }
    }
  }


  getCustomFieldMange = (editCode) => {
    const editTableConfig = this.getEditConfig({ editCode });
    if (!editTableConfig) return null;
    let customCfg = editTableConfig.customCfg;
    let editId = editTableConfig.id;//this.state.editData.ID;
    let editColumns = editTableConfig.editColumns;
    let editPanels = editTableConfig.editPanels;
    return <CustomFieldsManage
      customCfg={customCfg}
      onChange={(field, value, cuCfg) => {
        this.handleCustomFieldChange(customCfg, field, value, cuCfg, editCode, editColumns, editPanels);
      }}
      clearCustomConfig={() => {
        this.clearCustomConfig(editId, editCode, editColumns, editPanels)
      }}
      saveCustomConfig={() => {
        this.saveCustomConfig(customCfg, editId);
      }}
    />
  };




  /*
     新增行之前
    */
  onBeforeAddRow(params) {
    super.onBeforeAddRow(params);
    const { editCode: pageCode, srcRecord } = params ? params : {};
    const onBeforeAddSubRow = this.getDynJsFunc('onBeforeAddSubRow');
    if (typeof onBeforeAddSubRow === 'function') {
      return onBeforeAddSubRow({
        srcRecord: srcRecord,
        pageCode: pageCode,
        custom: this.props.custom,
        getFieldValue: (field) => { return this.getFieldValue(field); },
        setRowFieldVisible: this.setRowFieldVisible,
        setRowFieldLabel: this.setRowFieldLabel,
        setRowFieldDisable: this.setRowFieldDisable,
        setRowFieldPops: this.setRowFieldPops,
        setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this); },
        setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this); },
        getHeadFieldValue: (field) => { return this.getFieldValue(field); },
        saveRowRecord: (r) => {
          this.saveRowRecord({ record: r, editCode })
        },
        setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
      });
    }
  }

  /*
    新增行之后
   */
  onAfterAddRow(params) {
    super.onAfterAddRow(params);
    const { srcRecord, record, editCode } = params || {};
    // const { editCode: pageCode, record, srcRecord, } = params ? params : {};
    const editTableConfig = this.getEditConfig({ editCode: editCode });
    const editColumns = editTableConfig ? editTableConfig.editColumns : null;
    const onAfterAddRow = this.getDynJsFunc('onAfterAddSubRow');
    if (typeof onAfterAddRow === 'function') {
      onAfterAddRow({
        record: record,
        srcRecord: srcRecord,
        pageCode: editCode,
        custom: this.props.custom,
        dispatch: this.props.dispatch,
        login: this.props.login,
        app: this.props.app,
        stateData: this.state.data,
        setRowFieldVisible: this.setRowFieldVisible,
        setRowFieldLabel: this.setRowFieldLabel,
        setRowFieldDisable: this.setRowFieldDisable,
        setRowFieldPops: this.setRowFieldPops,
        setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this); },
        setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this, editCode); },
        getHeadFieldValue: (field) => { return this.getFieldValue(field); },
        saveRowRecord: (r) => {
          this.saveRowRecord({ record: r, editCode })
        },
        setFieldValue: (field, value) => { this.setFieldValue(field, value, this); },
        getFieldValue: (field) => { return this.getFieldValue(field); },
      });
    }

    if (editColumns && editColumns.length) {
      this.fillEditColumnDefaultValue({ record, cols: editColumns, getHeadFieldValue: this.getFieldValue });
      editColumns.forEach(t => {
        if (t.CONTROL_TYPE === 14) {
          this.getCodeRule(t.CODE_RULE_TYPE, t.FIELD_NAME, record.ID, pageCode);
        }
      });
    }
  }

  onBeforeDeleteRow(params) {
    const { editCode: pageCode, record } = params ? params : {};
    const onBeforeDeleteSubRow = this.getDynJsFunc('onBeforeDeleteSubRow');
    if (typeof onBeforeDeleteSubRow === 'function') {
      return onBeforeDeleteSubRow({
        record: record,
        pageCode: pageCode,
        custom: this.props.custom,
        getFieldValue: (field) => { return this.getFieldValue(field); },
        stateData: this.state.data,
      });
    }
  }

  onAfterDeleteRow(params) {
    const { editCode: pageCode, data } = params ? params : {};
    const onAfterDeleteSubRow = this.getDynJsFunc('onAfterDeleteSubRow');
    if (typeof onAfterDeleteSubRow === 'function') {
      onAfterDeleteSubRow({
        pageCode: pageCode,
        updateSubTableData: ({ pageCode, data, isAppend }) => { this.setEditTableData({ editCode: pageCode, data, isAppend }); },
        getSubTableData: ({ pageCode }) => { return this.getEditTableData({ editCode: pageCode }) },
        stateData: data,
      });
    }
  }

  onRowDropDownFilter(params) {
    super.onRowDropDownFilter(params);
    const { record, colConfig, params: filterParams, thisRef, editCode } = params;
    if (colConfig.column) {
      const getRowFieldValue = (field) => {
        return getDataFieldValue(record, field);
      };
      const onFetchAutoFilterFunc = thisRef.getDynJsFunc('onFetchAutoFilterDetail');
      if (typeof onFetchAutoFilterFunc === 'function') {
        onFetchAutoFilterFunc({
          record: record,
          colInfo: colConfig.column,
          params: filterParams,
          stateData: thisRef.state.data,
          pageCode: editCode,
        });
      }
      if (colConfig.column.Nav_Filters && colConfig.column.Nav_Filters.length) {
        colConfig.column.Nav_Filters.forEach(t => {
          const v = getParseValue(
            t.VALUE,
            thisRef.props.login.user,
            field => thisRef.getFieldValue(field),
            getRowFieldValue
          );
          if (v !== null && v !== undefined) {
            if (t.IS_CUSTOM) {
              filterParams[t.FIELD_NAME] = v;
            }
            else {
              extendRule(filterParams, t.FIELD_NAME, t.OPERATION, v, t.IS_SYS_PARAM);
            }
          }
        });
      }
    }
  }

  onAfterRowControlChange(params) {
    const { value, colConfig, record, editCode } = params || {};
    if (colConfig.column) {
      const func = this.getDynJsFunc('onSubChange');
      if (typeof func === 'function') {
        func({
          value,
          colInfo: colConfig.column,
          record,
          stateData: this.state.data,
          pageCode: editCode,
          login: this.props.login,
          dispatch: this.props.dispatch,
          setRowFieldVisible: this.setRowFieldVisible,
          setRowFieldLabel: this.setRowFieldLabel,
          setRowFieldDisable: this.setRowFieldDisable,
          setRowFieldPops: this.setRowFieldPops,
          setFieldValueByBatch: (fieldValues) => { this.setFieldValueByBatch(fieldValues, this); },
          setFieldEditable: (field, editable) => { this.setFieldEditable(field, editable, this); },
          getHeadFieldValue: (field) => { return this.getFieldValue(field); },
          setDataState: (r) => { return this.setState({ data: r }); },
          saveRowRecord: (r) => {
            this.saveRowRecord({ record: r, editCode })
          },
        });
      }
    }
  }

  onDestroyCacheData() {
    super.onDestroyCacheData();
    if (this.useCodeRules) {
      let r = '';
      Object.keys(this.useCodeRules).forEach((n) => {
        const codes = this.useCodeRules[n];
        if (codes && codes.length) {
          let temp = '';
          codes.forEach(t => {
            if (temp) {
              temp += ',';
            }
            temp += t;
          });
          if (r) {
            r += ';'
          }
          r += (n + ':' + temp);
        }
      });
      if (r) {
        this.props.dispatch({
          type: 'app/releasePreUseSerial',
          payload: initFilter(this.props.login.OrgId, r),
          onComplete: (ret) => {
            if (ret) {
              this.useCodeRules = null;
            }
          }
        });
      }
    }
  }

  renderSubTable = (editConfig) => {
    let { detailEditCodes = [], editPage = {} } = editConfig
    const subTableCondition = editPage.SUB_TABLE_CONDITION
    if (subTableCondition) {
      const conditions = []
      subTableCondition.split('|').forEach(cond => {
        const condArr = cond.split(',')
        conditions.push({
          tableCode: condArr[0],
          fieldName: condArr[1],
          operate: condArr[2],
          value: condArr[3]
        })
      })
      const validEditCodes = []
      detailEditCodes.forEach(code => {
        const relatedConds = conditions.filter(cond => cond.tableCode === code)
        const validCond = relatedConds.find(cond => {
          const { fieldName, operate, value } = cond
          const stateValue = getDataFieldValue(this.state.data, fieldName)
          switch (Number(operate)) {
            case 1:
              return stateValue !== null && stateValue !== undefined && stateValue.toString() == value
            default:
              return false
          }
        })
        !!validCond && validEditCodes.push(code)
      })
      detailEditCodes = validEditCodes
    }
    if (!detailEditCodes.length) return null
    if (detailEditCodes.length === 1) {
      return detailEditCodes.map(code => {
        return (
          <div style={{ marginBottom: '15px' }}>
            {this.getRenderEditTable({ editCode: code })}
          </div>
        )
      })
    }
    return (
      <Tabs style={{ marginBottom: '15px' }}>
        {
          detailEditCodes.map(code => {
            const config = this.getEditConfig({ editCode: code })
            // 空配置不渲染，否则界面会多出一个无内容的 tab
            if (config.id) {
              return (
                <TabPane tab={config.label} key={config.id}>
                  {this.getRenderEditTable({ editCode: code })}
                </TabPane>
              )
            }
            return null
          })
        }
      </Tabs>
    )
  }

  render() {
    const editConfig = this.getEditConfig();
    const btns = editConfig ? editConfig.btns : null;
    return (
      <div className={styles.editWrap}>
        <div className={styles.topBar}>
          <div className={classNames(styles.topBarLeftBtns, styles.antBtns_mr8)}>
            {this.getRenderBtns({ btns, record: this.state.data })}
          </div>
          <div style={{ float: "right" }}>
            <Dropdown overlay={this.getCustomFieldMange(undefined)} trigger={['click']} placement="bottomRight">
              <Button icon="bars" />
            </Dropdown>
          </div>
        </div>
        <Form className={styles.formBox}>
          <Row
            className={styles.controlBlock}
            style={{ paddingTop: editConfig && editConfig.columns && editConfig.columns.length ? 10 : 0 }}
          >
            {this.onRenderHeadControls()}
          </Row>
          {this.onRenderPanel()}
          {this.renderSubTable(editConfig)}
        </Form>
      </div>
    );
  }
}

export default EditComponent;
