/*
 * Create:      柿子
 * CreateDate:  2023/01/23
 * Describe：   左右结构查询报表 - 公共报表组件
 * */
import React, { Component } from 'react';
import { Card, Row, Col, Spin, message, Button, Empty } from 'antd';
import { Util } from 'tools';
import store from 'store';
import Reports from 'pages/raqSoft/reportsEmbed';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import GetPatientInformation from 'pages/optometry/component/GetPatientInformation';
import iconListVisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import './style/index.less';

class LeftConditionRightReports extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      userData,
      categoryData: {},
      selectData: {},
      queryFormData: [],
      spinLoading: true,
      reportParam: {}, // 报表入参
      raqName: '',
      reportTypeDataIndex: '', // 报表类型下拉框数据索引
    };
  }

  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('LeftConditionRightReports', newCategory, false);
      } else { // 头菜单刷新界面时获取类别
        newCategory = React.$getSessionData('LeftConditionRightReports', false);
      }
    }
    let categoryData = Util.getObjByUrlStr(newCategory);
    this.setState({ categoryData }, () => {
      this.getSelectData();
      this.getTableColumns('Y');
    });
  };

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

  // 获取下拉框数据
  getSelectData = async () => {
    try {
      let { categoryData, userData } = this.state;
      if (!(categoryData && categoryData.selectCode)) {
        return
      };
      let data = {
        params: [{
          hospID: userData?.hospID || '',
          status: categoryData?.groupType || undefined, // 界面标识
          groupType: categoryData?.groupType || undefined, // 界面标识
          componentName: categoryData?.componentName || undefined, // 组件名
        }]
      }
      let res = await React.$asyncPost(this, categoryData.selectCode, data);
      this.setState({ selectData: res.result });
    } catch (error) {
      console.log(error);
    }
  };

  // 获取表头数据
  getTableColumns = async (isQuery) => {
    try {
      const { categoryData } = this.state;
      if (!(categoryData && categoryData.componentName)) {
        message.error('列表数据还未配置呢，快去配置先！');
        this.setState({ spinLoading: false });
        return;
      }
      let data = {
        params: [{
          compontName: categoryData.componentName,
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let nFormData = res.result?.formData || [];
      let reportTypeDataIndex = Util.returnDataCccordingToAttributes(nFormData, 'reportType', 'className')?.dataIndex || 'reportType';
      console.log('reportTypeDataIndex', reportTypeDataIndex)
      this.setState({ queryFormData: nFormData, spinLoading: false, reportTypeDataIndex }, () => {
        if (isQuery === 'Y') { // 自动查询标志
          // 解决没有取到默认值问题
          setTimeout(() => {
            this.handleQuery();
          }, 300)
        }
      });
    } catch (error) {
      console.log(error)
      this.setState({ spinLoading: false }, () => {
        if (isQuery === 'Y') { // 自动查询标志
          setTimeout(() => {
            this.handleQuery();
          }, 300)
        }
      });
    }
  };

  // 查询
  handleQuery = async () => {
    let values = await this.queryFormRef.handleSave();
    if (values.error) {
      message.error('请完善必填信息');
      return;
    }
    let { reportTypeDataIndex, raqName } = this.state;
    let patientInfo = this.patientRef && this.patientRef.getPatientInfo();
    if (reportTypeDataIndex && reportTypeDataIndex in values && values[reportTypeDataIndex]) { // 获取报表类型
      raqName = values[reportTypeDataIndex];
    }
    this.setState({ raqName, reportParam: { ...values, ...patientInfo } });
  };

  // 清除操作数据
  handleClearSelectData = () => {
    this.setState({ rowID: '', rowData: {} });
  };

  // 重置
  handleReset = () => {
    this.queryFormRef && this.queryFormRef.resetFields();
    this.patientRef && this.patientRef.resetFields();
    this.handleClearSelectData();
  };

  render() {
    const { categoryData, queryFormData, selectData, reportParam, spinLoading, raqName } = this.state;

    let currentRapName = raqName || categoryData?.raqName || '';
    return (
      <Spin tip="正在初始化界面数据……" spinning={spinLoading}>
        <Row className="dynamic-component left-condition-right-list">
          <Col span={5}>
            <div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                bodyStyle={{ paddingRight: '16px' }}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    {categoryData?.cardTitle || '搜索条件'}
                  </div>
                )}
              >
                <div className="scroll-bar-style" style={{ height: store.getState().tableHeight.y + 182 + 'px', overflow: 'auto', paddingTop: '4px' }}>
                  {categoryData?.queryPatInfoFlag === 'Y' ? (
                    <GetPatientInformation
                      isEnter="Y"
                      enterMargin="14px 0"
                      patWidth="75%"
                      parLabelClass="lcrl-input-label"
                      queryType="fuzzySearch"
                      cardType={selectData?.defaultValue?.defaultCardType || undefined}
                      cardSelectData={selectData?.cardType || []}
                      onRef={ref => this.patientRef = ref}
                      handleQuery={this.handleQuery}
                    />
                  ) : ''}
                  <DynamicRenderingForm
                    className="dynamic-component-form"
                    onRef={ref => this.queryFormRef = ref}
                    rowData={{}}
                    selectData={selectData}
                    formData={queryFormData && queryFormData.length > 0 && [...queryFormData].map((item => {
                      return {
                        ...item,
                        onPressEnter: item.typeCode === 'Input' || item.typeCode === 'InputNumber' || item.typeCode === 'TextArea' ? this.handleQuery : ''
                      }
                    }))}
                  />
                  <div style={{ textAlign: 'center', marginTop: '6px' }}>
                    <Button style={{ marginRight: '20px' }} onClick={this.handleReset}>清空</Button>
                    <Button type="primary" onClick={this.handleQuery}>查询</Button>
                  </div>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={19}>
            {categoryData?.rightCardTitle !== 'none' ? (
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconMessages} alt="" />
                    {categoryData?.rightCardTitle || '查询列表'}
                  </div>
                )}
              >
                <div>
                  {currentRapName ? (
                    <Reports
                      params={{ ...reportParam }}
                      raqName={currentRapName}
                    />
                  ) : (
                    <div style={{ paddingTop: '10%' }}>
                      <Empty description="暂无报表信息" />
                    </div>
                  )}
                </div>
              </Card>
            ) : (
              <div>
                {currentRapName ? (
                  <Reports
                    params={{ ...reportParam }}
                    raqName={currentRapName}
                  />
                ) : (
                  <div style={{ paddingTop: '10%' }}>
                    <Empty description="暂无报表信息" />
                  </div>
                )}
              </div>
            )}
          </Col>
        </Row>
      </Spin>
    )
  }
};

export default LeftConditionRightReports;