import React from 'react'
import { message } from 'antd'
import {
  empty,
  extendRule,
  initFilter,
  addRuleAndGroups,
  getCustomParams,
  permissionUtils,
  getParseValue,
  getDataFieldValue,
} from '../../utils/common'
import TableBaseComponent from "../TableBaseComponent";
import WithDragDropContext from '../../components/common/WithDragDropContext'
import DataLoading from '../../components/common/DataLoading'

class TableComponent extends TableBaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      tableConfig: {},
      loadParam: {}
    };
  };
  onLoadData() {
    this.formOperateLog()
    this.getTablesByFormCode(this.props.formCode, this.props.parentId, this.props.tableId);
  }

  /**
   * 表单加载日志埋点
   */
  formOperateLog = () => {
    const { formId, tableId } = this.props
    if (formId && tableId) {
      const { formData, login } = this.props
      this.props.dispatch({
        type: 'app/operateLog',
        payload: {
          FormCode: formData.CODE,
          FormName: formData.NAME,
          UserId: login.userId,
          OrgId: login.OrgId
        }
      })
    }
  }

  getTablesByFormCode = (formCode, parentId, tableId) => {
    const orgId = this.props.login.OrgId;
    const OJson = initFilter(orgId, formCode, '', 0, 1, parentId, tableId);
    this.props.dispatch({
      type: 'listPage/getTablePageTables',
      payload: OJson
    }).then(res => {
      res && this.doGetTablesByFormCode(res)
    })
  };

  doGetTablesByFormCode = (ret) => {
    if (ret) {
      this.setState({
        tableList: ret.Nav_Tables,
        formData: ret.Nav_Form,
        jsFile: ret.Nav_Form.JS_FILES,
      }, () => {
        this.onAfterGetTablesByFormCode();
      });
    }
  };

  onAfterGetTablesByFormCode() {
    const { onLoadParam, onTableData, onRowSelectChange, parentRecord, onRegLoadDataFunc, isQuery = true, onRegClearSelectdRowFunc, customParams } = this.props;
    if (this.state.tableList && this.state.tableList.length) {
      this.state.tableList.forEach(t => {
        setTimeout(() => {
          this.getTableConfigByPage({
            tableId: t.ID,
            parentRecord,
            onLoadParam,
            customParams,
            onAfterGetData: onTableData,
            onSelectChange: onRowSelectChange,
            onComplete: (tableConfig) => {
              //注册加载函数
              if (onRegLoadDataFunc) {
                if (typeof onRegLoadDataFunc === 'function') {
                  onRegLoadDataFunc({
                    loadFunc: (data) => { this.loadDataTableBySearch(tableConfig.tableCode, data) },
                    pageCode: (tableConfig.pageTable ? tableConfig.pageTable.CODE : tableConfig.tableCode), parentId: parentRecord ? parentRecord.ID : null
                  });
                }
              }
              if (onRegClearSelectdRowFunc) {
                if (typeof onRegClearSelectdRowFunc === 'function') {
                  onRegClearSelectdRowFunc({
                    loadFunc: () => { this.setTableSelectedRowKeys({ tableCode: tableConfig.tableCode, selectedKeys: [] }); },
                    pageCode: (tableConfig.pageTable ? tableConfig.pageTable.CODE : tableConfig.tableCode), parentId: parentRecord ? parentRecord.ID : null
                  });
                }
              }
              // 查询table 数据
              if (isQuery) {
                this.loadTableData({ tableCode: tableConfig.tableCode });
              }
            }
          })
        }, 200);
      });
    }
  }

  onRenderTableByList({ tableList /*,parentRecord,onRegLoadDataFunc,onLoadParam,onClickRow,isQuery,parentId */ }) {
    const tableWrapStyle = {
      backgroundColor: '#ffffff',
      padding: '0.16rem'
    }
    return tableList && tableList.length
      ? tableList.map(item => {
        const tableConfig = this.getTableConfig({ tableCode: item.CODE })
        if (tableConfig && tableConfig.isShowCard) {
          return (
            <WithDragDropContext>
              <div key={item.ID} style={tableWrapStyle}>
                {this.getRenderTableCard(item.CODE)}
              </div>
            </WithDragDropContext>
          )
        }
        return (
          <WithDragDropContext>
            <div key={item.ID} style={tableWrapStyle}>
              {this.getRenderTable(item.CODE)}
            </div>
          </WithDragDropContext>
        )
      })
      : <DataLoading />
  }

  getTableConfigByPage = ({ tableId, parentRecord, onLoadParam, customParams, onAfterGetData, onSelectChange, onComplete }) => {
    const { login } = this.props;
    const doSetTableConfig = (ret2) => {
      let json1 = initFilter(login.OrgId, '', "NUM", 0, 1, login.user.ID);
      extendRule(json1, "ID", 1, tableId);
      this.props.dispatch({
        type: 'listPage/getTablePageConfigInfo',
        payload: json1,
        onComplete: (ret) => {
          if (ret) {
            ret.Nav_CustomHiddenCols = ret2 ? ret2.Nav_CustomHiddenCols : null;
            ret.Nav_CustomCols = ret2 ? ret2.Nav_CustomCols : null;
            ret.DefaultPageSize = ret2 ? ret2.DefaultPageSize : 0;
            this.doGetTableConfigByPage(ret, parentRecord, onLoadParam, customParams, onAfterGetData, onSelectChange, onComplete);
          }
        }
      })
    }

    let json2 = initFilter(login.OrgId, tableId, "NUM", 0, 1, login.user.ID);
    this.props.dispatch({
      type: 'listPage/getUserCustomConfigInfo',
      payload: json2,
      onComplete: (ret2) => {
        doSetTableConfig(ret2);
      }
    })
  };

  getColumnConfigByPageColumn = (col, colConfigs) => {
    let controlType = col.CONTROL_TYPE;
    let tmpData = {};
    if (controlType === 3) {//下拉
      tmpData = {
        enumName: col.ENUM,
      }
    }
    else if (controlType === 5) { // 多选控件
      tmpData = {
        enumName: col.ENUM,
      }
    }
    else if (controlType === 9 || controlType === 24) {//分页下拉
      tmpData = {
        api: col.INPUT_DATA_API,
        showField: col.INPUT_SHOW_FIELD,
        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,
        filterOrgType: col.INPUT_FILTER_ORG_TYPE,
      }
    }
    else if (controlType === 12) { // 下拉多选
      tmpData = {
        enumName: col.ENUM,
      }
    }

    const colConfig = {
      id: col.ID,
      field: col.FIELD_NAME,
      label: col.LABEL,
      num: col.NUM,
      isShowCol: col.IS_DEFAULT,
      enumName: col.ENUM,
      showIdField: col.SHOW_ID_FIELD,
      showFormCode: col.SHOW_FORM_CODE,
      showFormParms: col.CUSTOM_PARAMS,
      isRule: col.IS_RULE,
      formatFuncName: col.FORMAT,
      width: col.WIDTH,
      footer: col.FOOTER_SUM_TYPE,
      customParams: col.CUSTOM_PARAMS,
      column: col,
      data: tmpData,
      controlType,
    };
    colConfigs.push(colConfig);
    return colConfig;
  };

  getBtnConfigByPageBtn = (btn, btnConfigs) => {
    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,
      wordTemplateCode: btn.WORD_TEMPLATE_CODE,
      customParams: btn.CUSTOM_PARAMS,
      checkSelected: btn.SELECT_SHOW,
      isConfirm: btn.IS_COMFIRM,
      api: btn.API_URL,
      num: btn.NUM,
      btn,
      isAddLog: true,
      enableStatus: btn.ENABLE_STATUS
    };
    btnConfigs.push(btnConfig);
    return btnConfig;
  };

  getColBtnConfig = (origColConfigs, origBtnConfigs, colConfigs, btnConfigs, customCfg, customHidCols, customCols) => {
    let isNeedSort = false;
    if (origColConfigs && origColConfigs.length) {
      origColConfigs.forEach(n1 => {
        const temps = customCols ? customCols.filter(t => t.COLUMN_ID === n1.id) : null;//自定义列信息 如显示名称、顺序
        if (temps && temps.length) {
          const col = temps[0];
          if (col.LABEL) {
            n1.dbLabel = n1.dbLabel !== undefined && n1.dbLabel !== null ? n1.dbLabel : n1.label;
            n1.label = col.LABEL;
          }
          if (col.NUM !== undefined && col.NUM !== null) {
            n1.dbNum = n1.dbNum !== undefined && n1.dbNum !== null ? n1.dbNum : n1.num;
            n1.num = col.NUM;
            isNeedSort = true;
          }
        }
        else {
          if (n1.dbLabel) {
            n1.label = n1.dbLabel;
          }
          if (n1.dbNum) {
            n1.num = n1.dbNum;
            isNeedSort = true;
          }
        }
      });

      if (isNeedSort) {
        origColConfigs.sort((x, y) => x.num > y.num ? 1 : -1);
      }

      //获取列信息
      origColConfigs.forEach(t => {
        t.dbNum = t.dbNum !== undefined && t.dbNum !== null ? t.dbNum : t.num;
        t.dbLabel = t.dbLabel !== undefined && t.dbLabel !== null ? t.dbLabel : t.label;

        //检查是否隐藏
        let isHid = false;
        if (customHidCols && customHidCols.length) {
          customHidCols.forEach((n1, i1) => {
            if (n1.ID === t.id) {
              isHid = true;
            }
          });
        }
        const isSysParam = t.field ? t.field.indexOf('Nav_SysParams') > -1 : false;
        if (customCfg && !isSysParam) {
          customCfg.push({//填充自定义
            ID: t.id,
            title: t.label,
            isCheck: !isHid,
            num: t.num,
            dbTitle: t.dbLabel,
            dbNum: t.dbNum,
          });
        }
        if (isHid) return;
        colConfigs.push(t);
      });
    }

    if (origBtnConfigs && origBtnConfigs.length) {
      origBtnConfigs.forEach(t => {
        btnConfigs.push(t);
      });
    }
  };

  doGetTableConfigByPage(ret, parentRecord, onLoadParam, customParams, onAfterGetData, onSelectChange, onComplete) {
    //ret.Nav_Columns;//ret.RowBtns;//ret.Btns
    const origColConfigs = [];
    const origBtnConfigs = [];
    const origRowBtnConfigs = [];
    const origRightBtnConfigs = [];
    const colConfigs = [];
    const btnConfigs = [];
    const rowBtnConfigs = [];
    const rightBtnConfigs = [];
    const customCfg = [];//自定义配置



    const navFields = [];
    const formId = ret.PageTable.PAGE_FORM_ID;
    const tableConfig = {
      id: ret.PageTable.ID,
      tableCode: ret.PageTable.CODE,
      deleteApi: ret.PageTable.DEL_API_URL,
      batchDeleteApi: ret.PageTable.BATCH_DEL_API_URL,
      hasChildren: ret.HasChildren,
      classField: ret.PageTable.CLASS_FIELD,
      footerSumType: ret.PageTable.FOOTER_SUM_TYPE,
      checkType: ret.PageTable.CHECK_TYPE,
      checked: ret.PageTable.SHOW_CHECK,
      maxCheckCount: ret.PageTable.MAX_SELECT,
      classFuncName: ret.PageTable.CLASS_FUNC_NAME,
      api: ret.PageTable.API_URL,
      sort: ret.PageTable.SORT,
      order: ret.PageTable.SORT ? ret.PageTable.ORDER : 1,
      pageTable: ret.PageTable,
      orgType: ret.PageTable.FILTER_ORG_TYPE,
      parentRecord: parentRecord,
      formData: ret.Nav_Form,
      authOrgCodes: (ret.PageTable.AUTH_ORG_CODES ? ret.PageTable.AUTH_ORG_CODES : ret.Nav_Form.AUTH_ORG_CODES),
      formId: ret.PageTable.PAGE_FORM_ID,
      jsFile: ret.Nav_Form ? ret.Nav_Form.JS_FILES : '',
      // 代码中配置 customParams 优先级高于列表配置
      customParams: customParams || ret.PageTable.CUSTOM_PARAMS,
      position: ret.PageTable.POSITION,
      isShowRowNo: ret.PageTable.IS_SHOW_ROW_NO,
      rule: { rules: [] },
      defaultPageSize: ret.DefaultPageSize,
      onLoadParam,
      onAfterGetData,
      onSelectChange,
      isShowCard: ret.PageTable.IS_SHOW_CARD,
      cardPicField: ret.PageTable.PIC_CODE_FIELD,
      ignoreOrgRule: ret.PageTable.IGNORE_ORG_RULE,
      isNoSelectField: ret.PageTable.NO_SELECT_FIELD,
      exportTitle: ret.PageTable.TITLE
    };
    if (ret.PageTable.SORTS && ret.PageTable.ORDERS) {
      let sorts = ret.PageTable.SORTS.split(',');
      let orders = ret.PageTable.ORDERS.split(',');
      tableConfig.sorts = [];
      sorts.forEach((x, y) => {
        tableConfig.sorts.push({ sort: x, order: orders[y] });
      });
    }
    else {
      if (!tableConfig.sort) {
        tableConfig.sort = 'CREATE_TIME';
      }
    }

    // 过滤条件，具体设置页面：pf001 -> 列表配置 -> 操作：过滤
    if (ret.TableParams !== null && ret.TableParams.length > 0) {
      ret.TableParams.forEach(t => {
        tableConfig.rule.rules.push({
          isCustom: t.IS_CUSTOM,
          field: t.FIELD_NAME,
          operator: t.OPERATION,
          isSysParam: t.IS_SYS_PARAM,
          value: getParseValue(t.VALUE, this.props.login.user)
        });
      });
    }

    if (!empty(ret.PageTable.RELATION_FIELD, true) && parentRecord) {
      const parentField = ret.PageTable.PARENT_RELATION_FIELD ? ret.PageTable.PARENT_RELATION_FIELD : 'ID';
      tableConfig.rule.rules.push({
        field: ret.PageTable.RELATION_FIELD,
        operator: 1,
        value: getDataFieldValue(parentRecord, parentField)
      });
    }

    if (ret.Nav_Columns && ret.Nav_Columns.length) {
      ret.Nav_Columns.forEach(t => {
        if (t.FIELD_NAME && t.FIELD_NAME.indexOf('.') > 0) {
          let pos = t.FIELD_NAME.lastIndexOf('.');
          let includeTable = t.FIELD_NAME.substring(0, pos);
          navFields.push(includeTable);
        }
        //为添加权限预留
        if (t.IS_RULE && !permissionUtils(this.props.login).checkBtn(ret.Nav_Form.ID, t.ID)) return;

        if (t.IS_DEFAULT) {
          this.getColumnConfigByPageColumn(t, origColConfigs);
        }
      });
    }
    if (ret.RowBtns && ret.RowBtns.length) {
      ret.RowBtns.forEach(t => {
        if (t.ENABLE_STATUS === 1) return;
        //为添加权限预留
        if (t.IS_RULE && !permissionUtils(this.props.login).checkBtn(ret.Nav_Form.ID, t.ID)) return;
        this.getBtnConfigByPageBtn(t, origRowBtnConfigs);
      });
    }

    if (ret.Btns && ret.Btns.length) {
      ret.Btns.forEach(t => {
        if (t.ENABLE_STATUS === 1) return;
        //为添加权限预留
        if (t.IS_RULE && !permissionUtils(this.props.login).checkBtn(ret.Nav_Form.ID, t.ID)) return;
        const btnConfig = this.getBtnConfigByPageBtn(t, origBtnConfigs);
        btnConfigs.push(btnConfig);
      });
    }

    this.getColBtnConfig(origColConfigs, origRowBtnConfigs, colConfigs, rowBtnConfigs, customCfg, ret.Nav_CustomHiddenCols, ret.Nav_CustomCols);

    // const customConfigBtn = { id: guid(), code: 'customConfigBtn', btnType: 7 };
    // rightBtnConfigs.push(customConfigBtn);
    // origRightBtnConfigs.push(customConfigBtn);

    tableConfig.navColumns = ret.Nav_Columns
    tableConfig.originalColumns = origColConfigs;
    tableConfig.originalBtns = origBtnConfigs;
    tableConfig.originalRowBtns = origRowBtnConfigs;
    tableConfig.originalRightBtns = origRightBtnConfigs;

    tableConfig.columns = colConfigs;
    tableConfig.btns = btnConfigs;
    tableConfig.rowBtns = rowBtnConfigs;
    tableConfig.rightBtns = rightBtnConfigs;

    tableConfig.includes = navFields;

    tableConfig.customCfg = customCfg;

    if (tableConfig.jsFile) {
      this.setState({
        jsFile: tableConfig.jsFile
      });
    }
    this.setTableConfig({
      tableConfig,
      onComplete: () => {
        if (typeof onComplete === 'function') {
          onComplete(tableConfig);
        }
      },
    })
  }


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

  handleCustomFieldChange = (tableConfig, field, value, t) => { // 操作字段显示
    const isHidden = field === 'check';
    const btnCols = [], colCols = [], customCfg = [], customHidCols = [], customCols = [];

    const tmp = [...tableConfig.customCfg];
    tmp.forEach((n1, i1) => {
      if (n1.ID !== t.ID) {
        if (!n1.isCheck) {
          customHidCols.push(n1);
        }
      }
      const titleJson = this.getCustomCols(n1, 'title', isHidden || n1.ID !== t.ID || n1.ID === t.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(t);
    }
    this.getColBtnConfig(tableConfig.originalColumns, tableConfig.originalRowBtns, colCols, btnCols, customCfg, customHidCols, customCols);
    this.setTableConfig({
      tableConfig: {
        tableCode: tableConfig.tableCode,
        customCfg,
        rowBtns: btnCols,
        columns: colCols
      }
    });
  };

  saveCustomConfig = (tableConfig) => { // 保存配置字段
    const hiddenTmps = [];
    const colTmps = [];
    if (tableConfig.customCfg && tableConfig.customCfg.length) {
      tableConfig.customCfg.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,
      PageTableId: tableConfig.id,
      HiddenColumnIds: hiddenTmps,
      Columns: colTmps,
    };
    this.props.dispatch({
      type: 'listPage/saveCustomConfig',
      payload: json,
      onComplete: (ret) => {
        if (ret) {
          message.success('执行成功');
        }
      }
    });
  };

  clearCustomConfig = (tableConfig) => { //重置自定义信息
    const btnCols = [], colCols = [], customCfg = [];
    this.getColBtnConfig(tableConfig.originalColumns, tableConfig.originalRowBtns, colCols, btnCols, customCfg, null, null);
    this.setTableConfig({
      tableConfig: {
        tableCode: tableConfig.tableCode,
        customCfg,
        rowBtns: btnCols,
        columns: colCols
      }
    });

    const json = {
      UserId: this.props.login.userId,
      OrgId: this.props.login.OrgId,
      PageTableId: tableConfig.id,
      HiddenColumnIds: null,
      Columns: null,
    };
    this.props.dispatch({
      type: 'listPage/saveCustomConfig',
      payload: json
    })
  };



  onTableBtnParam(params) {
    const { btnConfig, tableConfig, record, tableCode, btnLoading, setformLoading } = params ? params : {};
    const { btnType, clickEventFunName, btn, customParams } = btnConfig ? btnConfig : {};
    // if (btnConfig.code === 'customConfigBtn') { // 表格头部按钮兰的列操作按钮，已移到表格列内
    //   return {
    //     content: <Dropdown overlay={<CustomFieldsManage
    //       customCfg={tableConfig.customCfg}
    //       onChange={(field, value, t) => this.handleCustomFieldChange(tableConfig, field, value, t)}
    //       clearCustomConfig={() => this.clearCustomConfig(tableConfig)}
    //       saveCustomConfig={() => this.saveCustomConfig(tableConfig)}
    //     />} trigger={['click']} placement="bottomRight" key={btnConfig.id} >
    //       <Button title="自定义" style={{ padding: "0 8px" }}>
    //         <Icon type="bars" style={{ fontSize: 16 }} />
    //       </Button>
    //     </Dropdown>
    //   }
    // }
    if (btnType === 0) {//自定义弹窗
      const clickEventFun = this.getDynJsFunc(clickEventFunName, tableConfig);
      if (typeof clickEventFun === 'function') {
        const btnParam = clickEventFun({
          record,
          parentRecord: tableConfig.parentRecord,
          dispatch: this.props.dispatch,
          close: params.close,
          loadData: () => { this.loadTableData({ tableCode }) },
          login: this.props.login,
          custom: this.props.custom,
          props: this.props,
          pageCode: tableConfig.pageTable.CODE,
          btn,
          getSelectedRecords: () => { return this.getTableSelectedRecord({ tableCode }); },
          btnCustomParams: getCustomParams(customParams),
          pageTableCustomParams: getCustomParams(tableConfig.customParams),
          setState: (data) => {
            this.setState(data);
          },
          getState: (key) => {
            return this.state[key];
          },
        });
        if (btnParam) {
          btnParam.disabled = btnParam.isReturn;
        }
        return btnParam;
      }
    }
    else if (btnType === 5 || btnType === 3 || btnType === 8 || btnType === 10) {//编辑 新增 查看 复制新增
      const clickEventFun = this.getDynJsFunc(clickEventFunName, tableConfig);
      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, tableConfig);
      if (typeof clickEventFun === 'function') {
        const btnParam = clickEventFun({
          record,
          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 === 6) {//自定义按钮事件
      return {
        click: (json) => {
          const clickEventFun = this.getDynJsFunc(clickEventFunName, tableConfig);
          if (typeof clickEventFun === 'function') {
            const btnParam = clickEventFun({
              record,
              parentRecord: tableConfig.parentRecord,
              dispatch: this.props.dispatch,
              props: this.props,
              loadData: () => { this.loadTableData({ tableCode }) },
              login: this.props.login,
              custom: this.props.custom,
              json,
              btnLoading,
              setformLoading,
              addOtherLog: (ids, json) => {
                const formId = (tableConfig.formId ? tableConfig.formId : (tableConfig.formData ? tableConfig.formData.ID : this.props.formId));
                const formCode = tableConfig.formCode ? tableConfig.formCode : (tableConfig.formData ? tableConfig.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 });
              },
              pageCode: tableConfig.pageTable.CODE,
              getSelectedRecords: () => { return this.getTableSelectedRecord({ tableCode }); },
              getSelectedRowKeys: () => { return this.getTableSelectedRowKeys({ tableCode }); },
              clearSelectedRowKeys: () => { this.setTableSelectedRowKeys({ tableCode, selectedKeys: [] }); },
              getLoadParam: () => {
                if (typeof tableConfig.onLoadParam === 'function') {
                  return tableConfig.onLoadParam({ pageCode: tableConfig.pageTable.CODE });
                }
                return {};
              },
              btnCustomParams: getCustomParams(customParams),
              pageTableCustomParams: getCustomParams(tableConfig.customParams),
            });
            return btnParam;
          }
        }
      };
    }
    else if (btnType === 7) {//自定义
      const clickEventFun = this.getDynJsFunc(clickEventFunName, tableConfig);
      if (typeof clickEventFun === 'function') {
        const btnParam = clickEventFun({
          record,
          parentRecord: tableConfig.parentRecord,
          dispatch: this.props.dispatch,
          loadData: () => { this.loadTableData({ tableCode }) },
          login: this.props.login,
          custom: this.props.custom,
          btn,
          props: this.props,
          setState: (data) => {
            this.setState(data);
          },
          getState: (key) => {
            return this.state[key];
          },
          btnLoading,
          setformLoading,
          addOtherLog: (ids, json) => {
            const formId = (tableConfig.formId ? tableConfig.formId : (tableConfig.formData ? tableConfig.formData.ID : this.props.formId));
            const formCode = tableConfig.formCode ? tableConfig.formCode : (tableConfig.formData ? tableConfig.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 });
          },
          pageCode: tableConfig.CODE,
          formId: tableConfig.pageTable.PAGE_FORM_ID,
          getSelectedRecords: () => { return this.getTableSelectedRecord({ tableCode }); },
          getLoadParam: () => {
            if (typeof tableConfig.onLoadParam === 'function') {
              return tableConfig.onLoadParam({ pageCode: tableConfig.pageTable.CODE });
            }
            return {};
          },
          getSelectedRowKeys: () => { return this.getTableSelectedRowKeys({ tableCode }); },
          clearSelectedRowKeys: () => { this.setTableSelectedRowKeys({ tableCode, selectedKeys: [] }); },
          btnCustomParams: getCustomParams(customParams),
          pageTableCustomParams: getCustomParams(tableConfig.customParams),
        });
        if (btnParam) {
          btnParam.disabled = btnParam.isReturn;
        }
        return btnParam;
      }
    }
  }
  onAfterLoadData({ tableCode }) {
    this.loadSubRowData(tableCode);
  }

  onTableClickRow(params) {
    const { tableCode, tableConfig, record } = params ? params : {};
    const onClickRow = this.props.onClickRow;
    if (typeof onClickRow === 'function') {
      onClickRow({ record: record, pageCode: (tableConfig && tableConfig.pageTable ? tableConfig.pageTable.CODE : tableCode) });
    }
  }

  onRenderTableSubRow(params) {
    const { tableCode, tableConfig, record } = params ? params : {};
    return (
      <TableComponent
        {...this.props}
        formCode={tableConfig.formData ? tableConfig.formData.CODE : ''}
        parentId={tableConfig.id}
        parentRecord={record}
        isQuery={true}
        onRegLoadDataFunc={(params) => { this.onRegSubRowLoadDataFunc({ ...params, tableCode }) }}
      />
    )
  }

  onRegSubRowLoadDataFunc = ({ tableCode, loadFunc, pageCode, parentId }) => {
    if (!this.loadDataFunc) {
      this.loadDataFunc = [];
    }
    const data = [...this.loadDataFunc];
    data.push({ loadFunc, parentId, tableCode });
    this.loadDataFunc = data;
  };

  onTableExpandRow(params) {
    const { tableCode, record, expanded } = params ? params : {};
    if (expanded) {
      this.loadSubRowData(tableCode, (record ? record.ID : ''));
    }
  }

  onLoadTableDataParam(params) {
    const { loadParam, tableConfig } = params ? params : {};
    let tmpLoadParam = null;
    if (typeof tableConfig.onLoadParam === 'function') {
      tmpLoadParam = tableConfig.onLoadParam({ pageCode: tableConfig.pageTable.CODE });
    }
    const rules = tmpLoadParam && tmpLoadParam.data && tmpLoadParam.data.rules ? tmpLoadParam.data.rules : [];
    const groups = tmpLoadParam && tmpLoadParam.data && tmpLoadParam.data.groups ? tmpLoadParam.data.groups : [];
    const customs = tmpLoadParam && tmpLoadParam.data && tmpLoadParam.data.customs ? tmpLoadParam.data.customs : [];
    const onlyFirst = tmpLoadParam && tmpLoadParam.data ? tmpLoadParam.data.onlyFirst : false;
    if (rules) {
      if (!onlyFirst || onlyFirst && this.state.isfirstLoad) {
        addRuleAndGroups(loadParam, {
          rules,
          groups
        });
      }
    }
    if (customs) {
      if (!onlyFirst || onlyFirst && this.state.isfirstLoad) {
        customs.forEach(item => {
          loadParam[item.key] = item.value;
        });
      }
    }
    const loadParamFun = this.getDynJsFunc('onLoadParam', tableConfig);
    if (loadParamFun) {
      loadParamFun({
        loadParam, parantRow: tableConfig.parentRecord, pageCode: (tableConfig.pageTable ? tableConfig.pageTable.CODE : tableConfig.tableCode),
        login: this.props.login,
        custom: this.props.custom,
        data: this.props.data,
      });
    }
  }

  loadSubRowData = (tableCode, parentId) => {
    if (this.loadDataFunc && this.loadDataFunc.length) {
      this.loadDataFunc.forEach((n, i) => {
        if (n.tableCode == tableCode && (n.parentId === parentId || !parentId)) {
          if (n.loadFunc) {
            n.loadFunc();
          }
        }
      })
    }
  };


  onTableRowClassName(params) {
    const { tableConfig, record } = params ? params : {};
    const classFunc = tableConfig.pageTable && tableConfig.pageTable.CLASS_FUNC_NAME ? this.getDynJsFunc(tableConfig.pageTable.CLASS_FUNC_NAME, tableConfig) : null;
    if (classFunc) {
      return classFunc({
        record,
        pageTableCustomParams: getCustomParams(tableConfig.customParams),
      });
    }
    return super.onTableRowClassName(params);
  }

  onTableRowFormatColumn({ tableCode, tableConfig, colConfig, record, text }) {
    const func = this.getDynJsFunc(colConfig.formatFuncName, tableConfig);
    if (func) {
      return func({
        record,
        loadData: () => { this.loadTableData({ tableCode }); },
        dispatch: this.props.dispatch,
        login: this.props.login,
        custom: this.props.custom,
        getLoadParam: () => {
          if (typeof tableConfig.onLoadParam === 'function') {
            return tableConfig.onLoadParam({ pageCode: tableCode });
          }
          return {};
        },
        text: text,
        onRefreshTableData: () => {
          const data = this.getTableData({ tableCode });
          this.setTableData({ tableCode, data });
        },
        width: colConfig.width,
        pageTableCustomParams: getCustomParams(tableConfig.pageTable.customParams),
        columnCustomParams: getCustomParams(colConfig.customParams),
      })
    }
  }



  onRowDropDownFilter(params) {
    super.onRowDropDownFilter(params);
    const { record, colConfig, params: filterParams, thisRef, tableCode } = 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: tableCode,
        });
      }
      if (colConfig.column.Nav_Filters && colConfig.column.Nav_Filters.length) {
        colConfig.column.Nav_Filters.forEach(t => {
          if (t.IS_CUSTOM) {
            filterParams[t.FIELD_NAME] = getParseValue(t.VALUE, thisRef.props.login.user, (field) => { return thisRef.getFieldValue(field); }, getRowFieldValue);
          }
          else {
            extendRule(filterParams, t.FIELD_NAME, t.OPERATION, getParseValue(t.VALUE, thisRef.props.login.user, (field) => { return thisRef.getFieldValue(field); }, getRowFieldValue), t.IS_SYS_PARAM);
          }
        });
      }
    }
  }

  onAfterTableChange(params) {
    const { pagination, tableCode } = params ? params : {};
    const { pageSize } = pagination ? pagination : {};
    const tableConfig = this.getTableConfig({ tableCode });
    if (pageSize && tableConfig.defaultPageSize !== pageSize) {
      this.props.dispatch({
        type: 'listPage/saveUserCustomConfigInfoForPageSize',
        payload: {
          DefaultPageSize: pageSize,
          UserId: this.props.login.userId,
          OrgId: this.props.login.OrgId,
          PageTableId: tableConfig.id,
        },
        onComplete: (ret) => {
          if (ret) {
            this.setTableConfig({
              tableConfig: {
                tableCode,
                defaultPageSize: pageSize,
              }
            });
          }
        }
      })
    }
  }

  getDynJsFunc = (e, tableConfig) => {
    let func = null;
    const stateJsFile = this.state.jsFile;
    let { jsFile, onLoadParam } = tableConfig ? tableConfig : {};
    if (!jsFile) {
      jsFile = stateJsFile;
    }

    //取静态公共方法
    if (!func) {
      const jsFile = this.getStaticJsFunc();
      func = jsFile[e];
    }

    //取props中的动态js方法
    if (!func && this.props.dynJsFunc) {
      func = this.props.dynJsFunc[e];
    }

    //取加载参数中的动态方法
    let tmpLoadParam = null;
    if (typeof onLoadParam === 'function') {
      tmpLoadParam = onLoadParam({ pageCode: tableConfig.pageTable.CODE });
    }
    if (!func && tmpLoadParam && tmpLoadParam.data && tmpLoadParam.data.dynJsFunc) {
      func = tmpLoadParam.data.dynJsFunc[e];
    }

    //取动态js文件中的方法
    if (!func && jsFile) {
      const jsFiles = jsFile.split(',');
      if (jsFiles) {
        jsFiles.forEach(t => {
          if (func) return;
          const jsFile = require('../../files/list/' + t).default;
          func = jsFile[e];
        });
      }
    }

    return func;
  };

  getStaticJsFunc = () => {
    return {
      colPercentFormat: ({ text }) => { //百分比显示（小数点格式化为2位)
        const num = parseFloat(text);
        if (!isNaN(num)) {
          return (num * 100).toFixed(2) + "%";
        }
        return '';
      },
      colTwoPointFormat: ({ text }) => { //小数点格式化为2位
        const num = parseFloat(text);
        if (!isNaN(num)) {
          return num.toFixed(2);
        }
        return '';
      },
      colNullFormat: ({ text }) => { //为0的显示为空
        const num = parseFloat(text);
        if (num == 0) {
          return '';
        }
        return num;
      },
      colThreePointFormat: ({ text }) => { //小数点格式化为3位
        const num = parseFloat(text);
        if (!isNaN(num)) {
          return num.toFixed(3);
        }
        return '';
      },
      colFourPointFormat: ({ text }) => { //小数点格式化为4位
        const num = parseFloat(text);
        if (!isNaN(num)) {
          return num.toFixed(2);
        }
        return '';
      },
      colTextFormat: ({ text }) => {//格式化文本（文本太长时取前10字符，鼠标以上去时显示所有）
        if (text) {
          if (text.length > 10) {
            return <span title={text}>{text.substring(0, 10) + '...'}</span>;
          }
          else {
            return text;
          }
        }
      },
      colDateFormat: ({ text }) => {//格式化日期  只取日期部分
        if (text) {
          return text.toString().substring(0, 10);
        }
      },
      colTimeFormat: ({ text }) => {//格式化日期  只取时间部分
        if (text) {
          return text.toString().substring(11);
        }
      },
      colYearFormat: ({ text }) => {//格式化日期  只取年部分
        if (text) {
          return text.toString().substring(0, 4);
        }
      },
      colMonthFormat: ({ text }) => {//格式化日期  只取年月部分
        if (text) {
          return text.toString().substring(0, 7);
        }
      },
      colBooleanFormat: ({ text }) => {//格式化为是否
        if (text) {
          if (text.toString().toLowerCase() == 'true' || text.toString().toLowerCase() == '1')
            return '是';
        }
        return '否';
      },
    };
  };

  render() {
    const { onRegLoadDataFunc, onLoadParam, parentRecord, onClickRow, isQuery, parentId, onRowSelectChange, rowSelectedKeys } = this.props;
    const { tableList } = this.state;
    return this.onRenderTableByList({
      tableList,
      onClickRow,
      onRegLoadDataFunc,
      onLoadParam,
      parentRecord,
      isQuery,
      parentId,
      onRowSelectChange,
      rowSelectedKeys
    });
  }
}

export default TableComponent;