// 拒发药品查询
import React from 'react';
import {Select, DatePicker, Button, Row, Col, Input, Card, Table, message} from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import store from 'store';
import PublicModalTable from 'pages/common/PublicModalTable';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';
import CommonPagination from 'components/pagination/index';
import "./style/index.less";

let {Option} = Select;
let timeout = null;

export default class HPInquiryOfRejectedDrugs extends React.Component {
  constructor() {
    super();
    this.state = {
      selectData: {},
      pharmacy: undefined, 
      startDate: Moment(), 
      endDate: Moment(),
      columns: [], 
      tableData: [], 
      total: 0, 
      page: 1, 
      pageSize: 20,
      loading: false,
      rowId: "",
      rowData: {},
      wardSelectData: [], //病区下拉框数据
      wardID: undefined, // 病区
      top: 0, 
      left: 0, 
      modalTableData: [],
      drugData: {}, // 弹窗药品行数据
      drugName: undefined,
      totalWidth: 0,
      locSelectData: [],
      selectedRowKeys: [],
      selectedRows: [],
    };
    this.modalColumns = [
      {
        key: 1,
        title:'库存项代码',
        dataIndex: 'stockCode',
        align: "center",
        width: '22%'
      },
      {
        key: 2,
        title: '库存项描述',
        dataIndex: 'stockDesc',
        align: "center",
        width: '24%',
      },
      {
        key: 5,
        title:'库存分类',
        dataIndex: 'stkSubCatDesc',
        align: "center",
        width: '16%',
      },
      {
        key: 3,
        title: '包装规格',
        dataIndex: 'stockSpec',
        align: "center",
        width: '12%',
      },
      {
        key: 6,
        title:'基本单位',
        dataIndex: 'baseUnitDesc',
        align: "center",
        width: '12%',
      },
      {
        key: 7,
        title: '入库单位',
        dataIndex: 'purUnitDesc',
        align: "center",
      }
    ]
  }

  componentDidMount() {
    this.getParameterSetting();
    this.getColumnsData();
  }

