/*
 * Create:      柿子
 * CreateDate:  2022/10/26
 * Describe：   父子表操作 - 父子表增删改查公共组件
 * */
import React, { Component } from 'react';
import { Row, Col, Tooltip, Button, Card, message, Popconfirm, Divider, Icon } from 'antd';
import { Util } from 'tools';
import store from 'store';
import PublicTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import iconListVisits from 'assets/images/icon_listvisits.png';
import './style/index.less';

class ParentChildTableOperation extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      category: '',
      categoryData: {},
      selectData: {},
      spinLoading: false,
      mainColumns: [], // 主表表头数据
      mainTotalWidth: 300,
      mainQueryFormData: [], // 主表查询表单数据
      isDateRange: false,
      clientQueryHeight: 0,
      mainCardDesc: '', // 主card描述
      mainTableData: [],
      mainFormData: [], // 主表表单数据
      mainTotal: 0,
      mainPage: 1,
      mainPageSize: 10,
      mainLoading: false,
      mainRowID: '',
      mainRowData: {},
      mainSaveRecord: {},
      detailCardDesc: '', // 主card描述
      detailColumns: [],
      detailTotalWidth: 300,
      detailTableData: [],
      detailFormData: [], // 明细表单数据
      detailTotal: 0,
      detailPage: 1,
      detailPageSize: 10,
      detailLoading: false,
      detailSaveData: {},
      detailRowID: '',
      detailQueryFormData: []
    };
  }

  componentDidMount() {
    let newCategory;
    if ('paras' in this.props && this.props.paras && this.props.paras.params) { // 侧菜单获取类别参数
      newCategory = this.props.paras.params;
    } else {
      if ('location' in this.props && this.props.location.state && this.props.location.state.params) { // 头菜单获取类别参数
        newCategory = this.props.location.state.params;
        React.$setSessionData('ParentChildTableOperation', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('ParentChildTableOperation', false);
      }
    }
    console.log('ParentChildTableOperation', newCategory);
    let categoryData = Util.getObjByUrlStr(newCategory);
    let defaultPageSize = categoryData?.paginationSize === 'large' ? (categoryData?.defaultPageSize || 50) : (categoryData?.defaultPageSize || 10); // 默认条数
    let defaultDetailPageSize = categoryData?.detailPaginationSize === 'large' ? (categoryData?.defaultDetailPageSize || 50) : (categoryData?.defaultDetailPageSize || 10); // 明细列表默认条数
    this.setState({ category: newCategory, categoryData, spinLoading: true, mainPageSize: defaultPageSize, detailPageSize: defaultDetailPageSize }, () => {
      this.getSelectData();
    });
  }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 请求下拉数据
  getSelectData = async () => {
    try {
      let { categoryData, userData } = this.state;
      if (!(categoryData?.selectCode)) {
        this.handleInit();
        return;
      };
      let data = {
        params: [{
          hospID: userData?.hospID || ''
        }],
      }
      let res = await React.$asyncPost(this, categoryData.selectCode, data);
      this.setState({ selectData: res && 'result' in res ? res.result : res }, () => {
        this.handleInit();
      });
    } catch (error) {
      console.log(error);
      this.setState({ selectData: {} }, () => {
        this.handleInit();
      });
    }
  }

  handleInit = () => {
    this.getColumnsData();
    this.getDetailColumnsData();
    this.getMainFormData();
    this.getDetailFormData();
  }

  // 获取表头数据
  getColumnsData = async () => {
    try {
      const { categoryData } = this.state;
      if (!(categoryData?.componentName)) {
        this.setState({ spinLoading: false });
        return;
      };
      let data = {
        params: [{
          type: 'C',
          compontName: categoryData.componentName,
          reactCode: [categoryData.componentName],
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let nIsDateRange = false;
      let nColumns = res.result && res.result.C && Array.isArray(res.result.C) ? res.result.C.map((item) => {
        return {
          ...item,
          render: (text, record) => {
            let brData = text && typeof (text) === 'string' && text.indexOf('<br>') > -1 ? text.split('<br>') : (text ? [text] : []);
            return (
              <Tooltip title={text && typeof (text) === 'string' && text.indexOf('<br>') > -1 ? text.replace(/<br>/g, '') : (text || '')}>
                <div>
                  {brData && brData.map((item, index) => {
                    return <div key={index} className="ellipsis" style={{ width: '100%' }}>{item}</div>
                  })}
                </div>
              </Tooltip>
            )
          }
        }
      }) : [];
      if (nColumns && nColumns.length > 0) {
        this.setState({ mainColumns: nColumns, mainTotalWidth: res.totalWidth });
      }
      let nFormData = res.result?.formData || [];
      for (var i = 0; i < nFormData.length; i++) {
        if (nFormData[i].typeCode === 'RangePicker') {
          nIsDateRange = true;
        }
      }
      this.setState({ isDateRange: nIsDateRange, mainQueryFormData: nFormData, spinLoading: false, mainCardDesc: res?.mainInf?.descripts || '' }, () => {
        if (this.state.mainQueryFormData && this.state.mainQueryFormData.length > 0) {
          let clientQueryDom = document.getElementById('pct-header-query');
          this.setState({ clientQueryHeight: clientQueryDom?.clientHeight || 64 });
        }
        this.getMainTableData();
      });
    } catch (error) {
      // 主表表头数据
      let mainColumns = [{
        key: 1,
        title: '代码',
        dataIndex: 'code',
        align: 'center',
        width: '100px'
      }, {
        key: 2,
        title: '描述',
        dataIndex: 'descripts',
        align: 'center',
        width: '100px'
      }, {
        key: 3,
        title: '英文描述',
        dataIndex: 'eNDesc',
        align: 'center',
        width: '100px'
      }];
      this.setState({ mainColumns, spinLoading: false });
    }
  }

  // 获取表单数据
  getMainFormData = async () => {
    try {
      const { categoryData } = this.state;
      if (!categoryData?.addCode && !categoryData?.editCode) { // 没有新增和编辑不走表单数据请求
        return;
      }
      let componentName = categoryData?.componentName || '';
      let componentNameForm = categoryData?.componentNameForm || '';
      let formName = componentNameForm || componentName + 'Form';
      if (!formName) return;
      let data = {
        params: [{
          type: 'C',
          compontName: formName,
          reactCode: [formName],
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let mainFormData = res.result?.formData || [];
      this.setState({ mainFormData });
    } catch (error) {
      console.log(error);
    }
  }

  handleQuery = () => {
    this.setState({ mainPage: 1 }, () => {
      this.getMainTableData();
    })
  }

  // 提供修改page和pageSize的回调函数
  handleCompilePage = (page, pageSize) => {
    // 修改page，或者pageSize
    this.setState({ mainPage: page, mainPageSize: pageSize }, () => {
      // 重新调用查询方法
      this.getMainTableData();
    })
  }

  // 请求列表数据
  getMainTableData = async () => {
    try {
      const { categoryData, mainPage, mainPageSize } = this.state;
      let recordID = categoryData?.recordID || 'id';
      if (!(categoryData?.queryCode)) return;
      let values = await this.formRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ mainLoading: true });
      let data = {
        params: [{
          ...values,
          error: undefined
        }],
      };
      if (categoryData?.paginationHideFlag !== 'Y') { // 是否展示分页
        data.pagination = [{
          pageSize: mainPageSize,
          currentPage: mainPage,
        }]
      }
      let res = await React.$asyncPost(this, categoryData.queryCode, data);
      this.setState({ mainTableData: React.$processingTableRequestData(res, recordID), mainTotal: res.result?.total || res.result?.totalCount || res.result?.TotalCount || 0, mainLoading: false }, () => {
        this.handleClearData();
      });
    } catch (error) {
      this.setState({ mainTableData: [], mainTotal: 0, mainLoading: false }, () => {
        this.handleClearData();
      });
    }
  }

  // 新增
  handleAdd = () => {
    let { mainSaveRecord, categoryData } = this.state;
    let rowID = categoryData?.recordID || 'id';
    if (mainSaveRecord && rowID in mainSaveRecord && mainSaveRecord[rowID]) {
      this.setState({ mainSaveRecord: {} })
    }
    this.mainModalRef && this.mainModalRef.modifyVisible(true);
  }

  // 编辑
  handleModify = (record, e) => {
    this.handleStopPropagation(e);
    this.setState({ mainSaveRecord: record }, () => {
      this.mainModalRef && this.mainModalRef.modifyVisible(true);
    })
  }

  // 删除
  handleDelete = async (record, e) => {
    try {
      this.handleStopPropagation(e);
      const { categoryData } = this.state;
      let rowID = categoryData?.recordID || 'id';
      if (!(categoryData?.deleteCode)) return;
      let data = {
        params: [{
          [rowID]: record[rowID]
        }]
      }
      let res = await React.$asyncPost(this, categoryData.deleteCode, data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      // 刷新列表数据
      getMainTableData();
    } catch (error) {
      console.log(error);
    }
  }

  // 记录表单的值
  recordMainFormInput = record => {
    this.setState({ mainSaveRecord: { ...this.state.mainSaveRecord, ...record } })
  }

  // 主表保存
  handleMainSave = async values => {
    try {
      let { mainSaveRecord, categoryData } = this.state;
      let addCode = categoryData?.addCode || '';
      let editCode = categoryData?.editCode || '';
      let rowID = categoryData?.recordID || 'id';
      let saveCode = mainSaveRecord[rowID] && editCode ? editCode : addCode; // 当为编辑并且编辑代码存在的时候取editCode，正常新增编辑同一个接口取addCode
      if (!saveCode) return;
      let data = {
        params: [{
          ...values,
          [rowID]: mainSaveRecord[rowID],
          error: undefined
        }]
      }
      let res = await React.$asyncPost(this, saveCode, data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.mainModalRef && this.mainModalRef.modifyVisible(false, 'Y');
      this.setState({ mainSaveRecord: {} }, () => {
        this.getMainTableData();
      });
    } catch (error) {
      console.log(error)
    }
  }

  // 操作行
  onClickRowPublic = (record) => {
    const { categoryData } = this.state;
    let rowID = categoryData?.recordID || 'id';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.mainRowID === '' || (this.state.mainRowID && (this.state.mainRowID !== record[rowID]))) {
          this.setState({ mainRowID: record[rowID], mainRowData: record }, () => {
            this.getDetailTableData();
          });
        } else {
          this.handleClearData();
        }
      }
    }
  }

  // 清除数据
  handleClearData = () => {
    this.setState({ mainRowID: '', mainRowData: {}, detailTableData: [] });
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    const { categoryData } = this.state;
    let rowID = categoryData?.recordID || 'id';
    return record[rowID] === this.state.mainRowID ? 'clickRowStyle' : '';
  }

  // 提供修改page和pageSize的回调函数
  handleDetailCompilePage = (page, pageSize) => {
    // 修改page，或者pageSize
    this.setState({ detailPage: page, detailPageSize: pageSize, detailLoading: true }, () => {
      // 重新调用查询方法
      this.getDetailTableData();
    })
  }

  // 获取主表表单数据
  getDetailColumnsData = async () => {
    try {
      const { categoryData } = this.state;
      let mainComponentName = categoryData?.componentName || '';
      let childComponentName = categoryData?.childComponentName || '';
      let componentName = childComponentName ? childComponentName : (mainComponentName + 'Detail');
      if (!componentName) {
        this.setState({ spinLoading: false });
        return;
      };
      let data = {
        params: [{
          type: 'C',
          compontName: componentName,
          reactCode: [componentName],
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let nColumns = res.result && res.result.C && Array.isArray(res.result.C) ? res.result.C.map((item) => {
        return {
          ...item,
          render: (text, record) => {
            let brData = text && typeof (text) === 'string' && text.indexOf('<br>') > -1 ? text.split('<br>') : (text ? [text] : []);
            return (
              <Tooltip title={text && typeof (text) === 'string' && text.indexOf('<br>') > -1 ? text.replace(/<br>/g, '') : (text || '')}>
                <div>
                  {brData && brData.map((item, index) => {
                    return <div key={index} className="ellipsis" style={{ width: '100%' }}>{item}</div>
                  })}
                </div>
              </Tooltip>
            )
          }
        }
      }) : [];
      if (nColumns && nColumns.length > 0) {
        this.setState({ detailColumns: nColumns, detailTotalWidth: res.totalWidth });
      }
      let nFormData = res.result?.formData || [];
      this.setState({ detailQueryFormData: nFormData, detailCardDesc: res?.mainInf?.descripts || '' });
    } catch (error) {
      // 明细表头数据
      let detailColumns = [{
        key: 1,
        title: '代码',
        dataIndex: 'code',
        align: 'center',
        width: '100px'
      }, {
        key: 2,
        title: '描述',
        dataIndex: 'descripts',
        align: 'center',
        width: '100px'
      }, {
        key: 3,
        title: '英文描述',
        dataIndex: 'eNDesc',
        align: 'center',
        width: '100px'
      }];
      this.setState({ detailColumns, spinLoading: false });
    }
  }

  // 获取明细表单数据
  getDetailFormData = async () => {
    try {
      const { categoryData } = this.state;
      if (!categoryData?.childAddCode && !categoryData?.childEditCode) { // 没有新增和编辑不走表单数据请求
        return;
      }
      let mainComponentName = categoryData?.componentName || '';
      let childComponentName = categoryData?.childComponentName || '';
      let childComponentNameForm = categoryData?.childComponentNameForm || '';
      let formName = childComponentNameForm || (childComponentName ? (childComponentName + 'Form') : mainComponentName + 'DetailForm');
      if (!formName) return;
      let data = {
        params: [{
          type: 'C',
          compontName: formName,
          reactCode: [formName],
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let detailFormData = res.result?.formData || [];
      this.setState({ detailFormData });
    } catch (error) {
      console.log(error);
    }
  }

  handleDetailQuery = () => {
    this.setState({ detailPage: 1 }, () => {
      this.getDetailTableData();
    })
  }

  // 获取明细列表数据
  getDetailTableData = async () => {
    try {
      const { categoryData, mainRowID, detailPage, detailPageSize } = this.state;
      let rowID = categoryData?.recordID || 'id';
      if (!(categoryData?.childQueryCode)) {
        message.error('请维护查询明细接口!');
        return;
      };
      let values = await this.detailFormRef.handleSave();
      if (values.error) {
        message.error('请完善必填信息');
        return;
      }
      this.setState({ detailLoading: true });
      let data = {
        params: [{
          [rowID]: mainRowID,
          ...values
        }]
      }
      if (categoryData?.detailPaginationHideFlag !== 'Y') {
        data.pagination = [{
          pageSize: detailPageSize,
          currentPage: detailPage,
          sortColumn: 'Code',
          sortOrder: 'asc'
        }]
      }
      let res = await React.$asyncPost(this, categoryData.childQueryCode, data);
      this.setState({ detailTableData: React.$processingTableRequestData(res), detailTotal: res.result?.total || res.result?.totalCount || res.result?.TotalCount || 0, detailLoading: false });
    } catch (error) {
      this.setState({ detailTableData: [], detailTotal: 0, detailLoading: false });
    }
  }

  // 记录表单的值
  recordDetailFormInput = record => {
    this.setState({ detailSaveData: { ...this.state.detailSaveData, ...record } });
  }

  // 添加明细
  handleDetailAdd = () => {
    let { mainRowID, detailSaveData, categoryData } = this.state;
    if (mainRowID === '') {
      message.info("请选中一条主记录后再添加！")
      return
    }
    let rowDetailID = categoryData?.childRecordID || 'id';
    if (detailSaveData && rowDetailID in detailSaveData && detailSaveData[rowDetailID]) {
      this.setState({ detailSaveData: {} });
    }
    this.detailModalRef && this.detailModalRef.modifyVisible(true);
  }

  // 编辑
  handleDetailModify = (record, e) => {
    this.setState({ detailSaveData: record }, () => {
      this.detailModalRef && this.detailModalRef.modifyVisible(true);
    })
  }

  // 明细保存
  handleDetailSave = async values => {
    try {
      let { categoryData, mainRowID, detailSaveData } = this.state;
      let rowID = categoryData?.recordID || 'id';
      let childAddCode = categoryData?.childAddCode || '';
      let childEditCode = categoryData?.childEditCode || '';
      let childRecordID = categoryData?.childRecordID || '';
      let rowDetailID = childRecordID || 'id';
      let saveCode = detailSaveData[childRecordID] && childEditCode ? childEditCode : childAddCode; // 当为编辑并且编辑代码存在的时候取editCode，正常新增编辑同一个接口取addCode
      if (!rowID || !rowDetailID || !saveCode) return;
      let data = {
        params: [{
          ...values,
          [rowDetailID]: detailSaveData[rowDetailID] || '',
          [rowID]: mainRowID
        }]
      }
      let res = await React.$asyncPost(this, saveCode, data);
      message.success(res.errorMessage ? res.errorMessage : '保存成功');
      this.detailModalRef && this.detailModalRef.modifyVisible(false, 'Y');
      this.setState({ detailSaveData: {} }, () => {
        this.getDetailTableData();
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 点击删除时阻止事件冒泡
  handleStopPropagation = (e) => {
    e?.stopPropagation();
  }

  // 明细删除
  handleDetailDelete = async (record, e) => {
    try {
      let { categoryData } = this.state;
      let childDeleteCode = categoryData?.childDeleteCode || '';
      let rowDetailID = categoryData?.childRecordID || 'id';
      if (!(record && rowDetailID in record && record[rowDetailID]) || !childDeleteCode) return;
      let data = {
        params: [{
          [rowDetailID]: record[rowDetailID]
        }]
      }
      let res = await React.$asyncPost(this, childDeleteCode, data);
      message.success(res.errorMessage ? res.errorMessage : '删除成功');
      this.getDetailTableData();
    } catch (error) {
      console.log(error)
    }
  }

  handleDetailRowClick = (record) => {
    const { categoryData } = this.state;
    let detailRowID = categoryData?.childRecordID || 'id';
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record[detailRowID]))) {
          this.setState({ detailRowID: record[detailRowID] });
        } else {
          this.setState({ detailRowID: '' });
        }
      }
    }
  }

  handleDetailSetRowClassName = (record) => {
    const { categoryData } = this.state;
    let detailRowID = categoryData?.childRecordID || 'id';
    return categoryData?.childRowClick === 'Y' && record[detailRowID] === this.state.detailRowID ? 'clickRowStyle' : '';
  }

  render() {
    let { category, categoryData, clientQueryHeight, mainColumns, mainTotalWidth, mainQueryFormData, mainFormData, mainSaveRecord, mainTableData, mainTotal, mainPage, mainLoading, detailColumns, detailTotalWidth, detailTableData, detailTotal, detailPage,
      detailLoading, detailFormData, detailSaveData, mainCardDesc, detailCardDesc, selectData, detailQueryFormData
    } = this.state;
    let mainAddCode = Util.getValueByUrlStr(category, 'addCode');
    let mainEditCode = Util.getValueByUrlStr(category, 'editCode');
    let mainDeleteCode = Util.getValueByUrlStr(category, 'deleteCode');
    let componentName = Util.getValueByUrlStr(category, 'componentName');
    let mainOperationWidth = mainAddCode && mainDeleteCode ? 130 : (mainAddCode || mainEditCode ? 80 : 0)
    let detailAddCode = Util.getValueByUrlStr(category, 'childAddCode');
    let detailEditCode = Util.getValueByUrlStr(category, 'childEditCode');
    let detailDeleteCode = Util.getValueByUrlStr(category, 'childDeleteCode');
    let detailOperationWidth = detailAddCode && detailDeleteCode ? 130 : (detailAddCode || detailEditCode ? 80 : 0)
    let nMainQueryFormData = mainQueryFormData && mainQueryFormData.length > 0 ? [...mainQueryFormData, {
      col: 2,
      title: '查询',
      typeCode: 'Button',
      marginBottom: 12,
      onClick: () => this.handleQuery(),
    }] : [];

    let nDetailQueryFormData = detailQueryFormData && detailQueryFormData.length > 0 ? [...detailQueryFormData, {
      col: 2,
      title: '查询',
      typeCode: 'Button',
      marginBottom: 12,
      onClick: () => this.handleDetailQuery(),
    }] : [];

    // 主表操作信息
    let mainOperation = {
      key: 'operation',
      title: '操作',
      align: 'center',
      fixed: 'right',
      dataIndex: 'operation',
      width: mainOperationWidth,
      render: (text, record) => {
        return (
          <span>
            {categoryData?.addCode || categoryData?.editCode !== 'none' ? (
              <>
                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                <span className="span" onClick={(e) => this.handleModify(record, e)}>编辑</span>
              </>
            ) : ''}
            {/* 分割线 */}
            {mainDeleteCode ? (
              <>
                <Divider type="vertical" />
                <Icon type="delete" className="common-record-delete-span"></Icon>
                <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handleStopPropagation} onClick={this.handleStopPropagation} onConfirm={(e) => handleDelete(record, e)} >
                  <span className="span common-record-delete-span">删除</span>
                </Popconfirm>
              </>
            ) : ''}
          </span >
        )
      }
    }

    // 组件所需参数
    const mainParams = {
      loading: mainLoading,
      // 当前页数
      page: categoryData?.paginationHideFlag !== 'Y' && mainPage,
      pageSize: categoryData?.defaultPageSize || '',
      // 表格数据
      data: mainTableData,
      // 数据总条数
      total: categoryData?.paginationHideFlag !== 'Y' && mainTotal,
      // 表头配置
      columns: mainOperationWidth ? [...mainColumns, mainOperation] : mainColumns,
      // 表格的宽度
      x: mainTotalWidth,
      y: store.getState().tableHeight.y + 94 - clientQueryHeight,
      height: store.getState().tableHeight.y + 144 - clientQueryHeight + 'px',
      componentName,
    };

    // 明细表操作信息
    let detailOperation = {
      key: 'operation',
      title: '操作',
      align: 'center',
      fixed: 'right',
      dataIndex: 'operation',
      width: detailOperationWidth,
      render: (text, record) => {
        return (
          <span>
            {detailAddCode || detailEditCode !== 'none' ? (
              <>
                <Icon type="edit" style={{ color: '#108EE9' }}></Icon>
                <span className="span" onClick={(e) => this.handleDetailModify(record, e)}>编辑</span>
              </>
            ) : ''}
            {detailDeleteCode ? (
              <>
                <Divider type="vertical" />
                <Icon type="delete" className="common-record-delete-span"></Icon>
                <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handleStopPropagation} onClick={this.handleStopPropagation} onConfirm={(e) => this.handleDetailDelete(record, e)} >
                  <span className="span common-record-delete-span">删除</span>
                </Popconfirm>
              </>
            ) : ''}
          </span >
        )
      }
    }

    const detailParams = {
      loading: detailLoading,
      // 当前页数
      page: categoryData?.detailPaginationHideFlag !== 'Y' && detailPage,
      pageSize: categoryData?.defaultDetailPageSize || '',
      // 表格数据
      data: detailTableData,
      // 数据总条数
      total: categoryData?.detailPaginationHideFlag !== 'Y' && detailTotal,
      // 表头配置
      columns: detailOperationWidth ? [...detailColumns, detailOperation] : detailColumns,
      x: detailTotalWidth,
      y: store.getState().tableHeight.y + (nDetailQueryFormData && nDetailQueryFormData.length > 0 || detailAddCode ? 50 : 94),
      height: store.getState().tableHeight.y + (nDetailQueryFormData && nDetailQueryFormData.length > 0 || detailAddCode ? 100 : 144) + 'px',
      componentName: categoryData?.childComponentName || (componentName + 'Detail'),
    };
    return (
      <div className="dynamic-component parent-child-table">
        <Row>
          <Col span={parseInt(categoryData?.leftCardCol || 12)}>
            <div style={{ paddingRight: '8px', position: 'relative' }}>
              <Card
                size="small"
                bordered={false}
                title={
                  <div className='card-title-left-img'>
                    <img src={iconListVisits} alt='' />
                    {categoryData?.cardDesc || mainCardDesc || '主列表'}
                  </div>
                }
              >
                <div className='table-body-height'>
                  <Row id="pct-header-query">
                    <Col span={20}>
                      <DynamicRenderingForm
                        rowData={{}}
                        className="dynamic-component-form"
                        onRef={ref => this.formRef = ref}
                        selectData={selectData}
                        formData={nMainQueryFormData && nMainQueryFormData.map((item => {
                          return {
                            ...item,
                            onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
                          }
                        }))}
                      />
                    </Col>
                    <Col span={4} style={{ textAlign: 'right' }}>
                      {mainAddCode ? (
                        <Button
                          icon="plus"
                          className="add-btn add-btn-noHover"
                          onClick={this.handleAdd}
                        >
                          新增
                        </Button>
                      ) : ''}
                    </Col>
                  </Row>
                  <PublicTablePagination
                    param={mainParams}
                    getColumns={this.getColumnsData}
                    compilePage={this.handleCompilePage}
                    onClickRowPublic={this.onClickRowPublic}
                    setRowClassNamePublic={this.setRowClassNamePublic}
                  />
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={parseInt(categoryData?.rightCardCol || 12)}>
            <Card
              size="small"
              bordered={false}
              title={
                <div className="card-title-left-img">
                  <img src={iconListVisits} alt='' />
                  {detailCardDesc || categoryData?.childCardDesc || '明细列表'}
                </div>
              }
            >
              <div className="table-body-height">
                <Row style={{ display: nDetailQueryFormData && nDetailQueryFormData.length > 0 || detailAddCode ? 'block' : 'none' }} id="pct-detail-header-query">
                  <Col span={20}>
                    <DynamicRenderingForm
                      rowData={{}}
                      className="dynamic-component-form"
                      onRef={ref => this.detailFormRef = ref}
                      selectData={selectData}
                      formData={nDetailQueryFormData && nDetailQueryFormData.map((item => {
                        return {
                          ...item,
                          onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleDetailQuery : ''
                        }
                      }))}
                    />
                  </Col>
                  <Col span={4} style={{ textAlign: 'right' }}>
                    {detailAddCode ? (
                      <Button
                        icon="plus"
                        className="add-btn add-btn-nohover"
                        onClick={this.handleDetailAdd}
                      >新增</Button>
                    ) : ''}
                  </Col>
                </Row>
                <PublicTablePagination
                  param={detailParams}
                  getColumns={this.getDetailColumnsData}
                  compilePage={this.handleDetailCompilePage}
                  onClickRowPublic={this.handleDetailRowClick}
                  setRowClassNamePublic={this.handleDetailSetRowClassName}
                />
              </div>
            </Card>
          </Col>
        </Row>

        {/* 主表新增弹窗 */}
        <PublicModalFormHooks
          idField={categoryData?.recordID}
          onRef={ref => this.mainModalRef = ref}
          formData={mainFormData}
          selectData={selectData}
          rowData={mainSaveRecord}
          recordFormInput={this.recordMainFormInput}
          handleSave={this.handleMainSave}
        />

        {/* 明细新增弹窗 */}
        <PublicModalFormHooks
          idField={categoryData?.childRecordID}
          onRef={ref => this.detailModalRef = ref}
          formData={detailFormData}
          rowData={detailSaveData}
          selectData={selectData}
          recordFormInput={this.recordDetailFormInput}
          handleSave={this.handleDetailSave}
        />
      </div>
    )
  }
};

export default ParentChildTableOperation;
// 医院组维护配置参数示例 - params=interfaceType:parentChildTable&selectCode:01040252&componentName:HospitalGroupMaintenance&queryCode:01040253&childQueryCode:01040255&addCode:01040254&childAddCode:01040256&deleteCode:01040258&childDeleteCode:01040257&recordID:hospGroupID&childRecordID:hospGroupLinkID&childComponentNameForm:HospitalGroupMDetailForm&cardDesc:医院组列表&childCadDesc:医院组详细列表&childRowClick:Y