import React from 'react'
import { Table, Button, message, notification, Icon, Checkbox, Pagination, Spin, Upload } from 'antd'
import {
  empty,
  extendInclude,
  getDataFieldValue,
  guid,
  initFilter, getCustomParams,
  addRuleAndGroups,
  setDataFieldValue,
  extendOrder,
  extend,
  renderExportCell,
  compare,
  getParseValue
} from '../../utils/common'
import ComponentBase from "../ComponentBase";
import styles from './index.css';
import EditModal from '../../components/Edit/EditModal';
import TableFooterByTotal from '../../components/Table/TableFooterByTotal';
import FormPage from '../../components/FormPage';
import ShowModal from '../../components/common/ShowModal';
import FormModal from '../../components/FormModal'
import { ConfirmButton, ExportToExcel, HttpPrint, PictureThumb, IFComponent } from '@woowalker/feui'
import DataLoading from '../../components/common/DataLoading';
import BDWordPreviewPage from '../../components/CustomPages/BD/BDWordPreviewPage';
import ColumnSetting from './TableColumnSetting';
import ColumnSort from "../../components/common/CustomFieldsManage";
import ImportModal from './ImportModal';
import TableResizableCell from '../../components/Table/TableResizableCell';
import { cloneDeep, get } from 'lodash'
import classNames from 'classnames'
import TableModal from '../../components/Table/TableModal';
import CombinationModal from '../../components/Combination/CombinationModal'
import { getDragableProps, DragDropCard } from '../../utils/withDragDropContext'
import update from 'immutability-helper'
import config from "../../config"
import storage from '../../utils/storage';
const { Column } = Table;