  // 获取初始化以及下拉框数据
  getParameterSetting = () => {
    let data = {
      params: []
    }
    $http.post('urlS', this, {
      code: "02040054",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({
            startDate: res.result&&res.result.startDate ? Moment(res.result.startDate) : Moment(),
            endDate: res.result&&res.result.endDate ? Moment(res.result.endDate) : undefined,
            locSelectData: res.result.loc,
            pharmacy: res.result.loc&&res.result.loc.length > 0 ? res.result.loc[0].id : undefined
          }, () => {
            this.handleQuery()
          })
        }
      }
    })
  }

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

  // 查询拒绝发药记录
  getTableData = () => {
    let {startDate, endDate, pharmacy, wardID, pageSize, page, drugData} = this.state;
    let data = {
      params: [{
        locID: pharmacy,
        wardID,
        startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "", // 开始日期
				endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "", // 截止日期
        stockID: drugData&&drugData.stockID ? drugData.stockID : ""
      }],
      pagination: [{
				pageSize,
				currentPage: page,
			}]
    }
    $http.post('urlS', this, {
      code: "02040053",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          for(var i = 0; i < res.result.rows.length; i++) {
            res.result.rows[i].key = res.result.rows[i].refDispID
          }
          this.setState({tableData: res.result.rows, total: res.result.total, selectedRowKeys: [], selectedRows: []})
        }
      }
    })
  }

  // 获取表头数据
  getColumnsData = () => {
    let data = {
      params: [{
        compontName: 'HPInquiryOfRejectedDrugs',
        type: 'C',
      }]
    }
    $http.post('urlS', this, {
      code: '01040073',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let arr = res.result.C&&res.result.C.length > 0 ? JSON.parse(JSON.stringify(res.result.C)).map((item, index) => {
            return  {
              ...item,
              key: index + 1,
              title: <div onDoubleClick={() => this.columnRef.onOpenModel()}>{item.title}</div>
            }
          }) : '';
          let filterArr = arr.filter(function(item){ return item.display === 'Y'});
          this.setState({columns: filterArr, totalWidth: res.totalWidth})
        }
      }
    })
  }

  onColumnRef = (ref) => {
    this.columnRef = ref;
  };

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

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

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

  // 请求病区下拉框数据(病区)
  handleWardSelectData = (value) => {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    timeout = setTimeout(() => {
      if (value) {
        let data = {
          params: [{
            alias: value
          }]
        }
        $http.post('urlS', this, {
          code: "02040003",
          data: data,
          success: function (res) {
            if (+res.errorCode === 0) {
              this.setState({wardSelectData: res.result})
            }
          }
        })
      }
    }, 300)
  }

  // 病区
  handleWardOnChange = e => {
    this.setState({wardID: e}, () => {
      this.getTableData();
    })
  }

  // 药品名称
  handleDrugNameChange=(e)=>{
    if(!e.target.value) {
      this.setState({drugData: {}}, () => {
        this.getTableData();
      })
    }
    this.setState({drugName: e.target.value});
  };

  // 描述回车事件
  stockDescOnPressEnter = (e) => {
    let top = document.getElementById('stock-desc').getBoundingClientRect().top + 33 + 'px';
    let left = document.getElementById('stock-desc').getBoundingClientRect().left + 'px'; // 如果弹窗宽度修改了则要基于600做减法(比如变成了800则需要减去200)
    this.setState({
      top,
      left
    });
    this.getModalListData(e.target.value);
    this.drugChild.showModal();
  };

  // 获取描述列表数据
  getModalListData = (alias) => {
    let data = {
      params: [
        {
          stockAlias: alias, // 库存项描述别名
          frLocID: undefined
        }
      ]
    };
    $http.post('urlS', this, {
      code: "02020042",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          for(var i = 0; i < res.result.length; i++) {
            res.result[i].key = i
          }
          this.setState({ modalTableData: res.result})
        } else {
          this.setState({ modalTableData: [] })
        }
      }
    })
  }

  // 操作弹框
  handleDrugRowClick = (record) => {
    return {
      onDoubleClick: () => {
        this.confirmSelection(record);
      }
    }
  };
  
  // 双击选中行数据的回调
  confirmSelection = (record) => {
    // this.resetFields();
    this.setState({drugName: record.stockDesc, drugData: record}, () => {
      this.getTableData();
      // 关闭弹窗
      this.drugChild.handleCancel();
    })
  };

  onDrugRef = ref => {
    this.drugChild = ref;
  }

  // 拒发药品列表行操作
  handleOnRow = (record) => {
    return {
      onClick: () => {
        let { selectedRowKeys, selectedRows } = this.state;
        let findFlag = false;
        let start = 0;
        if (selectedRowKeys) {
          selectedRowKeys.find(function (value, key) {
            if (value === record.key) {
              //遍历找到选中的数据，并记录下选中数据在数组中的key
              findFlag = true;
              start = key;
            }
          })
        }
        if (findFlag) {
          //再次点击移除选中
          selectedRowKeys.splice(start, 1);
          selectedRows.splice(start, 1);
        } else {
          //将点击的行添加到选中
          selectedRowKeys.push(record.key);
          selectedRows.push(record);
        }
        if (this.state.rowId === "") {
          this.setState({
            rowId: record.key,
            selectedRowKeys,
            selectedRows
          });
        } else {
          if (this.state.rowId !== record.key) {
            this.setState({
              rowId: record.key,
              selectedRowKeys,
              selectedRows
            });
          } else {
            this.setState({
              rowId: "",
              selectedRowKeys,
              selectedRows,
            });
          }
        }
      }
    }
  }

  handleRowClassName = (record) => {
    return (("^" + this.state.selectedRowKeys.join("^") + "^").indexOf("^" + record.key + "^") > -1) ? 'clickRowStyle' : '';
  }

  // 修改条数
  handleCompilePageSize = (page, pageSize) => {
    this.setState({page: 1, pageSize}, () => {
      this.getTableData();
    })
  }

  // 修改页数
  handleCompilePage = (page, pageSize) => {
    this.setState({page, pageSize}, () => {
      this.getTableData();
    })
  }

  // 撤销发药
  handleRevokingDispensing = () => {
    let {selectedRowKeys} = this.state;
    let data = {
      params: [{
        refDispID: selectedRowKeys
      }]
    }
    $http.post('urlS', this, {
      code: '02040055',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success(res.errorMessage);
          this.getTableData();
        }
      }
    })
  }

  render() {
    let {pharmacy, startDate, endDate, locSelectData, columns, tableData, total, page, loading, wardSelectData, wardID, drugName, top, left, modalTableData, totalWidth, selectedRowKeys,
      selectedRows
    } = this.state;

    const rowSelection = {
      selectedRowKeys,
      selectedRows,
      onChange: (selectedRowKeys, selectedRows) => {
        let rowId= "";
        if (selectedRowKeys.length !== 0) {
          rowId=selectedRowKeys[selectedRowKeys.length-1];
        }
        this.setState({selectedRowKeys, selectedRows, rowId: rowId})
      }
    };

    let drugParam = {
      width: '600px',
      top,
      left,
      columns: this.modalColumns,
      data: modalTableData,
      isOnRow: true,
      TableClassName: 'tab-placeholder',
    };

    // 药房
    let pharmacyOption = locSelectData &&locSelectData.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    // 病区
    let wardAreaOption = wardSelectData&&wardSelectData.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })
    return (
      <div className="inquiry-of-rejected-drugs">
        <Row style={{padding: '0 24px'}}>
          <Col span={16}>
            <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: '15px'}} 
                placeholder="结束日期"
                allowClear={false}
              />
              病区：<Select
                style={{width: '200px', margin: '8px 15px 0 0'}} 
                showSearch
                defaultActiveFirstOption={false}
                showArrow={false}
                filterOption={false}
                onSearch={this.handleWardSelectData}
                notFoundContent={null}
                placeholder='搜索病区'
                allowClear
                value={wardID}
                onChange={this.handleWardOnChange}
              >
                {wardAreaOption}
              </Select>
              <span id="stock-desc">
                药品名称：<Input style={{width: "200px", margin: '8px 15px 0 0'}} placeholder='回车检索药品相关信息' allowClear onPressEnter={this.stockDescOnPressEnter} value={drugName} onChange={this.handleDrugNameChange} />
              </span>
              
              <Button style={{marginTop: '8px'}} onClick={this.getTableData}>查询</Button>
            </div>
          </Col>
          <Col span={8} style={{textAlign: 'right'}}>
            <Button
              type="primary"
              style={{marginTop: '8px'}}
              disabled={selectedRowKeys&&selectedRowKeys.length > 0 ? false : true}
              onClick={this.handleRevokingDispensing}
            >
              撤销拒绝发药
            </Button>
          </Col>
        </Row>
        <div style={{height: '6px', background: 'rgba(240, 242, 245, 1)', width: '100%'}}></div>
        <Card
          size="small"
          title={<div className="card-title-left-icon"><div></div>拒发药品明细</div>}
        >
          <div style={{height: store.getState().tableHeight.y + 174 - 48 + 'px', overflow: 'auto'}}>
            <Table
              rowSelection={rowSelection}
              columns={columns}
              dataSource={tableData}
              bordered
              pagination={false}
              scroll={{x: totalWidth, y: store.getState().tableHeight.y}}
              onRow={this.handleOnRow}
              rowClassName={this.handleRowClassName}
            />
            <CommonPagination size='small' current={page} total={total} search= 'search'
              onShowSizeChange={this.handleCompilePageSize} complete={true} dataSource={tableData}
              loading={loading} onChange={this.handleCompilePage} pageSize={20} />
            {/* <PubilcTablePagination param={param} handelThis={this} onRef={this.onRef} onClickRowPublic={this.onClickRowPublic} setRowClassNamePublic={this.setRowClassNamePublic} /> */}
          </div>
        </Card>
        <PublicModalTable onClickRowPublic={this.handleDrugRowClick} param={drugParam} onRef={this.onDrugRef} />
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName='HPInquiryOfRejectedDrugs'
          configType="C"
          onRef={this.onColumnRef}
          reloadData={this.getColumnsData}
        />
      </div>
    )
  }
}