// 物资入库单据批量出库
import React, { Component } from 'react';
import { Modal, Card, Row, Col, Table, Button, DatePicker, Select, Pagination, message } from 'antd';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import '../style/index.less';
import store from 'store';
import ColumnAuthoritysModel from 'pages/columnAuthority/ColumnAuthoritysModel';

let { Option } = Select;

class MaterialDocumentDeliveryModal extends Component {
  constructor(props) {
    super(props);
    let userData = window.sessionStorage.userData ? JSON.parse(window.sessionStorage.userData) : {};
    this.state = {
      userData,
      visible: false,
      tableData: [], // 入库单列表数据
      page: 1,
      pageSize: 10,
      total: 0,
      detailTableData: [], // 明细列表数据
      detailPage: 1,
      detailPageSize: 10,
      detailTotal: 0,
      rowID: "",
      locID: userData && userData.locID ? userData.locID : undefined,
      startDate: Moment(), // 开始日期
      endDate: Moment(), // 截止日期
      frLoc: userData && userData.locID ? userData.locID : undefined, // 供给科室
      toLoc: undefined, // 请求科室
      detailColumns: [],
      detailWidthTotal: 0,
      parameterCode: ""
    };

    this.columns = [
      {
        key: 1,
        title: '供应商',
        dataIndex: 'vendorDesc',
        align: "center",
        width: '28%'
      },
      {
        key: 2,
        title: '入库科室',
        dataIndex: 'inOperLocDesc',
        align: "center",
        width: '16%',
      },
      {
        key: 3,
        title: '入库单号',
        dataIndex: 'No',
        align: "center",
        width: '20%',
      },
      {
        key: 4,
        title: '单据状态',
        dataIndex: 'stateDesc',
        align: "center",
        width: '16%',
      },
      {
        key: 5,
        title: '入库日期',
        dataIndex: 'createDate',
        align: "center",
      }
    ];

    this.detailColumns = [
      {
        key: 1,
        title: '药品代码',
        dataIndex: 'stockCode',
        align: "center",
        width: '150px'
      },
      {
        key: 2,
        title: '药品名称',
        dataIndex: 'stockDesc',
        align: "center",
        width: '300px',
      },
      {
        key: 3,
        title: '包装规格',
        dataIndex: 'stockSpec',
        align: "center",
        width: '150px',
      },
      {
        key: 5,
        title: '生产厂家',
        dataIndex: 'manfDesc',
        align: "center",
        width: '300px',
      },
      {
        key: 6,
        title: '批号',
        dataIndex: 'batNo',
        align: "center",
        width: '150px',
      },
      {
        key: 7,
        title: '剂型',
        dataIndex: 'formDesc',
        align: "center",
        width: '150px',
      },
      {
        key: 8,
        title: '数量',
        dataIndex: 'qty',
        align: "center",
        width: '100px',
      },
      {
        key: 9,
        title: '单位',
        dataIndex: 'unitDesc',
        align: "center",
        width: '100px',
      },
      {
        key: 10,
        title: '进价',
        dataIndex: 'rp',
        align: "center",
        width: '100px',
      },
      {
        key: 11,
        title: '售价',
        dataIndex: 'sp',
        align: "center",
        width: '100px',
      },
      {
        key: 12,
        title: '发票号',
        dataIndex: 'invNo',
        align: "center",
        width: '100px',
      },
      {
        key: 13,
        title: '发票日期',
        dataIndex: 'invDate',
        align: "center",
        width: '100px',
      },
      {
        key: 14,
        title: '发票金额',
        dataIndex: 'invAmt',
        align: "center",
        width: '100px',
      },
      {
        key: 15,
        title: '进价金额',
        dataIndex: 'rpAmt',
        align: "center",
        width: '100px',
      },
      {
        key: 16,
        title: '售价金额',
        dataIndex: 'spAmt',
        align: "center",
        width: '100px',
      },
    ]
  }

  componentDidMount() {
    this.props.onRef(this);
  }

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

  // 打开弹窗
  showModal = () => {
    let { columns } = this.state;
    this.setState({ visible: true }, () => {
      this.handleQuery();
      if (!(columns && columns.length > 0)) {
        this.getDetailTableColumns();
      }
    })
  }

