// 住院退药查询
import React, { Component } from 'react';
import { Card, Row, Col, DatePicker, Select, Button, Table, message } from 'antd';
import PubilcTablePagination from 'pages/common/PubilcTablePagination';
import iconListVisits from 'assets/images/icon_listvisits.png';
import store from 'store';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import CommonPagination from 'components/pagination/index';
import { $loopPrint } from '../lodop/Common/Print.js';

let { Option } = Select;

class HPDrugReturnInquiry extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      basicHeight: 0,
      pharmacy: userData && userData.locID ? userData.locID : undefined,
      startDate: Moment(),
      endDate: Moment(),
      columns: [],
      widthTotal: 0,
      tableData: [],
      total: 0,
      page: 1,
      basicHeight: 0,
      loading: false,
      detailTableData: [],
      detailWidthTotal: 0,
      detailColumns: [],
      detailTotal: 0,
      detailPage: 1,
      detailPageSize: 10,
      rowID: "",
      rowData: {},
      selectData: {}
    };
    this.columns = [
      { title: '床号', dataIndex: 'bedNO', key: '1', width: '100px', align: "center" },
      { title: '姓名', dataIndex: 'patName', key: '2', width: '100px', align: "center" },
      { title: '病人ID', dataIndex: 'patNo', key: '3', width: '100px', align: "center" },
      { title: '退药申请单号', dataIndex: 'inRetNO', key: '4', width: '150px', align: "center" }
    ];
    this.detailColumns = [
      {
        title: '退药数量',
        dataIndex: 'retQty',
        width: '100px',
        align: "center"
      },
      {
        title: '退药原因',
        dataIndex: 'retReasonDesc',
        width: '200px',
        align: "center",
      },
      {
        title: '药品名称',
        dataIndex: 'stockDesc',
        width: '250px',
        align: "center"
      },
      {
        title: '商品名',
        dataIndex: 'tradeName',
        width: '250px',
        align: "center"
      },
      {
        title: '剂型',
        dataIndex: 'formDesc',
        width: '100px',
        align: "center",
      },
      {
        title: '规格',
        dataIndex: 'stockSpec',
        width: '100px',
        align: "center"
      },
      {
        title: '退药时间',
        dataIndex: 'retDateTime',
        width: '200px',
        align: "center"
      },
    ];
  }

  componentDidMount() {
    this.setState({ basicHeight: document.getElementById("dri-operation").clientHeight }, () => {
      this.getSelectData();
    });
  }

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

  // 取发药下拉框数据集
  getSelectData = () => {
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "02040036",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ selectData: res }, () => {
            this.handleQuery();
          })
        }
      }
    })
  }

  onRef = ref => {
    this.child = ref;
  }

  // 药房查询条件
  handlePharmacyOnChange = e => {
    this.setState({ pharmacy: e })
  }

  // 开始日期
  handleStartDate = e => {
    this.setState({ startDate: e })
  }

  // 结束日期
  handleEndDate = e => {
    this.setState({ endDate: e })
  }

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

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

  // 获取主表table数据
  getTableData = () => {
    let { startDate, endDate, pharmacy, page, pageSize } = this.state;
    let data = {
      params: [{
        startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
        endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
        recLocID: pharmacy
      }],
      pagination: [{
        pageSize,
        currentPage: page,
      }]
    }
    $http.post('urlS', this, {
      code: "02040066",
      data: data,
      success: function (res) {
        this.child.handleLoading();
        if (+res.errorCode === 0) {
          for (var i = 0; i < res.rows.length; i++) {
            res.rows[i].key = i + 1
          }
          this.setState({ tableData: res.rows, total: res.total, rowID: "", rowData: {}, detailTableData: [], detailTotal: 0 });
        } else {
          this.setState({ tableData: [], total: 0, rowID: "", rowData: {}, detailTableData: [], detailTotal: 0 });
        }
      },
      error: function () {
        this.setState({ tableData: [], total: 0, rowID: "", rowData: {}, detailTableData: [], detailTotal: 0 }, () => {
          this.child.handleLoading();
        });
      }
    })
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '') {
          // 保存行数据以及ID
          this.setState({ rowID: record.inRetID, rowData: record }, () => {
            this.handleQueryDetail();
          });
        } else {
          if (this.state.rowID !== record.inRetID) {
            this.setState({ rowID: record.inRetID, rowData: record }, () => {
              this.handleQueryDetail();
            });
          }
        }
      }
    }
  }

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

  // 获取明细列表数据
  handleQueryDetail = () => {
    let { rowID, detailPageSize, detailPage } = this.state;
    let data = {
      params: [{
        inRetID: rowID
      }],
      pagination: [{
        pageSize: detailPageSize,
        currentPage: detailPage,
      }]
    }
    $http.post('urlS', this, {
      code: "02040067",
      data: data,
      success: function (res) {
        this.child.handleLoading();
        if (+res.errorCode === 0) {
          for (var i = 0; i < res.rows.length; i++) {
            res.rows[i].key = i
          }
          this.setState({ detailTableData: res.rows, detailTotal: res.total });
        } else {
          this.setState({ detailTableData: [], detailTotal: 0 });
        }
      }
    })
  }

  /**打印住院退药
    */
  print = () => {
    let { rowID } = this.state;
    const data = {
      params: [{ retID: rowID }]
    };
    $http.post('urlS', this, {
      code: "02040068",
      data: data,
      success: function (res) {
        // console.log(res)
        if (+res.errorCode === 0) {
          $loopPrint('', res.result);
        } else {
          message.error(res.errorMessage);
        }
      }
    })
  }

  // 明细列表修改条数
  handleDetailChange = (page, pageSize) => {
    this.setState({ detailPage: page, detailPageSize: pageSize }, () => {
      this.handleQueryDetail();
    })
  }

  // 明细列表修改条数
  handleDetailSizeChange = (current, size) => {
    this.setState({ detailPage: 1, detailPageSize: size }, () => {
      this.handleQueryDetail();
    })
  }

  render() {
    let { pharmacy, startDate, endDate, columns, widthTotal, tableData, total, page, basicHeight, loading, detailTableData, detailWidthTotal, detailColumns,
      detailTotal, detailPage, selectData, rowID
    } = this.state;

    // 组件所需参数
    const param = {
      // 表头配置
      columns: columns && columns.length > 0 ? columns : this.columns,
      // 表格数据
      data: tableData,
      // 数据总条数
      total,
      // 当前页数
      page,
      // 表格的宽度
      x: columns && columns.length > 0 ? widthTotal : 450,
      y: store.getState().tableHeight.y + 90 - basicHeight,
      height: store.getState().tableHeight.y + 136 - basicHeight + 'px',
      isOnRow: true,
      rowClassName: true,
      TableClassName: 'table-scroll-height',
      loading
    };

    // 药房
    let pharmacyOption = selectData.recLoc && selectData.recLoc.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return (
      <div className="drug-return-inquiry hospital-pharmacies">
        <Row id="dri-operation" style={{ padding: '0 24px' }}>
          <Col span={20}>
            <div style={{ marginBottom: '8px' }}>
              药房：<Select value={pharmacy} onChange={this.handlePharmacyOnChange} showSearch optionFilterProp="seatchprop" placeholder="请选择" style={{ width: '150px', margin: '8px 15px 0 0' }}>
                {pharmacyOption}
              </Select>
              <DatePicker
                value={startDate}
                onChange={this.handleStartDate}
                style={{ width: '150px', marginTop: '8px' }}
                placeholder="开始日期"
                allowClear={false}
              />
              <span style={{ display: 'inline-block', margin: '0 5px' }}>到</span>
              <DatePicker
                value={endDate}
                onChange={this.handleEndDate}
                style={{ width: '150px', marginRight: '20px' }}
                placeholder="结束日期"
                allowClear={false}
              />
              <Button type="primary" style={{ marginTop: '8px', marginRight: "20px" }} onClick={this.handleQuery}>查询</Button>
              <Button type="primary" style={{ marginTop: '8px' }} onClick={this.print} disabled={!!!rowID}>打印</Button>
            </div>
          </Col>
        </Row>
        <div style={{ height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%' }}></div>
        <Row>
          <Col span={6}>
            <Card
              size="small"
              title={<div className="card-title-left-img"><img src={iconListVisits} alt="" />退药列表</div>}
            // extra={}
            >
              <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} onClickRowPublic={this.onClickRowPublic} setRowClassNamePublic={this.setRowClassNamePublic} />
            </Card>
          </Col>
          <Col span={18}>
            <div style={{ paddingLeft: '6px', position: 'relative' }}>
              <Card
                size="small"
                title={<div className="card-title-left-img"><img src={iconListVisits} alt="" />退药明细</div>}
              >
                <div style={{ height: store.getState().tableHeight.y + 174 - basicHeight + 'px', overflow: 'auto' }}>
                  <Table
                    dataSource={detailTableData}
                    pagination={false}
                    bordered
                    scroll={{ x: detailWidthTotal ? parseInt(detailWidthTotal) : 1000, y: store.getState().tableHeight.y + 90 - basicHeight }}
                    columns={detailColumns && detailColumns.length > 0 ? detailColumns : this.detailColumns}
                    onRow={this.handleTableClickRow}
                    rowClassName={this.handleTableSetRowClassName}
                    className="table-body-height"
                  />
                  <CommonPagination size="small" current={detailPage} total={detailTotal} search="search"
                    onShowSizeChange={this.handleDetailSizeChange} complete={true} dataSource={detailTableData}
                    onChange={this.handleDetailChange} />
                </div>
              </Card>
              <div style={{ width: '6px', background: 'rgba(240, 242, 245, 1)', position: 'absolute', top: 0, left: 0, height: '100%' }}></div>
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}

export default HPDrugReturnInquiry;