/*
 * Create:      柿子
 * CreateDate:  2023/03/13
 * Describe：   门诊退药查询
 * */
import React, { Component } from 'react';
import { Row, Col, Card, Button } from 'antd';
import { Util, dayFormat } from 'tools';
import moment from 'moment';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import RangeDatePicker from 'components/rangePicker/index';
import GetPatientInformation from 'pages/optometry/component/GetPatientInformation';
import iconListvisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';

class DrugReturnQuery extends Component {
  constructor(props) {
    super(props);
    this.state = {
      endDate: undefined,
      startDate: undefined,
      page: 1,
      pageSize: 20,
      total: 0,
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      rowID: '',
      detailPage: 1,
      detailPageSize: 20,
      detailTotal: 0,
      detailLoading: false,
      detailTableData: [],
      detailTotalWidth: 0,
      detailColumns: [],
      detailRowID: ''
    }
  }

  componentDidMount() {
    this.getSelectData();
    this.getTableColumns();
    this.getDetailTableColumns();
  }

  getSelectData = async () => {
    try {
      let res = await React.$asyncPost(this, '02030128');
      let selectData = res?.result || {};
      // 默认日期
      let startDate = selectData?.startDate || moment().format(dayFormat);
      let endDate = selectData?.endDate || moment().format(dayFormat);
      this.setState({ startDate, endDate }, () => {
        this.getTableData();
        this.patientRef && this.patientRef.getCardSelectData();
      });
    } catch (error) {
      console.log(error)
    }
  }

  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'DrugReturnQuery',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          columns: columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  handleModifyInputValue = (e, dataIndex) => {
    this.state[dataIndex] = e;
    this.setState({});
  }

  // 查询
  handleQuery = () => {
    this.setState({ page: 1 }, () => {
      this.getTableData();
    })
  }

  // 请求列表数据
  getTableData = async () => {
    try {
      this.setState({ loading: true })
      let { startDate, endDate, pageSize, page } = this.state;
      let patID = this.patientRef && this.patientRef.getPatientID();
      let data = {
        params: [{
          startDate,
          endDate,
          patID
        }],
        pagination: [{
          pageSize,
          currentPage: page
        }]
      }
      let res = await React.$asyncPost(this, '02030129', data);
      let tableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      this.setState({ tableData, total: res.result?.total || 0, loading: false });
      this.handleClearData();
    } catch (error) {
      this.setState({ loading: false })
    }
  }

  // 分页操作
  compilePage = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.retID))) {
          this.setState({ rowID: record.retID }, () => {
            this.getDetailTableData();
          })
        } else {
          this.handleClearData();
        }
      }
    }
  }

  handleClearData = () => {
    this.setState({ rowID: '', detailTableData: [], detailTotal: 0, detailRowID: '' });
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.retID === this.state.rowID ? 'clickRowStyle' : '';
  }

  getDetailTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'DrugReturnQueryDetail',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let columns = res.result?.C || [];
      if (columns && columns.length > 0) {
        this.setState({
          detailColumns: columns,
          detailTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 查询明细列表数据
  getDetailTableData = async () => {
    try {
      this.setState({ detailLoading: true });
      let { rowID, detailPageSize, detailPage } = this.state;
      let data = {
        params: [{
          retID: rowID
        }],
        pagination: [{
          pageSize: detailPageSize,
          currentPage: detailPage
        }]
      }
      let res = await React.$asyncPost(this, '02030130', data);
      let detailTableData = Util.addKeyValueToDataSource(res.result?.rows || []);
      this.setState({ detailTableData, detailTotal: res.result?.total || 0, detailLoading: false, detailRowID: '' });
    } catch (error) {
      this.setState({ detailLoading: false })
    }
  }

  handleDetailCompilePage = (page, pageSize) => {
    this.setState({ detailPage: page, detailPageSize: pageSize }, () => {
      this.getDetailTableData();
    })
  }

  handleDetailClickRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record.key))) {
          this.setState({ detailRowID: record.key });
        } else {
          this.setState({ detailRowID: '' });
        }
      }
    }
  }

  // 选中行操作
  handleDetailSetRowClassName = (record) => {
    return record.key === this.state.detailRowID ? 'clickRowStyle' : '';
  }

  render() {
    const { endDate, startDate, page, total, loading, tableData, totalWidth, columns, detailPage, detailTotal, detailLoading, detailTableData, detailTotalWidth, detailColumns } = this.state;

    return (
      <div>
        <div className="common-query-header flex-align-items" style={{ lineHeight: 'initial' }}>
          <GetPatientInformation
            // queryType="fuzzySearch"
            onRef={ref => this.patientRef = ref}
            handleQuery={this.handleQuery}
          />
          <div style={{ display: 'inline-block' }}>
            <RangeDatePicker
              width="300px"
              label="退药日期："
              isChange={true}
              format={dayFormat}
              endDate={endDate}
              startDate={startDate}
              endChange={(e) => this.handleModifyInputValue(e, 'endDate')}
              startChange={(e) => this.handleModifyInputValue(e, 'startDate')}
            />
          </div>
          <Button style={{ marginLeft: '12px' }} type="primary" onClick={this.handleQuery}>查询</Button>
        </div>
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <Row className="table-body-height">
          <Col span={10}>
            <Card
              size="small"
              bordered={false}
              title={<div className="card-title-left-img"><img src={iconListvisits} alt="" />退药列表</div>}
            >
              <PubilcTablePagination
                param={{
                  page,
                  total,
                  loading,
                  pageSize: '20',
                  columns, // 表头配置
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y + 22,
                  height: store.getState().tableHeight.y + 72 + 'px',
                  componentName: 'DrugReturnQuery',
                }}
                compilePage={this.compilePage}
                getColumns={this.getTableColumns}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </Card>
          </Col>
          <Col span={14}>
            <div style={{ paddingLeft: '8px', position: 'relative' }}>
              <Card
                size="small"
                bordered={false}
                title={<div className="card-title-left-img"><img src={iconMessages} alt="" />退药明细</div>}
              >
                <PubilcTablePagination
                  param={{
                    pageSize: '20',
                    page: detailPage,
                    total: detailTotal,
                    loading: detailLoading,
                    columns: detailColumns, // 表头配置
                    data: detailTableData, // 表格数据
                    x: detailTotalWidth, // 表格的宽度
                    y: store.getState().tableHeight.y + 22,
                    height: store.getState().tableHeight.y + 72 + 'px',
                    componentName: 'DrugReturnQueryDetail',
                  }}
                  compilePage={this.handleDetailCompilePage}
                  getColumns={this.getDetailTableColumns}
                  onClickRowPublic={this.handleDetailClickRow}
                  setRowClassNamePublic={this.handleDetailSetRowClassName}
                />
              </Card>
              <div className="common-card-left-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
        </Row>
      </div>
    )
  }
};

export default DrugReturnQuery;