  // 获取库单列表数据
  getTableData = () => {
    let { locID, startDate, endDate, pageSize, page } = this.state;
    let data = {
      params: [{
        inOperLocID: locID,
        statusID: "30",
        startDate: startDate ? Moment(startDate).format('YYYY-MM-DD') : "",
        endDate: endDate ? Moment(endDate).format('YYYY-MM-DD') : "",
      }],
      pagination: [{
        pageSize,
        currentPage: page
      }]
    }
    $http.post('urlS', this, {
      code: "02060010",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res && res.rows && res.rows.length > 0 ? res.rows : [];
          for (var i = 0; i < tableData.length; i++) {
            tableData[i].key = i + 1;
          }
          this.setState({
            tableData, total: res.total, detailTableData: [], rowID: "", rowData: {}
          })
        } else {
          this.setState({
            tableData: [], total: 0, detailTableData: [], rowID: "", rowData: {}
          })
        }
      }
    })
  }

  // 入库单列表分页 change
  paginationChange = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getTableData();
    })
  }

  // 入库单列表分页 showSizeChange
  paginationShowSizeChange = (current, size) => {
    this.setState({ page: 1, pageSize: size }, () => {
      this.getTableData();
    })
  }

  // 表格行操作
  handleTableClickRow = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '') {
          // 保存行数据以及ID
          this.setState({ rowID: record.inOperID, rowData: record }, () => {
            this.getDetailTableData()
          })
        } else {
          if (this.state.rowID !== record.key) {
            this.setState({ rowID: record.inOperID, rowData: record }, () => {
              this.getDetailTableData()
            })
          }
        }
      },
      onDoubleClick: () => {
        this.setState({ rowID: record.inOperID, rowData: record }, () => {
          this.getDetailTableData('noConfirm')
        })
      }
    }
  };

  // 表格行的类名
  handleTableSetRowClassName = (record) => {
    return record.inOperID === this.state.rowID ? 'clickRowStyle' : '';
  };

  // 显示分页总条数
  showTotal(total) {
    return `共 ${total} 条`;
  }

  // 获取明系列表头数据
  getDetailTableColumns = () => {
    let { userData } = this.state;
    let data = {
      params: [{
        reactCode: ['MaterialStorageOrderMaking'],
        compontName: 'MaterialWarehouseList',
        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.setState({ parameterCode: 'MaterialWarehouseList' }, () => {
                  this.columnRef.onOpenModel();
                })
              }}>{userData.language == 'EN' ? item.enDescripts : item.title}</div>,
            }
          }) : '';
          let filterArr = arr.filter(function (item) { return item.display === 'Y' });
          console.log(filterArr)
          this.setState({ detailColumns: filterArr, detailWidthTotal: res.totalWidth })
        }
      }
    })
  };

  // 查询明细列表数据
  getDetailTableData = (isConfirm) => {
    let { rowID } = this.state;
    let data = {
      params: [{
        inOperID: rowID
      }],
    }
    $http.post('urlS', this, {
      code: "02060012",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let detailTableData = res.detail && res.detail.rows && res.detail.rows.length > 0 ? res.detail.rows : [];
          for (let i = 0; i < detailTableData.length; i++) {
            detailTableData[i].key = i + "detail";
          }
          this.setState({ detailTableData }, () => {
            if (isConfirm === "noConfirm") {
              this.handleOk(); // 确认
            }
          });
        } else {
          this.setState({
            detailTableData: [],
          })
        }
      }
    })
  }

  // 明细列表分页 change
  detailPaginationChange = (page, pageSize) => {
    this.setState({ page, pageSize }, () => {
      this.getDetailTableData();
    })
  }

  // 明细列表分页 showSizeChange
  detailPaginationShowSizeChange = (current, size) => {
    this.setState({ page: 1, pageSize: size }, () => {
      this.getDetailTableData();
    })
  }

  // 重置表单
  resetFields = () => {
    let { userData } = this.state;
    this.setState({
      locID: userData && userData.locID ? userData.locID : undefined,
      startDate: Moment(), // 开始日期
      endDate: Moment(), // 截止日期
      rowID: '',
      rowData: {},
      page: 1,
      tableData: [],//主列表数据
      total: 0,
      detailTableData: [], //明细列表数据
      frLoc: userData && userData.locID ? userData.locID : undefined,
      toLoc: undefined
    });
  };

  // 获取科室数据
  handleLocChange = e => {
    this.setState({ locID: e, frLoc: e })
  }

  // 查询条件 --- 开始日期
  handleStartDate = (e) => {
    this.setState({ startDate: e });
  }

  // 查询条件 --- 截止日期
  handleEndDate = (e) => {
    this.setState({ endDate: e });
  }

  // 取消
  handleCancel = () => {
    this.setState({ visible: false })
  }

  // 确定
  handleOk = () => {
    let { detailTableData, frLoc, toLoc } = this.state;
    // if (!frLoc) {
    //   message.error("供给科室不能为空。");
    //   return;
    // }
    if (!toLoc) {
      message.error("请求科室不能为空。");
      return;
    }
    if (detailTableData && detailTableData.length > 0) {
      let data = {
        params: [{
          transID: '',
          frLocID: frLoc,
          toLocID: toLoc,
          stkCatID: '',
          remark: '',
          operTypeID: '',
          detail: detailTableData
        }]
      };
      $http.post('urlS', this, {
        code: "02060017",
        data: data,
        success: function (res) {
          if (+res.errorCode === 0) {
            // 成功提示
            message.success(res.errorMessage)
            this.props.getEchoData(res.result.main.transID);
            this.resetFields();
            this.handleCancel();
          }
        },
        error: function (err) {
          console.log(err)
        }
      })
    } else {
      message.error("请选择一条需要操作的数据");
    }
  }

  // 供给科室
  handleFrLocChange = e => {
    this.setState({ frLoc: e })
  }

  // 请求科室
  handleToLocChange = e => {
    this.setState({ toLoc: e })
  }
  
  onColumnRef = (ref) => {
    this.columnRef = ref;
  }

  render() {
    let { visible, tableData, page, total, detailTableData, locID, startDate, endDate, toLoc, detailColumns, detailWidthTotal } = this.state;

    // 科室下拉数据
    let locOption = this.props.SelectData && this.props.SelectData.loc && this.props.SelectData.loc.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    // 骑牛科室下拉数据
    let toLocOption = this.props.SelectData && this.props.SelectData.toLoc && this.props.SelectData.toLoc.map((item, index) => {
      return (<Option key={index} value={item.id} title={item.descripts} seatchprop={item.descripts + '^' + item.descriptsSPCode}>{item.descripts}</Option>)
    })

    return (
      <div>
        <Modal
          title="物资入库单据批量出库"
          visible={visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText='保存'
          cancelText='取消'
          width='75%'
          height='85%'
          className="selectRequisition material-document-delivery-modal"
        >
          <div>
            <div style={{ margin: "12px 0", display: "flex", alignItems: "center", padding: "0 12px", boxSizing: "border-box" }}>
              <span className="custom-form-item-label" style={{ width: "100px" }}>入库科室：</span>
              <Select className="custom-form-item-input" style={{ width: '150px', marginRight: '15px' }} value={locID} onChange={this.handleLocChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                {locOption}
              </Select>
              <span className="custom-form-item-label">日期：</span>
              <DatePicker className="custom-start-date" value={startDate} onChange={this.handleStartDate} style={{ width: '150px' }} placeholder="开始日期" format="YYYY-MM-DD" />
              <span className="custom-form-item-label custom-form-label-date">到</span>
              <DatePicker className="custom-end-date" value={endDate} onChange={this.handleEndDate} style={{ width: '150px', marginRight: '20px' }} placeholder="结束日期" format="YYYY-MM-DD" />

              <Button type="primary" style={{ marginRight: '15px' }} onClick={this.handleQuery}>
                查询
            </Button>
              <Button type="danger" style={{ marginRight: '20px' }} ghost onClick={this.resetFields}>
                清屏
            </Button>

              {/* <span className="custom-form-item-label formRequired" style={{ width: "110px" }}>供给科室：</span>
              <Select className="custom-form-item-input" style={{ width: '150px', marginRight: '15px' }} value={frLoc} onChange={this.handleFrLocChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                {locOption}
              </Select> */}
              <span className="custom-form-item-label formRequired" style={{ width: "110px" }}>请求科室：</span>
              <Select className="custom-form-item-input" style={{ width: '150px', marginRight: '15px' }} value={toLoc} onChange={this.handleToLocChange} showSearch optionFilterProp="seatchprop" allowClear placeholder="请选择">
                {toLocOption}
              </Select>
            </div>
            <Row style={{ padding: "0 12px", boxSizing: "border-box" }}>
              <Col span={10}>
                <div style={{ paddingRight: '6px', position: 'relative' }}>
                  <Card
                    size='small'
                    title={<div className="card-title-left-icon"><div></div>入库单</div>}
                  >
                    <div style={{ height: store.getState().tableHeight.y - 140 + 'px' }}>
                      <Table
                        columns={this.columns}
                        dataSource={tableData}
                        pagination={false}
                        bordered
                        scroll={{ x: 1000, y: store.getState().tableHeight.y - 226 }}
                        onRow={this.handleTableClickRow}
                        rowClassName={this.handleTableSetRowClassName}
                        className="table-body-height"
                      />
                      <Pagination
                        showTotal={() => this.showTotal(total)}
                        size="small"
                        showQuickJumper
                        showSizeChanger
                        defaultCurrent={1}
                        current={page}
                        total={total}
                        onChange={this.paginationChange}
                        onShowSizeChange={this.paginationShowSizeChange}
                        style={{ textAlign: "right", marginTop: '13px' }}
                      />
                    </div>
                  </Card>
                  <div style={{ width: '6px', background: '#fff', position: 'absolute', top: 0, right: 0, height: '100%' }}></div>
                </div>
              </Col>
              <Col span={14}>
                <Card
                  size='small'
                  title={<div className="card-title-left-icon"><div></div>入库单明细</div>}
                >
                  <div style={{ height: store.getState().tableHeight.y - 140 + 'px' }}>
                    <Table
                      columns={detailColumns && detailColumns.length > 0 ? detailColumns : this.detailColumns}
                      dataSource={detailTableData}
                      pagination={false}
                      bordered
                      scroll={{ x: detailWidthTotal ? parseInt(detailWidthTotal) : 1000, y: store.getState().tableHeight.y - 226 }}
                      className="table-body-height"
                    />
                  </div>
                </Card>
              </Col>
            </Row>
          </div>
        </Modal>
        <ColumnAuthoritysModel
          clientWidth='800px'
          compontName={this.state.parameterCode}
          configType="C"
          onRef={this.onColumnRef}
          reloadData={() => {
            if (this.state.parameterCode == 'MaterialWarehouseList') {
              this.getDetailTableColumns()
            } else if (this.state.parameterCode == 'Order') {
              this.getTableColumns()
            }
          }
          }
        />
      </div>
    );
  }
}

export default MaterialDocumentDeliveryModal;