class TableBaseComponent extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {
      data: {},
      tableConfig: {},
      loadParam: {},
      searchColumnText: "",             // 列搜索文本
      showColumnSetting: null,          // 显示表头的设置图标
      showFilterDropdown: false,
      formLoading: false,
      localSearch: {
        // field: "",
        // value: ""
      }
    };
    this.defaultTableCode = 'table';
    this.genDataSource = this.genDataSource.bind(this);
  };

  componentDidMount() {
    super.componentDidMount();
    this.onLoadData();
  };

  /*
  加载数据 事件
   */
  onLoadData() {
    const tableConfigs = this.onGetTableConfig();
    if (tableConfigs && tableConfigs.length) {
      let tableConfig = this.state.tableConfig;
      if (!tableConfig) {
        tableConfig = {};
      }
      tableConfigs.forEach(t => {
        if (t.tableCode === undefined) {
          t.tableCode = this.defaultTableCode;
        }
        if (t.originalColumns === undefined) {
          t.originalColumns = t.columns;
        }
        if (t.originalBtns === undefined) {
          t.originalBtns = t.btns;
        }
        if (t.originalRowBtns === undefined) {
          t.originalRowBtns = t.rowBtns;
        }
        if (t.originalRightBtns === undefined) {
          t.originalRightBtns = t.rightBtns;
        }
        if (!t.id) {
          t.id = guid();
        }
        tableConfig[t.tableCode] = t;
      });
      this.setState({
        tableConfig,
      }, () => {
        this.onAfterLoadData();
      });
    }
    else {
      this.onAfterLoadData();
    }
  }

  /*
  加载数据之后
   */
  onAfterLoadData() {
    this.onAfterGetTableConfig();
    let tableConfig = this.state.tableConfig;
    if (tableConfig) {
      Object.keys(tableConfig).forEach((n) => {
        this.loadTableData({
          tableCode: tableConfig[n].tableCode,
          isResetLoad: true,
        });
      });
    }
  }

  /*
  获取表配置信息
  {
    tableCode://配置信息
    columns:
    btns:
    rowBtns:
    deleteApi:
    batchDeleteApi:
    rule:
    id:
    hasChildren
    classField
    footerSumType
    checkType
    checked,
    api,
    position,
    isShowRowNo,是否显示序号
  }
  */
  onGetTableConfig() {

  }

  /*
    获取表配置信息 之后
   */
  onAfterGetTableConfig() {

  }

  /*
  依搜索参数加载表数据
   */
  loadDataTableBySearch = (tableCode, data) => {
    const tableConfig = this.getTableConfig({ tableCode })
    const customParams = getCustomParams(tableConfig.customParams)

    let { param, extendParam = {} } = data ? data : {};
    extendParam["PageIndex"] = 1;
    extendParam["Start"] = 0;
    extendParam['IsAllLoad'] = !!customParams.IsAllLoad;
    const tempParamJson = this.getLoadParam({ tableCode });
    if (param && extendParam) {
      this.setSearchParam({
        tableCode,
        searchParam: param,
        onComplete: () => {
          if (!tempParamJson) {
            const loadParamJson = this.initLoadParam({ tableCode });
            extendParam = {
              ...loadParamJson,
              ...extendParam
            }
          }
          this.setLoadParam({
            tableCode,
            loadParam: extendParam,
            onComplete: () => {
              this.loadTableData({ tableCode });
            }
          })
        }
      });
    }
    else if (param) {
      this.setSearchParam({
        tableCode,
        searchParam: param,
        onComplete: () => {
          this.loadTableData({ tableCode });
        }
      });
    }
    else if (extendParam) {
      if (!tempParamJson) {
        const loadParamJson = this.initLoadParam({ tableCode });
        extendParam = {
          ...loadParamJson,
          ...extendParam
        }
      }
      this.setLoadParam({
        tableCode,
        loadParam: extendParam,
        onComplete: () => {
          this.loadTableData({ tableCode });
        }
      })
    }
    else {
      this.loadTableData({ tableCode });
    }
  };

  /*
  初始化加载参数
   */
  initLoadParam = ({ tableCode, pageSize, pageIndex }) => {
    const tableConfig = this.getTableConfig({ tableCode });
    let { sort, order, defaultPageSize } = tableConfig ? tableConfig : {};
    if (!sort) {
      sort = 'CREATE_TIME';
      order = 1;
    }
    const loadParamJson = initFilter(this.props.login.OrgId, '', sort, order);
    if (defaultPageSize) {
      loadParamJson.Limit = defaultPageSize;
      loadParamJson.Start = (loadParamJson.PageIndex - 1) * defaultPageSize;
    }
    if (pageSize) {
      loadParamJson.Limit = pageSize;
      loadParamJson.Start = (loadParamJson.PageIndex - 1) * pageSize;
    }
    if (pageIndex) {
      let pz = 10;
      if (pageSize >= 0) {
        pz = pageSize
      } else if (defaultPageSize) {
        pz = defaultPageSize
      } else {
        pz = 10
      }
      loadParamJson.PageIndex = pageIndex;
      loadParamJson.Start = (pageIndex - 1) * pz;
    }
    const selectFields = (tableConfig.navColumns || []).map(col => {
      return col.FIELD_NAME && col.FIELD_NAME !== 'null' ? col.FIELD_NAME : false
    }).filter(field => !!field)
    if (selectFields.length && !tableConfig.isNoSelectField) {
      if (selectFields.indexOf('ID') === -1) {
        selectFields.push('ID')
      }
      if (selectFields.indexOf('ORG_ID') === -1) {
        selectFields.push('ORG_ID')
      }
      loadParamJson.SelectField = selectFields
    }
    if (tableConfig && tableConfig.rule) {
      addRuleAndGroups(loadParamJson, tableConfig.rule);
    }
    return loadParamJson;
  };

  /*
  加载表数据
   */
  loadTableData(params) {
    const { tableCode = this.defaultTableCode, isResetLoad, pageSize, onComplete, onLoadData } = params ? params : {};
    const tempParamJson = this.getLoadParam({ tableCode });
    if (isResetLoad || !tempParamJson) {
      const loadParamJson = this.initLoadParam({ tableCode, pageSize });
      this.setLoadParam({
        tableCode,
        loadParam: loadParamJson,
        onComplete: () => {
          const paramJson = this.getLoadParam({ tableCode });
          const tempJson = paramJson ? JSON.parse(JSON.stringify(paramJson)) : {};
          this.doLoadTableData({ ...tempJson }, tableCode, onComplete, onLoadData);
        }
      });
    }
    else {
      const paramJson = this.getLoadParam({ tableCode });
      const tempJson = paramJson ? JSON.parse(JSON.stringify(paramJson)) : {};
      this.doLoadTableData({ ...tempJson }, tableCode, onComplete, onLoadData);
    }
  }

  /*
  重置加载表数据参数
   */
  onLoadTableDataParam(params) {

  }

  /*
  加载数据之后
   */
  onAfterLoadTableData(params) {

  }
  getRequestHeaders =() =>{
    // 请求参数
    const addHeader = 'Bearer ' + storage('lacal').getItem('accessToken').val
    const userId = storage('lacal').getItem('userid').val
    const user = storage('lacal').getItem('loginUserVerify').val
    const RootOrgId = storage('lacal').getItem('RootOrgId').val
    const orgId = storage('lacal').getItem('webOrgId').val
    const Tenant = storage('lacal').getItem('Tenant').val
    const headers = {
      // 'Content-Type': type === 'post' ? 'application/json' : 'application/x-www-form-urlencoded',
      Authorization: addHeader,
      userid: userId,
      username: user ? user.username : '',
      RootOrgId,
      orgId,
      Tenant:Tenant
    }
    return headers
  }

  /**
   * 获取表格加载参数
   * @param {*} loadParamJson
   * @param {*} tableCode
   */
  getLoadTableDataParams = (loadParamJson, tableCode) => {
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    const tableConfig = this.getTableConfig({ tableCode });
    const { api, sorts, orgType, authOrgCodes, ignoreOrgRule } = tableConfig ? tableConfig : {};
    if (api === null || api === undefined) return false;
    if (sorts && sorts.length) {
      sorts.forEach(t => {
        extendOrder(loadParamJson, t.sort, t.order);
      });
    }

    //去重添加添加导航属性
    const navFields = [];
    if (tableConfig && tableConfig.includes && tableConfig.includes.length) {
      tableConfig.includes.forEach(t => {
        navFields.push(t);
      });
    }
    else if (tableConfig) {
      const cols = tableConfig.originalColumns && tableConfig.originalColumns.length ? tableConfig.originalColumns : tableConfig.columns;
      if (cols && cols.length) {
        const doGetInclude = (f) => {
          if (f && f.indexOf('.') > 0) {
            let pos = f.lastIndexOf('.');
            let includeTable = f.substring(0, pos);
            navFields.push(includeTable);
          }
        }
        cols.forEach(t => {
          const field = t.field;
          if (field) {
            let opIndex = field.indexOf('+');
            if (opIndex === -1) {
              opIndex = field.indexOf('-');
              if (opIndex === -1) {
                opIndex = field.indexOf('*');
                if (opIndex === -1) {
                  opIndex = field.indexOf('/');
                }
              }
            }
            if (opIndex !== -1) {
              const leftField = field.substring(0, opIndex);
              const rightField = field.substring(opIndex + 1);
              doGetInclude(leftField);
              doGetInclude(rightField);
            }
            else {
              doGetInclude(field);
            }
          }
        });
      }
    }
    if (navFields.length) {
      const tmp = [...new Set(navFields)];
      tmp.forEach((n, i) => {
        extendInclude(loadParamJson, n);
      });
    }
    if (orgType) {
      loadParamJson.OrgType = orgType;
    }
    if (authOrgCodes) {
      loadParamJson.AuthOrgCodes = authOrgCodes;
    }

    //查询参数
    const searchParam = this.getSearchParam({ tableCode });
    if (searchParam) {
      if (searchParam) {
        addRuleAndGroups(loadParamJson, searchParam);
      }
    }
    // 菜单参数
    const { currActivatedMenu } = this.props.app || {}
    loadParamJson['MenuParameter'] = currActivatedMenu && currActivatedMenu.MENU_FORM_PARAMS ? currActivatedMenu.MENU_FORM_PARAMS : ''
    // 是否忽略组织权限
    if (ignoreOrgRule) {
      loadParamJson.IgnoreOrgRule = ignoreOrgRule
    }

    const isError = this.onLoadTableDataParam({ tableCode, loadParam: loadParamJson, tableConfig });
    if (isError) return false;
    return loadParamJson
  }

  /*
  实际加载表数据
   */
  doLoadTableData = (loadParamJson, tableCode, onComplete, onLoadData) => {
    const payloadJson = this.getLoadTableDataParams(loadParamJson, tableCode)
    if (!payloadJson) return

    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    const tableConfig = this.getTableConfig({ tableCode });
    const { api } = tableConfig ? tableConfig : {};

    this.props.dispatch({
      type: 'listPage/getTableData',
      payload: loadParamJson,
      url: api,
      onComplete: (ret) => {
        if (ret && !ret.IsSuccessful) {
          message.error(ret.ErrorMessage);
        }
        if (ret && ret.Data && ret.Data.length && tableConfig.isShowRowNo) {
          ret.Data.forEach((n, i) => {
            n.ROW_NO = (i + 1);
          });
        }
        if (typeof onLoadData === 'function') {
          onLoadData(ret);
        }
        else {
          this.setTableData({
            tableCode,
            data: ret,
            onComplete: () => {
              if (ret && typeof tableConfig.onAfterGetData === 'function') {
                tableConfig.onAfterGetData(ret.Data, tableConfig.pageTable ? tableConfig.pageTable.CODE : tableConfig.tableCode);
              }
              if (ret) {
                this.onAfterLoadTableData({ tableCode, data: ret.Data });
              }
              if (typeof onComplete === 'function') {
                onComplete();
              }
            }
          });
        }
        // 设置默认选中
        const { rowSelectedKeys } = this.props
        if (Array.isArray(rowSelectedKeys) && rowSelectedKeys.length) {
          this.setTableSelectedRowKeys({ tableCode, selectedKeys: rowSelectedKeys })
        }
      }
    })
  };

  /*
  获取配置
   */
  getTableConfig(params) {
    const { tableCode = this.defaultTableCode } = params || {};
    let tableConfig = this.state.tableConfig;
    if (tableConfig === undefined) {
      tableConfig = {};
    }
    return tableConfig[tableCode];
  }

  /*
  设置配置
   */
  setTableConfig({ tableConfig, onComplete }) {
    if (!tableConfig) return;
    let tableCode = tableConfig.tableCode;
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
      tableConfig.tableCode = tableCode;
    }
    let tempTableConfig = this.state.tableConfig;
    if (tempTableConfig === undefined) {
      tempTableConfig = {};
    }
    let oldConfig = tempTableConfig[tableCode];
    if (oldConfig === undefined) {
      oldConfig = {};
    }
    tableConfig = {
      ...oldConfig,
      ...tableConfig,
    };
    if (tableConfig.originalColumns === undefined) {
      tableConfig.originalColumns = tableConfig.columns;
    }
    if (tableConfig.originalBtns === undefined) {
      tableConfig.originalBtns = tableConfig.btns;
    }
    if (tableConfig.originalRightBtns === undefined) {
      tableConfig.originalRightBtns = tableConfig.rightBtns;
    }
    if (tableConfig.originalRowBtns === undefined) {
      tableConfig.originalRowBtns = tableConfig.rowBtns;
    }
    if (!tableConfig.id) {
      tableConfig.id = guid();
    }
    tempTableConfig = {
      ...tempTableConfig,
      [tableCode]: tableConfig,
    };

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

  /*
    获取加载参数
    */
  getLoadParam(params) {
    const { tableCode = this.defaultTableCode } = params ? params : {};
    let loadParam = this.state.loadParam;
    if (loadParam === undefined) {
      loadParam = {};
    }
    return loadParam[tableCode];
  }

  /*
  设置加载参数
   */
  setLoadParam({ tableCode, loadParam, onComplete }) {
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    let tempLoadParam = this.state.loadParam;
    if (tempLoadParam === undefined) {
      tempLoadParam = {};
    }
    let oldParam = tempLoadParam[tableCode];
    if (oldParam === undefined) {
      oldParam = {};
    }
    loadParam = {
      ...oldParam,
      ...loadParam,
    };
    tempLoadParam = {
      ...tempLoadParam,
      [tableCode]: loadParam,
    };

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

  /*
    获取查询参数
    */
  getSearchParam(params) {
    const { tableCode = this.defaultTableCode } = params ? params : {};
    let searchParam = this.state.searchParam;
    if (searchParam === undefined) {
      searchParam = {};
    }
    return searchParam[tableCode];
  }

  /*
  设置查询参数
   */
  setSearchParam({ tableCode, searchParam, onComplete }) {
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    let tempSearchParam = this.state.searchParam;
    if (tempSearchParam === undefined) {
      tempSearchParam = {};
    }
    let oldParam = tempSearchParam[tableCode];
    if (oldParam === undefined) {
      oldParam = {};
    }
    searchParam = {
      ...oldParam,
      ...searchParam,
    };
    tempSearchParam = {
      ...tempSearchParam,
      [tableCode]: searchParam,
    };

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

  /*
  获取表数据
   */
  getTableData(params) {
    const { tableCode = this.defaultTableCode } = params ? params : {};
    let data = this.state.data;
    if (data === undefined) {
      data = {};
    }
    return data[tableCode];
  }

  /*
  设置表数据
   */
  setTableData({ tableCode, data, onComplete }) {
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    let tempData = this.state.data;
    if (tempData === undefined) {
      tempData = {};
    }
    tempData = {
      ...tempData,
      [tableCode]: data,
    };

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

  /*
获取选中
 */
  getTableSelectedRowKeys(params) {
    const { tableCode = this.defaultTableCode } = params ? params : {};
    let selectedKeys = this.state.selectedKeys;
    if (selectedKeys === undefined) {
      selectedKeys = {};
    }
    const cuKeys = selectedKeys[tableCode];
    if (cuKeys) {
      return cuKeys;
    }
    return [];
  }

  /**
   * add by qxiong 2020.06.11
   * @param {*} param0 
   * 设置所有页面选中
   * 在此日期前，有关 selectedKeys 的使用
   * 并没有发现复制一份旧的 selectedKeys， 然后使用 tableCode 保存新一份 selectedKeys 有什么作用
   * 所以此处不继续沿用这种逻辑，而是直接该保存保存，不绕弯路
   * const { selectedRowsAll = [] } = this.state
   * 上面这一行的 selectedRowsAll = [] 默认赋值，以及为什么会有很多 undefined 的判断，因为这个组件是被继承的，继承的组件中又重写了state
   * 所以就相当于直接在这个组件中定义 state，基本都取不到
   */
  setTableSelectedRowsAll = ({ selectedRowKeys, selectedRows = [] }) => {
    const { selectedRowsAll = [] } = this.state
    selectedRowsAll.push(...selectedRows)
    const tempSelected = []
    selectedRowKeys.forEach(key => {
      const find = selectedRowsAll.find(row => row.ID === key)
      find && tempSelected.push(find)
    })
    this.state.selectedRowsAll = tempSelected
  }

  /*
  设置选中
   */
  setTableSelectedRowKeys({ tableCode, selectedKeys, onComplete }) {
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    let tempSelectedKeys = this.state.selectedKeys;
    if (tempSelectedKeys === undefined) {
      tempSelectedKeys = {};
    }
    tempSelectedKeys = {
      ...tempSelectedKeys,
      [tableCode]: selectedKeys,
    };
    let isSelected = this.state[tableCode + '_isSelected'];
    if (!selectedKeys || !selectedKeys.length) {
      isSelected = false;
    }
    this.setState({
      selectedKeys: tempSelectedKeys,
      [tableCode + '_isSelected']: isSelected,
    }, () => {
      const tableConfig = this.getTableConfig({ tableCode });
      if (tableConfig && typeof tableConfig.onSelectChange === 'function') {
        tableConfig.onSelectChange(this.getTableSelectedRowKeys({ tableCode }), (tableConfig.pageTable ? tableConfig.pageTable.CODE : tableCode));
      }
      if (typeof onComplete === 'function') {
        onComplete();
      }
    });
  }

  /*
  表改变事件
   */
  onTableChange = (tableCode, pagination, filters, sorter) => {
    const { current, pageSize } = pagination;
    const loadParam = this.getLoadParam({ tableCode });
    let sort = {
    };
    if (sorter && sorter.field) {
      sort["Sort"] = sorter.field;
      sort["Order"] = sorter.order === "descend" ? '0' : '1';
    }
    let newParams = {
      ...loadParam,
      OrgId: this.props.login.OrgId,
      PageIndex: current,
      Limit: pageSize,
      Start: (current - 1) * pageSize
    };
    const tempParam = { ...newParams, ...sort };
    if (!loadParam.IsAllLoad) {
      const tempJson = JSON.parse(JSON.stringify(tempParam));
      this.doLoadTableData({ ...tempJson }, tableCode);
    }
    this.setLoadParam({
      tableCode,
      loadParam: tempParam,
      onComplete: () => {
        this.onAfterTableChange({ tableCode, pagination, filters, sorter, loadParam: tempParam });
      }
    });
  };

  /*
   表改变之后
   {
   tableCode,
    pagination,
    filters,
     sorter,
     loadParam
     }
   */
  onAfterTableChange(params) {

  }

  /*
  选中表行项改变时
   */
  onSelectTableChange = (tableCode, selectedRowKeys, selectedRows) => {  // 选择表格行
    this.setTableSelectedRowsAll({ selectedRowKeys, selectedRows })
    this.setTableSelectedRowKeys({ tableCode, selectedKeys: selectedRowKeys });
    this.setState({
      [tableCode + '_isSelected']: selectedRowKeys && selectedRowKeys.length
    });
  };

  /*
  获取表选中记录
  {
  tableCode:表编号
  }
   */
  getTableSelectedRecord(params) {
    const { tableCode = this.defaultTableCode } = params ? params : {};
    const tableData = this.getTableData({ tableCode });
    const selectKeys = this.getTableSelectedRowKeys({ tableCode });
    const result = [];
    if (selectKeys && tableData && tableData.Data) {
      selectKeys.forEach(item => {
        tableData.Data.forEach(t => {
          if (item.toString().toUpperCase() == t.ID.toString().toUpperCase()) {
            result.push(t);
          }
        })
      });
    }
    return result;
  }

  /*
    保存行记录
   */
  saveRowRecord({ record, onComplete, tableCode }) {
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    const data = this.getTableData({ tableCode });
    let list = data.Data;
    if (!list) {
      list = [];
      data.Data = [];
    }
    const index = list.findIndex(item => record.ID === item.ID);
    const item = list[index];
    if (item) {
      list.splice(index, 1, {
        ...item,
        ...record,
      });
    }
    this.setTableData({
      tableCode,
      data,
      onComplete
    });
  }

  /*
 {field,value,colConfig,record,thisRef,tableCode}
  */
  onAfterRowControlChange(params) {

  }
  /*
      {field,value,colConfig,record,thisRef}
     */
  onRowControlChange(params) {
    const { field, value, record, thisRef, tableCode = thisRef.defaultTableCode } = params ? params : {};
    if (record) {
      setDataFieldValue(record, field, value);
      thisRef.saveRowRecord({
        record,
        tableCode,
        onComplete: () => {
          thisRef.onAfterRowControlChange(params);
        },
      });
    }
  }

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

  /*
  {field,colConfig,record,thisRef,tableCode}
   */
  onAfterRowControlBlur(params) {

  }

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

  }

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

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

  }

  /*
   {record,complete,colConfig,data,columns,thisRef}
   */
  onRowDropDownSelect(params) {
    const { record, complete, colConfig, data, columns, thisRef, tableCode = thisRef.defaultTableCode } = params ? params : {};
    if (thisRef.onBeforeRowDropDownSelect({ ...params })) return;
    const configData = colConfig.data;
    thisRef.fillDropDownSelectRecord({
      record,
      data,
      saveField: configData.saveField,
      labelField: configData.labelField,
      navField: configData.navField,
      field: colConfig.field,
      idField: colConfig.idField,
    });

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

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

  }

  /*
  {tableCode,record,isShow,isPermit,getHeadFieldValue}
   */
  onRowEditFormData(params) {
    const { record, tableCode = this.defaultTableCode } = params ? params : {};
    const data = this.getTableData({ tableCode });
    return {
      record: record,
      onSave: (row) => {
        this.saveRowRecord({ ...params, record: row, });
      },
      stateData: data ? [] : data.Data,
    }
  }

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

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

  /*
  格式化行项列
   */
  onTableRowFormatColumn({ tableCode, tableConfig, colConfig, record, text }) {
    return text;
  }

  /**
   * 可控的排序设置
   *
   */
  setSortData = (orderType, sortType, tc) => {
    this.setLoadParam({
      tableCode: tc,
      loadParam: {
        Order: orderType,
        Sort: sortType
      },
      onComplete: () => {
        this.loadTableData({ tableCode: tc });
      }
    })
  }
  /**搜索单列 */
  setSearchInfo = (value, fields,) => {
    this.setState({
      localSearch: {
        fields,
        value
      }
    })
  }

  /**单元格 */
  renderCell = ({ isShowCol, col, tableCode, tableConfig, record, text, columns }) => {
    if (isShowCol) {
      if (col.formatFuncName) {
        col.format = (params) => {
          const formatValue = this.onTableRowFormatColumn({ record: params.record, text: params.text, tableCode, tableConfig, colConfig: params.col });
          setDataFieldValue(record, (col.field ? col.field : col.formatFuncName) + '_formatValue', formatValue);
          return formatValue;
        };
      }
      return this.getTableCellText({ col, record, text });
    }
    this.setRowColumnConfig({ col, params: { columns, tableCode, tableConfig }, record });
    return <div key={record.ID + col.field} style={{ width: col.width > 0 && col.width, wordWrap: 'break-word', wordBreak: 'break-all' }}>
      {
        this.getControl(col)
      }
    </div>
  }

  /*
  {
      format,enumName,isBool,isDate,isPercent,isTwoPoint,isLimitText,isTime,showFormCode,showIdField,showFormId,visible,label,ID,width
      data:{
         enumName
      }
    }
   */
  getColumnByColumnConfig(tableCode) {
    const { showColumnSetting, showFilterDropdown } = this.state;
    const tableConfig = this.getTableConfig({ tableCode });
    if (!tableConfig) {
      return [];
    }

    const columns = tableConfig.columns;
    if (!columns) return [];
    const cols = [];
    const tmp = [];
    if (tableConfig.isShowRowNo) {
      tmp.push({ title: '序号', key: 'ROW_NO', dataIndex: 'ROW_NO', width: 60 });
    }
    columns.forEach(col => {
      if (col.visible || col.visible === undefined) {
        const isShowCol = col.controlType === null || col.controlType === undefined || col.controlType === 0 || col.controlType > 100;
        const uniqueKey = col.id ? col.id : (col.field ? col.field : col.formatFuncName);
        const columnObj = {
          title: <div style={{ userSelect: "none" }}>{col.label}</div>,
          key: uniqueKey,
          dataIndex: col.field,
          filterDropdown: args => {
            return <ColumnSetting
              {...this.props}
              {...args}
              key={uniqueKey}
              setSortData={type => this.setSortData(type, col.field, tableCode)}
              setSearchInfo={val => this.setSearchInfo(val, col.field, tableCode)}
              tableConfig={tableConfig}
              onMouseLeave={() => this.setState({ showFilterDropdown: false, showColumnSetting: null })}
              stateTableConfig={this.state.tableConfig}
              setTableConfig={value => this.setState({ tableConfig: value })}
              colConfig={col}
            />
          },
          filterDropdownVisible: showFilterDropdown && showColumnSetting === uniqueKey,
          filterIcon: filtered => (
            showColumnSetting === uniqueKey
              ? <Icon type="setting" />
              : <div />
          ),
          onFilterDropdownVisibleChange: (visible) => {
            this.setState({
              showFilterDropdown: visible
            })
          },
          render: (text, record) => {
            const convertText = this.renderCell({ isShowCol, col, tableCode, tableConfig, record, text, columns });
            const cellTitle = (typeof convertText === "string" || typeof convertText === "number") ? convertText : "";
            return <span title={cellTitle}>{convertText}</span>
          }
        }
        col.width && (columnObj.width = col.width)
        tmp.push(columnObj);
      }
    });

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

  /*
  获取渲染按钮
   */
  getRenderBtns(tableCode, tableConfig, record, btns, type) {
    const filterBtns = []
    if (btns && btns.length) {
      btns.forEach(btn => {
        const { BTN_CONDITION } = btn.btn || {}
        if (BTN_CONDITION) {
          const conditions = BTN_CONDITION.split('|').map(item => {
            const conds = item.split(',')
            return {
              field: conds[0],
              operate: conds[1],
              //value: conds[2]
              value: getParseValue(conds[2], this.props.login.user)
            }
          })
          const find = conditions.find(cond => {
            const { field, operate, value } = cond
            //let fileValue=getDataFieldValue(record, field);
            let fileValue=get(record,field);
            switch (Number(operate)) {
              case 1: // 等于
                return fileValue == value
              case 2: // 不等于
                return fileValue != value
              default:
                return false
            }
          })
          find && filterBtns.push(btn)
        } else {
          filterBtns.push(btn)
        }
      })
    }
    //排序
    filterBtns.sort(compare);
    return filterBtns.map(t => {
      return this.getRenderBtn({ tableCode, tableConfig, record, btnConfig: t, type });
    })
  }


  /*
  获取表行项样式类名称
   */
  onTableRowClassName({ tableConfig, record }) {
    if (this.props.SetRowClass && typeof this.props.SetRowClass === 'function') {
      return this.props.SetRowClass(record);
    }
    else if (tableConfig && tableConfig.classField) {
      let className = null;
      let classAry = tableConfig.classField.split(',');
      classAry.forEach((n, i) => {
        let splitClass = n.split(':');
        if (splitClass.length === 2) {
          let filed = splitClass[0];
          let values = splitClass[1].split('|');
          let r = record[filed];

          if (r !== null && r !== undefined && values.length > 1) {
            let index = 0;
            let isGet = false;
            for (index = 0; index < values.length; index = index + 2) {
              if (values[index].toString() == r.toString()) { //如果数组中某个元素和你想要测试的元素对象element相等，则证明数组中包含这个元素，返回true

                isGet = true;
                break;
              }
            }
            if (isGet) {
              className = values[index + 1];
              return className;
            }
          }
        }
      });
      return className;
    }
    return null;
  }

  /*
  渲染表行项子表
   */
  onRenderTableSubRow({ tableCode, tableConfig, record }) {

  }

  /*
  展开表行项时
   */
  onTableExpandRow({ tableCode, tableConfig, record, expanded }) {

  }

  /*
    渲染表页脚
   */
  onRenderTableFooter({ tableCode, tableConfig, data, columns, selectedRowKeys }) {
    return <TableFooterByTotal data={data} sumNum={tableConfig.footerSumType} columns={columns} selected={selectedRowKeys} />
  }

  /*
  点击表行项
   */
  onTableClickRow({ tableCode, tableConfig, record }) {

  }

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

  /*
     btn={
      id:按钮ID
      btnType:按钮类型
      code:按钮编号
      label:显示名称
      icon:按钮图标
      css:按钮样式
      formCode:表单编号
      api:API
      isConfirm:是否需确认
      checkSelected:检查选中
      isAddLog:是否需添加日志
     }
     type:0-行按钮  1-按钮  2-右侧按钮
   */
  getRenderBtn(params) {
    const { tableCode, tableConfig, record, btnConfig } = params ? params : {};
    const { formData } = this.state || {};
    const isRow = record;
    const isSelected = this.state[tableCode + '_isSelected'];
    const loadKey = tableCode + '_' + (record ? (record.ID + btnConfig.id) : btnConfig.id);
    const btnIsLoading = this.state[loadKey];
    const btnLoading = (loading) => {
      this.setState({
        [loadKey]: loading,
      })
    }

    const setformLoading = (loading) => {
      this.setState({
        formLoading: loading,
      })
    }
    const close = (type) => {
      if (type === undefined || type === 0) {
        const tmpFunc = this.state['closeModelFunc' + (record ? (record.ID + btnConfig.id) : btnConfig.id)];
        if (tmpFunc) {
          tmpFunc();
        }
      }
      if (type === undefined || type === 1) {
        this.loadTableData({ tableCode });
      }
    };
    let btnParam = this.onTableBtnParam({ ...params, close, btnLoading, setformLoading });
    if (!btnParam) {
      btnParam = {};
    }

    let { disabled, onBtnDisabled, content, click, json, onClick } = btnParam ? btnParam : {};

    let disabledClick = disabled ? e => e.stopPropagation() : null;
    let disabledStyle = disabled ? { color: "#c5c3c3", cursor: "not-allowed" } : { cursor: "pointer" };

    if (btnConfig.btnType === 0) { //自定义弹窗
      const closeFunc = (fun) => {
        const data = {};
        data['closeModelFunc' + (record ? (record.ID + btnConfig.id) : btnConfig.id)] = fun;
        this.setState(data);
      };
      const showData = {
        regClose: closeFunc,
      };


      const getIds = () => {
        if (btnConfig.btn.BTN_FUN_TYPE == 1) {//行按鈕
          if (record) {
            let d = false;
            if (typeof onBtnDisabled === 'function') {
              d = onBtnDisabled(record);
            }
            if (d) return;
            return record.ID;
          }
        }
        else {
          const selectRecords = this.getTableSelectedRecord({ tableCode });
          const tempSelectRecordIds = [];
          selectRecords.forEach(t => {
            let d = false;
            if (typeof onBtnDisabled === 'function') {
              d = onBtnDisabled(t);
            }
            if (d) return;
            tempSelectRecordIds.push(t.ID);
          });
          if (tempSelectRecordIds.length) {
            return tempSelectRecordIds.join(',');
          }
        }
      };


      if (!content && btnParam) {
        const that = this;
        const clickKey = btnConfig.code ? btnConfig.code : btnConfig.id;
        //
        let tempData = {
          id: (record ? record.ID : ''),
          parentRecord: record,
          clickKey,
          close,
          getIds,
          getTableSelectedRowKeys: () => that.getTableSelectedRowKeys({ tableCode }),
          btnConfig,
          ...getCustomParams(btnConfig.customParams),
          onSave: () => {
            close();
            this.loadTableData({ tableCode });
          },
          onCancel: () => {
            close();
          },
          onRegDestroyCacheDataFunc: (ret) => {
            if (!this.regDestroyCacheDataFunc) {
              this.regDestroyCacheDataFunc = {};
            }
            this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')] = ret;
          }
        };



        const regClick = async function () {
          let ids = "";
          let isError = false;
          if (btnConfig.btn.BTN_FUN_TYPE == 0) {//按鈕 非行按鈕
            ids = that.getTableSelectedRowKeys({ tableCode });
            if (btnConfig.checkSelected && !ids) {
              message.error('请选择记录');
              isError = true;
            }
          }
          if (!isError) {
            await that.props.dispatch({
              type: 'custom/save',
              payload: {
                [clickKey + (record ? record.ID : '')]: true
              },
            });
          }
          that.btnOperateLog(btnConfig)
          return {
            isReturn: isError
          }
        };

        if (btnParam.data) {
          tempData = {
            ...tempData,
            ...btnParam.data,
          }
        }
        btnParam.content = <FormPage formCode={btnConfig.formCode} data={tempData} />;
        btnParam.click = () => { return regClick() };
        showData.close = () => {
          if (this.regDestroyCacheDataFunc && this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')]) {
            this.regDestroyCacheDataFunc[clickKey + (record ? record.ID : '')]();
          }
        }
      }
      if (btnParam) {
        extend(showData, btnParam);
      }

      let disabledClick = (disabled || !getIds()) ? e => e.stopPropagation() : null;
      let disabledStyle = (disabled || !getIds()) ? { color: "c5c3c3", cursor: "not-allowed" } : { cursor: "pointer" };

      return <ShowModal key={record ? (record.ID + btnConfig.id) : btnConfig.id} title={btnConfig.label} data={showData} login={this.props.login}>
        {isRow
          ? <div><Icon type={btnConfig.icon} className="table_rowBtnStyle" title={btnConfig.label} onClick={disabledClick} style={disabledStyle} /></div>
          : <Button type={btnConfig.css} icon={btnConfig.icon} disabled={disabled || !isSelected && !isRow && btnConfig.checkSelected}>{btnConfig.label}</Button>}
      </ShowModal>;
    }
    else if (btnConfig.btnType === 2) { // 刷新
      if (!isRow) {
        return (
          <Button
            onClick={() => {
              this.btnOperateLog(btnConfig)
              this.loadTableData({ tableCode })
            }}
            type={btnConfig.css}
            icon={btnConfig.icon}
            key={btnConfig.id}>刷新</Button>
        );
      }
    }
    else if (btnConfig.btnType === 5 || btnConfig.btnType === 3 || btnConfig.btnType === 8 || btnConfig.btnType === 10) { //编辑 新增 查看 复制新增
      const isShow = btnConfig.btnType === 8;
      const getIds = () => {
        if (record) {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(record);
          }
          if (d) return;
          return record.ID;
        }
        const selectRecords = this.getTableSelectedRecord({ tableCode });
        const tempSelectRecordIds = [];
        selectRecords.forEach(t => {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(t);
          }
          if (d) return;
          tempSelectRecordIds.push(t.ID);
        });
        if (tempSelectRecordIds.length) {
          return tempSelectRecordIds.join(',');
        }
      };
      const isBatchEdit = btnConfig.btnType === 5 && !isRow;
      const isEdit = !isBatchEdit;
      const extKey = record ? (record.ID + btnConfig.id) : btnConfig.id;
      const reloadKey = (isEdit ? '' : 'batchEdit_') + (btnConfig.formCode + '_' + extKey + '_reload')
      const data = {
        isShow: isShow,
        record,
        isBatchEdit: btnConfig.btnType === 5 && !isRow,
        parentRecord: this.props.parentRecord,
        getIds,
        TreeSelected: this.props.data?.TreeSelected,
        TreeSelectId: this.props.data?.TreeSelectId,
        reloadKey,
      };

      if (data.isBatchEdit && !disabled) {
        disabled = !isSelected;
      }
      if (record && !disabled) {
        disabled = !getIds();
      }
      disabledClick = disabled ? e => e.stopPropagation() : null;
      disabledStyle = disabled ? { color: "#c5c3c3", cursor: "not-allowed" } : { cursor: "pointer" };
      const id = btnConfig.btnType !== 10 && record ? record.ID : '';
      const copySrcId = btnConfig.btnType === 10 && record ? record.ID : '';
      return (
        <EditModal
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          id={id}
          copySrcId={copySrcId}
          data={data}
          title={btnConfig.label}
          customParams={this.props.customParams}
          onSave={() => {
            this.loadTableData({ tableCode })
          }}
          formCode={btnConfig.formCode}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof click === 'function') {
              click(visible)
            }
          }}
        >
          {
            isRow
              ? <div><Icon type={btnConfig.icon} className="table_rowBtnStyle" disabled={disabled} title={btnConfig.label} onClick={disabledClick} style={disabledStyle} /></div>
              : <Button type={btnConfig.css} icon={btnConfig.icon} disabled={disabled}>{btnConfig.label}</Button>
          }
        </EditModal>
      )
    }
    else if (btnConfig.btnType === 4) { //删除
      const getIds = () => {
        if (record) {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(record);
          }
          if (d) return;
          return record.ID;
        }
        const selectRecords = this.getTableSelectedRecord({ tableCode });
        const tempSelectRecordIds = [];
        selectRecords.forEach(t => {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(t);
          }
          if (d) return;
          tempSelectRecordIds.push(t.ID);
        });
        if (tempSelectRecordIds.length) {
          return tempSelectRecordIds.join(',');
        }
      };
      if (isRow) {
        return (
          <ConfirmButton
            key={record ? (record.ID + btnConfig.id) : btnConfig.id}
            isConfirm={true}
            onClick={() => {
              this.btnOperateLog(btnConfig)
              this.onTableBtnDelete({ ...params, btnConfig, id: getIds(), btnLoading })
            }}
            type={btnConfig.css ? btnConfig.css : 'danger'}
            icon={btnConfig.icon ? btnConfig.icon : 'delete'}
            title="删除"
            size="small"
            confirmTitle={'是否确定删除?'}
            disabled={disabled || !getIds()}
            loading={btnIsLoading}
          />
        )
      }
      else {
        return (
          <ConfirmButton
            key={record ? (record.ID + btnConfig.id) : btnConfig.id}
            isConfirm={true}
            onClick={() => {
              this.btnOperateLog(btnConfig)
              this.onTableBtnBatchDelete({ ...params, btnConfig, ids: getIds(), btnLoading })
            }}
            type={btnConfig.css ? btnConfig.css : 'danger'}
            icon={btnConfig.icon ? btnConfig.icon : 'delete'}
            title="删除"
            confirmTitle={'是否确定删除?'}
            disabled={disabled || !isSelected}
            loading={btnIsLoading}
          />
        )
      }
    }
    else if (btnConfig.btnType === 6) { //自定义按钮事件
      const regClick = () => {
        let tempBtnParam = null;
        if (typeof click === 'function') {
          tempBtnParam = click();
        }
        let { json, onBtnDisabled, onClick } = tempBtnParam ? tempBtnParam : {};
        const getIds = () => {
          if (record) {
            let d = false;
            if (typeof onBtnDisabled === 'function') {
              d = onBtnDisabled(record);
            }
            if (d) return;
            return record.ID;
          }
          const selectRecords = this.getTableSelectedRecord({ tableCode });
          const tempSelectRecordIds = [];
          selectRecords.forEach(t => {
            let d = false;
            if (typeof onBtnDisabled === 'function') {
              d = onBtnDisabled(t);
            }
            if (d) return;
            tempSelectRecordIds.push(t.ID);
          });
          if (tempSelectRecordIds.length) {
            return tempSelectRecordIds.join(',');
          }
        };
        const ids = getIds();
        if (!ids && (isRow || !isRow && btnConfig.checkSelected)) {
          message.error('请选择记录或者记录无效');
          return;
        }
        if (btnConfig.api) {
          const filter = initFilter(this.props.login.OrgId, ids);
          const temJson = json ? { ...filter, ...json } : filter;
          if (typeof onClick === 'function') {
            if (onClick(temJson, ids)) {
              return;
            }
          }
          btnLoading(true);
          this.props.dispatch({
            type: 'app/getDataByPost',
            payload: temJson,
            url: btnConfig.api,
            onComplete: (ret) => {
              btnLoading(false);
              if (ret) {
                this.loadTableData({ tableCode });
                message.success('执行成功');
                //添加日志
                if (btnConfig.isAddLog) {
                  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(temJson);
                  this.addOtherLog({ formCode, formId, title, data, extData });
                }
              }
            }
          })
        }
        this.btnOperateLog(btnConfig)
      };
      disabled = disabled ? disabled : (((isRow && false || !isRow && !isSelected && btnConfig.checkSelected)) ? true : false);
      return (
        <ConfirmButton
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          onClick={regClick}
          isConfirm={btnConfig.isConfirm}
          loading={btnIsLoading}
          type={btnConfig.css}
          icon={btnConfig.icon}
          title={btnConfig.label}
          size={isRow ? 'small' : null}
          confirmTitle={'是否确认执行?'}
          disabled={disabled}
        />
      )
    }
    else if (btnConfig.btnType === 7) { //自定义
      const getIds = () => {
        if (record) {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(record);
          }
          if (d) return;
          return record.ID;
        }
        const selectRecords = this.getTableSelectedRecord({ tableCode });
        const tempSelectRecordIds = [];
        selectRecords.forEach(t => {
          let d = false;
          if (typeof onBtnDisabled === 'function') {
            d = onBtnDisabled(t);
          }
          if (d) return;
          tempSelectRecordIds.push(t.ID);
        });
        if (tempSelectRecordIds.length) {
          return tempSelectRecordIds.join(',');
        }
      };

      if (content) {
        return content;
      }
      if (btnConfig.api) {
        const regClick = () => {
          const ids = getIds();
          if (!ids && !isRow && btnConfig.checkSelected) {
            message.error('请选择记录');
            return;
          }
          const filter = initFilter(this.props.login.OrgId, ids);
          const temJson = json ? { ...filter, ...json } : filter;
          if (typeof onClick === 'function') {
            if (onClick(temJson, ids)) {
              return;
            }
          }
          btnLoading(true);
          this.btnOperateLog(btnConfig)
          this.props.dispatch({
            type: 'app/getDataByPost',
            payload: temJson,
            url: btnConfig.api,
            onComplete: (ret) => {
              btnLoading(false);
              if (ret) {
                this.loadTableData({ tableCode });
                message.success('执行成功');
                //添加日志
                if (btnConfig.isAddLog) {
                  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(temJson);
                  this.addOtherLog({ formCode, formId, title, data, extData });
                }
              }
            }
          })
        };
        disabled = disabled ? disabled : (((isRow && !getIds() || !isRow && !isSelected && btnConfig.checkSelected)) ? true : false);
        return (
          <ConfirmButton
            key={record ? (record.ID + btnConfig.id) : btnConfig.id}
            onClick={regClick}
            isConfirm={btnConfig.isConfirm}
            loading={btnIsLoading}
            type={btnConfig.css}
            icon={btnConfig.icon}
            title={btnConfig.label}
            size={isRow ? 'small' : null}
            confirmTitle={'是否确认执行?'}
            disabled={disabled}
          />
        )
      }
      const customParams = getCustomParams(btnConfig.customParams)
      if (customParams && customParams.print === 'true') {
        return (
          <HttpPrint onClick={() => this.btnOperateLog(btnConfig)}>
            <Button type={btnConfig.css} icon={btnConfig.icon} >{btnConfig.label}</Button>
          </HttpPrint>
        )
      }
    }
    else if (btnConfig.btnType === 9) { // 导出
      let { tableCode = this.defaultTableCode, tableConfig } = params ? params : {};
      tableConfig === undefined && (tableConfig = this.getTableConfig({ tableCode }));

      const tableColumns = this.getColumnByColumnConfig(tableCode)
      const tableDataSource = this.getTableData({ tableCode })
      const tableSelectedKeys = this.getTableSelectedRowKeys({ tableCode })
      const loadParamJson = this.getLoadTableDataParams(cloneDeep(this.initLoadParam({ tableCode })), tableCode)
      // 计算导出的 excel 需要在第一行插入的标题
      const formCode = tableConfig.formCode ? tableConfig.formCode : (tableConfig.formData ? tableConfig.formData.CODE : this.props.formCode)
      const searchModel = this.props.search || {
        fieldConfigs: {},
        relatedFieldConfigs: {}
      }
      const relatedFieldConfigs = searchModel.relatedFieldConfigs[formCode] || {}
      const relatedFormCode = relatedFieldConfigs.relatedTo
      const relatedExtraRows = relatedFieldConfigs.extraRows
      const fieldConfigs = searchModel.fieldConfigs[relatedFormCode || formCode] || []
      const exportInserTitle = [tableConfig.exportTitle || formData.NAME]
      if (relatedFormCode && Array.isArray(relatedExtraRows)) {
        exportInserTitle.push(...relatedExtraRows)
      }
      fieldConfigs.forEach(fc => {
        const { isExportTitle, label, value, dataSource } = fc
        const cellText = renderExportCell(value, dataSource, fc, this.props.app.enums || {})
        if (isExportTitle && cellText) {
          exportInserTitle.push(`${label}：${cellText}`)
        }
      })

      if (!isRow) {
        return (
          <ExportToExcel
            fileName={formData.NAME}
            insertRows={[exportInserTitle.join(' ')]}
            columns={tableColumns}
            columnConfigs={tableConfig.columns}
            dataSource={tableDataSource && tableDataSource.Data ? tableDataSource.Data : []}
            selectedKeys={tableSelectedKeys}
            config={{
              type: 'listPage/getTableData',
              payload: loadParamJson || {},
              url: tableConfig.api,
              customParams:btnConfig.customParams//wyw 添加 参数到导出功能 url
            }}
          />
        )
      }
      return null;
    }
    else if (btnConfig.btnType === 11) { // 导入
      if (!isRow) {
        return (
          <ImportModal
            key={record ? (record.ID + btnConfig.id) : btnConfig.id}
            formCode={btnConfig.formCode}
            click={() => { this.btnOperateLog(btnConfig) }}
          >
            <Button icon='download'>导入</Button>
          </ImportModal>
        )
      }
      return null;
    }
    else if (btnConfig.btnType === 12) { // 列表弹窗
      return (
        <TableModal
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          formCode={btnConfig.formCode}
          id={record.ID}
          customParams={btnConfig.customParams}
          data={record}
          title={btnConfig.label}
          parentId={btnConfig.btnType === -1 ? record.parent_id : record.ID}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof this.click === 'function') {
              this.click(visible)
            }
          }}>
          <Icon type={btnConfig.icon} title={btnConfig.label} />
        </TableModal>
      )
    }
    else if (btnConfig.btnType === 14) { // 组合表单
      return (
        <CombinationModal
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          formCode={btnConfig.formCode}
          id={record.ID}
          customParams={btnConfig.customParams}
          data={record}
          title={btnConfig.label}
          parentId={btnConfig.btnType === -1 ? record.parent_id : record.ID}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof this.click === 'function') {
              this.click(visible)
            }
          }}>
          <Icon type={btnConfig.icon} title={btnConfig.label} />
        </CombinationModal>
      )
    }
    else if (btnConfig.btnType === 15) { // 自定义导入
      const uploadProps = {
        name: 'file',
        showUploadList: false,
        action: config.serviceHost(btnConfig.api),
        data: { OrgId: this.props.login.OrgId },
        headers: this.getRequestHeaders(),
        onChange: (info) => {
          const { name, status, response = {} } = info.file
          const { IsSuccessful, ErrorMessage } = response
          if (status === 'done') {
            if (IsSuccessful) {
              message.success(`${name} 导入并保存成功`)
              this.forceUpdate()
            } else {
              message.error(`${name} 导入失败，${ErrorMessage}`)
            }
          } else if (status === 'error') {
            if (response.ErrorMessage) {
              message.error(`${name} 导入错误，${ErrorMessage}`)
            } else {
              message.error(`${name} 导入错误`)
            }
          }
        }
      }
      return (
        <Upload {...uploadProps}>
          <Button><Icon type={btnConfig.icon} title={btnConfig.label} /> {btnConfig.label}</Button>
        </Upload>
      )
    }
    else if (btnConfig.btnType === 16) { // 带参数的自定义弹窗
      return (
        <FormModal
          key={record ? (record.id + btnConfig.id) : btnConfig.id}
          formCode={btnConfig.formCode}
          id={record?.id}
          customParams={btnConfig.customParams}
          data={record}
          title={btnConfig.label}
          parentId={btnConfig.btnType === -1 ? record?.parent_id : record?.id}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof this.click === 'function') {
              return this.click(visible)
            }
          }}>
          <Icon type={btnConfig.icon} title={btnConfig.label} />
        </FormModal>
      )
    }
    else if (btnConfig.btnType === 17) { // 树弹窗
      return (
        <FormModal
          key={record ? (record.id + btnConfig.id) : btnConfig.id}
          formCode={btnConfig.formCode}
          id={record?.id}
          customParams={btnConfig.customParams}
          data={record}
          title={btnConfig.label}
          parentId={btnConfig.btnType === -1 ? record?.parent_id : record?.id}
          click={visible => {
            visible && this.btnOperateLog(btnConfig)
            if (typeof this.click === 'function') {
              return this.click(visible)
            }
          }}>
          <Icon type={btnConfig.icon} title={btnConfig.label} />
        </FormModal>
      )
    }
    else if (btnConfig.btnType === 18) { // word打印模板
      return (
        <ShowModal
          key={record ? (record.ID + btnConfig.id) : btnConfig.id}
          title={btnConfig.label}
          data={{
            content: <BDWordPreviewPage recordId={record.ID} templateCode={btnConfig.wordTemplateCode} />
          }}
        >
          <Icon
            type={btnConfig.icon}
            className='table_rowBtnStyle'
            title={btnConfig.label}
            onClick={disabledClick}
            style={disabledStyle}
          />
        </ShowModal>
      )
    }
    else if (btnConfig.btnType === 20) { // 复选框
      return (
        <Checkbox
          checked={tableConfig.dragable}
          onChange={evt => {
            tableConfig.dragable = evt.target.checked
            this.forceUpdate()
          }}
        >
          {btnConfig.label}
        </Checkbox>
      )
    }

    return isRow ?
      <div><Icon type={btnConfig.icon} className="table_rowBtnStyle" onClick={disabledClick} style={disabledStyle} title={btnConfig.label} /></div> :
      <Button type={btnConfig.css} icon={btnConfig.icon} >{btnConfig.label}</Button>;
  }


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

  /*
  删除记录
   */
  onTableBtnDelete(params) {
    let { tableCode = this.defaultTableCode, tableConfig, id, btnConfig, btnLoading } = params ? params : {};
    if (tableConfig === undefined) {
      tableConfig = this.getTableConfig({ tableCode });
    }
    const delApiUrl = tableConfig ? tableConfig.deleteApi : {};
    if (empty(delApiUrl)) {
      message.error('请配置删除API');
      return;
    }
    if (empty(id)) {
      return;
    }
    if (btnLoading) {
      btnLoading(true);
    }
    this.props.dispatch({
      type: 'app/deleteItem',
      payload: { id },
      url: delApiUrl,
      onComplete: (ret) => {
        if (btnLoading) {
          btnLoading(false);
        }
        if (ret) {
          const deleteData = [];
          if (btnConfig.isAddLog) {
            const tableData = this.getTableData({ tableCode });
            const selectKeys = id.split(',');// this.getTableSelectedRowKeys({ tableCode });

            if (selectKeys && tableData && tableData.Data) {
              selectKeys.forEach(item => {
                tableData.Data.forEach(t => {
                  if (item.toString().toUpperCase() === t.ID.toString().toUpperCase()) {
                    deleteData.push(t);
                  }
                })
              });
            }
          }
          message.success('删除成功');
          this.loadTableData({ tableCode });
          if (btnConfig.isAddLog) {
            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 extData = deleteData ? ('删除数据，详情：', JSON.stringify(deleteData)) : null;
            this.addDeleteLog({ formCode, ids: id, formId, extData });
          }
        }
      }
    })
  }

  /*
  批次删除记录
   */
  onTableBtnBatchDelete(params) {
    let { tableCode = this.defaultTableCode, tableConfig, ids, btnConfig, btnLoading } = params ? params : {};
    if (tableConfig === undefined) {
      tableConfig = this.getTableConfig({ tableCode });
    }
    const delApiUrl = tableConfig ? tableConfig.batchDeleteApi : {};
    if (empty(delApiUrl)) {
      message.error('请配置删除API');
      return;
    }
    if (!ids) return;
    if (btnLoading) {
      btnLoading(true);
    }
    this.props.dispatch({
      type: 'app/deleteItemBatch',
      payload: {
        ids: ids
      },
      url: delApiUrl,
      onComplete: (ret) => {
        if (btnLoading) {
          btnLoading(false);
        }
        if (ret) {
          const deleteData = [];
          if (btnConfig.isAddLog) {
            const tableData = this.getTableData({ tableCode });
            const selectKeys = ids.split(',');// this.getTableSelectedRowKeys({ tableCode });

            if (selectKeys && tableData && tableData.Data) {
              selectKeys.forEach(item => {
                tableData.Data.forEach(t => {
                  if (item.toString().toUpperCase() === t.ID.toString().toUpperCase()) {
                    deleteData.push(t);
                  }
                })
              });
            }
          }
          this.loadTableData({ tableCode });
          message.success('删除成功');
          this.setTableSelectedRowKeys({ tableCode, selectedKeys: [] });
          if (btnConfig.isAddLog) {
            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 extData = deleteData ? ('删除数据，详情：', JSON.stringify(deleteData)) : null;
            this.addDeleteLog({ formCode, ids, formId: formId, extData });
          }
        }
      }
    })
  }

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

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

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

          return false;
        })
      } else {
        return tableData.Data
      }
    } else {
      return []
    }
  }

  /**
   * 表格操作栏
   */
  tableOperateColumn(tableCode) {
    const tableConfig = this.getTableConfig({ tableCode });
    const rowBtns = tableConfig.rowBtns;

    const OperateTitle = () => {
      return (
        <ColumnSort
          customCfg={tableConfig.customCfg}
          onChange={(field, value, t) => this.handleCustomFieldChange(tableConfig, field, value, t)}
          clearCustomConfig={() => this.clearCustomConfig(tableConfig)}
          saveCustomConfig={() => this.saveCustomConfig(tableConfig)}
        />
      )
    }

    if (rowBtns && rowBtns.length) {
      let currRecord = {};
      // let obj = {
      //   render: (text, record, index) => {
      //     currRecord = record
      //   }
      // };

      //let l = this.getRenderBtns(tableCode, tableConfig, currRecord, rowBtns, 0).filter(value => typeof value !== "undefined").length;
      //if (l === 0 || l == null) l = 1;
      let width = 32 * rowBtns.length;
      if (width < 80) {
        width = 80;
      }
      return (
        <Column
          title="操作"
          key={rowBtns && rowBtns.length ? rowBtns[0].id : ''}
          dataIndex=''
          // 如果需要支持拖曳排序，则不允许fixed，否则会报错
          fixed={tableConfig.hasChildren || tableConfig.dragable ? false : 'right'}
          width={width}
          filterIcon={<Icon type="menu" />}
          filterDropdown={<OperateTitle />}
          render={(text, record, index) => {
            // 此项宽度设置为 单个样式宽 * 按钮个数 - 左右边距
            return <div className={styles.actionTd} style={{ width: 32 * rowBtns.length - 8 }}>
              {
                this.getRenderBtns(tableCode, tableConfig, record, rowBtns, 0)
              }
            </div>
          }}
        />
      )
    } else {
      return (
        <Column
          title=""
          key="operateColumn"
          dataIndex=''
          filterIcon={<Icon type="menu" />}
          filterDropdown={<OperateTitle />}
          width={35}
          render={() => <div style={{ width: 26 }} />}
        />
      )
    }
  }

  // 伸缩表格列操作
  handleResize = (tableCode, colu) => (e, { size }) => {
    if (this.state.tableConfig === undefined || !this.state.tableConfig[tableCode]) {
      message.error("表单配置错误！");
      return
    }

    let thisColumns = { ...this.state.tableConfig[tableCode] }
    if (this.state.tableConfig === undefined) {
      this.state.tableConfig = {};
    }
    thisColumns.columns.forEach(item => {
      if (item.field === colu.dataIndex) {
        item.width = size.width
      }
    })

    this.setState({
      tableConfig: {
        ...this.state.tableConfig,
        [this.state.tableConfig[tableCode]]: thisColumns
      }
    })
  }

  /**
   * 批量新增保存
   */
  handleBatchAddSave = (tableCode) => {
    const { selectedRowsAll = [] } = this.state
    const { close } = this.props.data
    close instanceof Function && close(undefined, cloneDeep(selectedRowsAll))
    this.state.selectedRowsAll = undefined
    this.onSelectTableChange(tableCode, [], [])
  }

  moveRow = (dragIndex, hoverIndex, tableCode, tableConfig) => {
    const tableData = this.state.data[tableCode].Data
    const dragRow = tableData[dragIndex]
    const hoverRow = tableData[hoverIndex]
    const pageTable = tableConfig.pageTable || {}
    if (!pageTable.SORT) {
      message.error('未配置排序字段，操作取消')
      return
    }
    // 调用接口
    this.props.dispatch({
      type: 'listPage/listRowDragChange',
      payload: {
        Keyword: pageTable.DATA_TABLE,
        Parameter1: dragRow.ID,
        Parameter2: hoverRow.ID,
        Parameter3: pageTable.SORT,
        OrgId: this.props.login.OrgId
      },
      onComplete: (res) => {
        if (res) {
          // 更新数据
          const updateData = update(tableData, {
            $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]]
          })
          this.state.data[tableCode].Data = updateData
          this.setState({ data: this.state.data })
        }
      }
    })
  }

  /*
  渲染表
   */
  getRenderTable(tableCode) {
    if (tableCode === undefined) {
      tableCode = this.defaultTableCode;
    }
    let tableConfig = this.getTableConfig({ tableCode });
    if (!tableConfig) return <DataLoading style={{ height: 300 }} />;
    const tableHeight = tableConfig.pageTable ? tableConfig.pageTable.HEIGTH : 0;
    const tableWidth = tableConfig.pageTable ? tableConfig.pageTable.WIDTH : 0;
    const isFixed = tableConfig.checked || (tableConfig.rowBtns && tableConfig.rowBtns.length) || tableHeight; // 是否固定列

    let newColumns = this.getColumnByColumnConfig(tableCode); // 表头字段

    let loadParam = this.getLoadParam({ tableCode });
    let tableData = this.getTableData({ tableCode });
    const selectKeys = this.getTableSelectedRowKeys({ tableCode });
    loadParam = loadParam || {};
    tableData = tableData || {};
    const tableDataSource = this.genDataSource(tableCode, tableData)
    tableDataSource.forEach(tds => {
      !tds.hasOwnProperty('key') && (tds.key = tds.ID)
    })
    const defaultExpandedRowKeys = tableDataSource && tableDataSource.length ? [tableDataSource[0].key] : []

    const paginationConfig = loadParam?.IsAllLoad ? false : {
      pageSizeOptions: ['5', '10', '20','100'],
      current: loadParam ? loadParam.PageIndex : 1,
      pageSize: loadParam ? loadParam.Limit : 10,
      total: tableData ? tableData.TotalCount : 0,
      showSizeChanger: true,
      showQuickJumper: true,
      size: 'small',
      position: (tableConfig.position ? tableConfig.position : 'bottom'),
      showTotal: () => `共 ${tableData ? tableData.TotalCount : 0} 条`
    };

    // 配置最多可选个数
    const customRowSelection = tableConfig.maxCheckCount ? {
      hideDefaultSelections: true,
      columnTitle: ' ',
      getCheckboxProps: (record) => {
        return {
          disabled: selectKeys.length >= tableConfig.maxCheckCount && selectKeys.indexOf(record.ID) === -1
        }
      }
    } : {}

    const rowSelection = {
      // 如果需要支持拖曳排序，则不允许fixed，否则会报错
      fixed: !tableConfig.hasChildren && !tableConfig.dragable,
      selectedRowKeys: selectKeys,
      columnWidth: 32,
      onChange: (selectedRowKeys, selectedRows) => { this.onSelectTableChange(tableCode, selectedRowKeys, selectedRows); },
      type: tableConfig && tableConfig.checkType == 1 ? "radio" : "checkbox",
      hideDefaultSelections: false,
      ...customRowSelection
    };

    let hasFooter = () => { // 是否显示底部
      let footerSumType = tableConfig.footerSumType;
      if (footerSumType === 1) {
        return true
      } else if (footerSumType === 2) {
        return selectKeys && selectKeys.length > 0;
      } else {
        return false;
      }
    };

    /**
     * 固定规则：
     * 固定列要设置宽度（操作列除外）
     * 留少数几列不设定宽度
     */
    let isScrollX = () => {
      if (isFixed) {
        const totalWidth = newColumns.reduce((a, b) => {
          if (b.width) {
            return a + b.width
          } else {
            return a + 0
          }
        }, 0);
        const scrollX = tableWidth > (totalWidth + 200) ? tableWidth : (totalWidth + 200);
        return { scroll: { x: scrollX, y: tableHeight } }
      } else {
        return { scroll: { y: tableHeight } }
      }
    };

    const openNotification = (h) => {
      notification.destroy();
      notification.open({
        message: h.title,
        key: h.key,
        placement: "bottomRight",
      })
    };

    let isLoading = this.props.loading ? this.props.loading.effects["listPage/getTableData"] : false;
    if (!isLoading) {
      isLoading = this.state.formLoading
    }
    const isBatchAddList = this.props.data && this.props.data.btnTypeBatchAdd
    const contentWidth = tableConfig.pageTable && tableConfig.pageTable.WIDTH ? tableConfig.pageTable.WIDTH : "auto"
    const TableHeadBtns = this.getRenderBtns(tableCode, tableConfig, null, tableConfig.btns, 1);
    const { components } = getDragableProps()
    const dragableProps = tableConfig.dragable ? {
      components: {
        ...components,
        ...TableResizableCell
      },
      onRow: (rowRecord, index) => ({
        index,
        moveRow: (dragIndex, hoverIndex) => this.moveRow(dragIndex, hoverIndex, tableCode, tableConfig),
        onClick: () => {
          this.onTableClickRow({ tableCode, tableConfig, rowRecord });
        }
      })
    } : {
      components: TableResizableCell,
      onRow: (rowRecord, index) => ({
        onClick: () => {
          this.onTableClickRow({ tableCode, tableConfig, rowRecord });
        }
      })
    }
    return <React.Fragment>
      {
        isBatchAddList
          ? (
            <div className={styles.tableBtnBar}>
              <Button type="primary" onClick={() => this.handleBatchAddSave(tableCode)}>保存</Button>
            </div>
          ) : (
            TableHeadBtns && TableHeadBtns.length
              ? (
                <div className={styles.tableBtnBar}>
                  {TableHeadBtns}
                </div>
              )
              : null
          )
      }

      <div className={styles.tableContent} style={{ width: contentWidth }}>
        <Table
          rowKey="ID"
          id={tableConfig.id}
          loading={isLoading}
          size="small"
          pagination={paginationConfig}
          dataSource={tableDataSource}
          onChange={(pagination, filters, sorter) => {
            this.onTableChange(tableCode, pagination, filters, sorter)
          }}
          rowSelection={tableConfig.checked ? rowSelection : null}
          rowClassName={(record, index) => {
            const remoteClass = this.onTableRowClassName({ tableConfig, record })
            const crossClass = index % 2 === 1 ? 'dark-row' : 'light-row'
            if (remoteClass) {
              return classNames(styles[remoteClass]);
            }
            return classNames(styles[crossClass])
          }}
          expandedRowRender={(tableConfig.hasChildren ? (record) => {
            return this.onRenderTableSubRow({ record, tableCode, tableConfig });
          } : null)}
          expandIcon={(props) => {
            if (!props.expandable) return null
            if (props.expanded) {
              return <Icon type="up" onClick={e => props.onExpand(props.record, e)} />
            } else {
              return <Icon type="down" onClick={e => props.onExpand(props.record, e)} />
            }
          }}
          expandedRowKeys={this.state.expandedRowKeysChanged ? this.state.expandedRowKeys : defaultExpandedRowKeys}
          onExpand={(expanded, record) => {
            this.onTableExpandRow({ tableCode, tableConfig, record, expanded })
          }}
          onExpandedRowsChange={expandedRowKeys => {
            this.setState({
              expandedRowKeysChanged: true,
              expandedRowKeys
            })
          }}
          footer={hasFooter() ? (data) => {
            return this.onRenderTableFooter({
              tableCode,
              tableConfig,
              selectedRowKeys: selectKeys,
              data,
              columns: tableConfig.columns
            });
          } : null}
          bordered
          {...isScrollX()}
          {...dragableProps}
        >
          {
            newColumns && newColumns.map((h, index) => {
              return (
                <Column
                  {...h}
                  onCell={() => {
                    return {
                      onDoubleClick: (e) => {
                        e.preventDefault();
                        e.stopPropagation()
                        if (h.title) {
                          openNotification(h);
                        }
                      }
                    }
                  }}
                  onHeaderCell={column => {
                    return {
                      onMouseEnter: () => { // 鼠标移入表头单元格
                        this.setState({
                          showColumnSetting: column.key
                        })
                      },
                      width: column.width,
                      onResize: this.handleResize(tableCode, column)
                    };
                  }}
                />
              )
            })
          }
          {!isBatchAddList ? this.tableOperateColumn(tableCode) : null}
        </Table>
      </div>
    </React.Fragment>
  }

  handleTableCardSelect = (evt, item, tableCode) => {
    const selectKeys = cloneDeep(this.getTableSelectedRowKeys({ tableCode }))
    if (evt.target.checked) {
      this.onSelectTableChange(tableCode, [item.ID].concat(selectKeys), [item])
    } else {
      const findIndex = selectKeys.findIndex(sel => sel === item.ID)
      if (findIndex !== -1) {
        selectKeys.splice(findIndex, 1)
        this.onSelectTableChange(tableCode, selectKeys, [])
      }
    }
  }

  /*
   * 渲染卡片式表格
   */
  getRenderTableCard(tableCode) {
    if (tableCode === undefined) tableCode = this.defaultTableCode
    let tableConfig = this.getTableConfig({ tableCode })
    if (!tableConfig) return null;

    let loadParam = this.getLoadParam({ tableCode });
    let tableData = this.getTableData({ tableCode });
    loadParam = loadParam || { PageIndex: 1, IsAllLoad: false, Limit: 10 };
    tableData = tableData || { TotalCount: 0 };

    const newColumns = this.getColumnByColumnConfig(tableCode) // 表头字段
    const tableDataSource = this.genDataSource(tableCode, tableData)
    const selectKeys = this.getTableSelectedRowKeys({ tableCode })
    const paginationConfig = {
      pageSizeOptions: ['5', '10', '20','100'],
      current: loadParam ? loadParam.PageIndex : 1,
      pageSize: loadParam ? (loadParam.IsAllLoad ? loadParam.ShowLimit : loadParam.Limit) : 10,
      total: tableData ? tableData.TotalCount : 0,
      showSizeChanger: true,
      showQuickJumper: true,
      size: 'small',
      position: (tableConfig.position ? tableConfig.position : 'bottom'),
      showTotal: () => `共 ${tableData ? tableData.TotalCount : 0} 条`
    }

    let isLoading = this.props.loading ? this.props.loading.effects["listPage/getTableData"] : false;
    if (!isLoading) {
      isLoading = this.state.formLoading
    }
    const isBatchAddList = this.props.data && this.props.data.btnTypeBatchAdd
    const TableHeadBtns = this.getRenderBtns(tableCode, tableConfig, null, tableConfig.btns, 1)

    const WrapComponent = tableConfig.dragable ? DragDropCard : React.Fragment

    return <React.Fragment>
      <IFComponent
        IF={!!isBatchAddList}
        ELSE={
          <IFComponent IF={TableHeadBtns && TableHeadBtns.length}>
            <div className={styles.tableBtnBar}>{TableHeadBtns}</div>
          </IFComponent>
        }
      >
        <div className={styles.tableBtnBar}>
          <Button type="primary" onClick={() => this.handleBatchAddSave(tableCode)}>保存</Button>
        </div>
      </IFComponent>
      <div style={{ textAlign: 'center' }}>
        <Spin spinning={isLoading} wrapperClassName={styles.tableCardSpin}>
          {
            tableDataSource.map((ds, dsIndex) => {
              const actionBtns = this.getRenderBtns(tableCode, tableConfig, ds, tableConfig.rowBtns, 0)
              const thumbCode = get(ds, tableConfig.cardPicField)
              return (
                <WrapComponent
                  row={ds}
                  index={dsIndex}
                  moveRow={(dragIndex, hoverIndex) => this.moveRow(dragIndex, hoverIndex, tableCode, tableConfig)}
                >
                  <div key={ds.ID} className={styles.tableCard}>
                    <IFComponent IF={!!tableConfig.checked}>
                      <Checkbox
                        checked={selectKeys.indexOf(ds.ID) !== -1}
                        onChange={evt => this.handleTableCardSelect(evt, ds, tableCode)}
                        className={styles.tableCardCheckbox}
                      />
                    </IFComponent>
                    {
                      newColumns.map(col => {
                        return (
                          <div key={col.key} className={styles.tableCardZone}>
                            <span>{col.title}</span>
                            <span>：</span>
                            <span>{col.render ? col.render(ds[col.dataIndex], ds) : ds[col.dataIndex]}</span>
                          </div>
                        )
                      })
                    }
                    <IFComponent IF={!isBatchAddList}>
                      <div className={styles.tableCardZone}>
                        <span>操作：</span>
                        <div
                          className={styles.actionTd}
                          style={{ width: actionBtns.length ? actionBtns.length * 22 : 'auto' }}
                        >
                          {actionBtns}
                        </div>
                      </div>
                    </IFComponent>
                    <IFComponent IF={!!thumbCode}>
                      <div className={styles.tableCardPic}>
                        <PictureThumb
                          thumbCodes={[thumbCode]}
                          thumbConfigs={[{ target: thumbCode }]}
                          style={{ maxWidth: 120 }}
                        />
                      </div>
                    </IFComponent>
                  </div>
                </WrapComponent>
              )
            })
          }
        </Spin>
        <Pagination
          onChange={(current, pageSize) => {
            this.onTableChange(tableCode, { ...paginationConfig, current, pageSize })
          }}
          onShowSizeChange={(current, pageSize) => {
            this.onTableChange(tableCode, { ...paginationConfig, current, pageSize })
          }}
          {...paginationConfig}
        />
      </div>
    </React.Fragment>
  }
}

export default TableBaseComponent;
