/*
 * Creator:     WRX
 * CreatDate:   2022-09-20
 * descripts：  视光 - 库存 - 产品库存查询
 * */
import React, { Component } from 'react';
import { Row, Col, DatePicker, Button, Card, message, Input, Switch, Select, Radio } from 'antd';
import { $http } from "containers/config/https";
import { handleExcel } from 'tools/handleExcel.js';
import { Util } from 'tools';
import store from 'store';
import moment from "moment";
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import ViewTheNumberOfInTransit from './component/ViewTheNumberOfInTransit';
import iconListVisits from 'assets/images/icon_listvisits.png';
import iconInquire from 'assets/images/icon_Inquire.png';
import './style/index.less';

const Option = Select.Option;

class ProductInventoryInquiry extends Component {
  constructor(props) {
    super(props)
    this.userData = React.$getSessionData();
    this.state = {
      startDate: moment().format('YYYY-MM-DD'),
      columns: [],
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      loading: false,
      selectData: {},
      cardType: '',
      cardSelectData: [], // 卡类型下拉数据
      stkSubCat: [],
      productAlias: '',
      batchTotalWidth: 1500,
      stockTotalWidth: 2550,
      stockColumns: [],
      batchColumns: [],
      stockData: [],
      batchData: [],
      stockTotal: 0,
      stockPage: 1,
      stockPageSize: 10,
      batchLoading: false,
      batchTotal: 0,
      batchPage: 1,
      batchPageSize: 10,
      stkLocID: '',
      checkStatus: 'NZ',
      useStatus: 'Y',
      allPatData: '',
      exportLoading: false,
      stkSubCatID: '',
      loc: [],
      locID: '',
      inputNo: undefined, // 产品编号
      patInfo: undefined, // 患者信息
      ordActive: false,
      stkActive: false,
      unzeroFlag: true
    };
  }

  componentDidMount() {
    this.getDefaultSelect();
    this.getStockTableColumns();
    this.getBatchTableColumns();
  }

  // 获取库存列表头数据 -- 01040073
  getStockTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OptometryInventoryInquiry',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let filterArr = res.result?.C || [];
      if (filterArr && filterArr.length > 0) {
        for (let i = 0; i < filterArr.length; i++) {
          if (filterArr[i]?.dataIndex === 'resQty') {
            filterArr[i].render = (text, record) => (
              <span className="span" onClick={() => this.handleViewTransit(record)}>{text}</span>
            )
          }
        }
        this.setState({
          stockColumns: filterArr,
          stockTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取批次列表头数据 -- 01040073
  getBatchTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'OptometryInventoryInquiryDetail',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let filterArr = res.result?.C || [];
      if (filterArr && filterArr.length > 0) {
        filterArr = filterArr.map((item) => {
          return {
            ...item,
            render: (text, record) => {
              if (item.dataIndex === 'ordActive' || item.dataIndex === 'stkActive') {
                return (
                  <Switch
                    checkedChildren="开"
                    unCheckedChildren="关"
                    checked={record[item.dataIndex] === 1}
                    onChange={() => this.handleActiveChange(record, item.dataIndex)}
                  />
                )
              } else if (item.dataIndex === 'batResQty') {
                return <span className="span" onClick={() => this.handleViewTransit(record)}>{text}</span>
              } else {
                return text;
              }
            }
          }
        })
        this.setState({
          batchColumns: filterArr,
          batchTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 批次锁
  handleActiveChange = (record, dataIndex) => {
    let data = {
      params: [{
        stkLocBatID: record.stkLocBatID,
        stkActive: dataIndex === 'stkActive' ? record.stkActive === 1 ? 0 : 1 : undefined,  //库存激活
        ordActive: dataIndex === 'stkActive' ? undefined : record.ordActive === 1 ? 0 : 1,  //医嘱激活
      }]
    }
    $http.post('urlS', this, {
      code: '17033013',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.getBatchData()
        }
      }
    })
  }

  // 获取下拉框数据
  getDefaultSelect = async () => {
    try {
      let data = {
        params: []
      }
      let res = await React.$asyncPost(this, '17030036', data);
      this.setState({ selectData: res?.result || {}, loc: res.result.loc, stkSubCat: res.result.stkSubCat });
    } catch (error) {
      this.setState({ loc: [], stkSubCat: [] });
    }
  }

  // 获取库存数据
  getStockData = (isTips) => {
    this.setState({ loading: true });
    let { locID, stkSubCatID, stockPage, stockPageSize, startDate, productAlias, checkStatus, useStatus, inputNo, patInfo } = this.state;
    let data = {
      params: [{
        locID: locID === "" ? this.userData.locID : locID,        //科室ID 必填
        endDate: startDate,
        stkSubCatID: stkSubCatID, //库存子类
        alias: productAlias,  // 库存名称
        useStatus,
        stkStatus: checkStatus,
        inputNo, // 产品编号
        patInfo, // 患者信息
      }],
      pagination: [{
        pageSize: stockPageSize,
        currentPage: stockPage,
        sort: "",
        dir: "Asc"
      }]
    }
    $http.post('urlS', this, {
      code: '17033011',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res.result?.rows || [];
          this.setState({ stockData: tableData, stockTotal: res.result?.total || 0, stkLocID: '', batchData: [], batchTotal: 0, loading: false });
          if (!(tableData && tableData.length > 0)) {
            isTips === 'N' ? '' : message.error('未查询到数据');
          }
        } else {
          this.setState({ loading: false });
        }
      },
      error: function () {
        this.setState({ loading: false });
      }
    })
  }

  // 获取库存数据
  getBatchData = (isTips) => {
    this.setState({ batchLoading: true });
    let { batchPage, batchPageSize, stkLocID, unzeroFlag } = this.state;
    let data = {
      params: [{
        stkLocID, // 科室库存ID
        unzeroFlag: unzeroFlag ? 'Y' : 'N'
      }],
      pagination: [{
        pageSize: batchPageSize,
        currentPage: batchPage,
        sort: "",
        dir: "Asc"
      }]
    }
    $http.post('urlS', this, {
      code: '17033012',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res.result?.rows || [];
          if (tableData && tableData.length > 0) {
            this.setState({ batchData: tableData, batchTotal: res.result?.total || 0, batchLoading: false });
          } else {
            this.setState({ batchData: [], batchTotal: 0, batchLoading: false });
            isTips === 'N' ? '' : message.error('未查询到数据');
          }
        } else {
          this.setState({ batchLoading: false });
        }
      },
      error: function () {
        this.setState({ batchLoading: false });
      }
    })
  }

  // 修改查询接口入参
  handleInputChange = (values) => {
    this.setState({ locID: values })
  }

  // 查询条件相关
  stkSubCatChange = (values) => {
    this.setState({ stkSubCatID: values })
  }

  checkOptionsChange = (checkedValues) => {
    this.setState({ checkStatus: checkedValues.target.value })
  }

  useOptionsChange = (checkedValues) => {
    this.setState({ useStatus: checkedValues.target.value })
  }

  // 7.1.4 导出库存信息
  handleExport = () => {
    this.setState({
      exportLoading: true,
    })
    let { locID, stkSubCatID, stockPage, stockPageSize, startDate, productAlias, checkStatus, useStatus, inputNo, patInfo } = this.state;
    let data = {
      params: [{
        locID: locID === "" ? this.userData.locID : locID,        //科室ID 必填
        endDate: startDate,
        stkSubCatID: stkSubCatID, //库存子类
        alias: productAlias,  // 库存名称
        useStatus,
        stkStatus: checkStatus,
        inputNo, // 产品编号
        patInfo, // 患者信息
      }],
      pagination: [{
        pageSize: stockPageSize,
        currentPage: stockPage,
        sort: "",
        dir: "Asc"
      }]
    }
    $http.post('urlS', this, {
      code: '17033014',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          handleExcel.downloadExcel(res.result?.filePath || ''); // 后台导出
          this.setState({
            exportLoading: false,
          })
        } else {
          this.setState({
            exportLoading: false,
          })
        }
      },
      error: function () {
        this.setState({
          exportLoading: false,
        })
      }
    })
  }

  // 按产品名称查询
  changeAliasInput = (value) => {
    this.setState({ productAlias: value.target.value })
  }

  // 库存分页操作
  compileStockPage = (stockPage, stockPageSize) => {
    this.setState({ stockPage, stockPageSize }, () => {
      this.getStockData();
    })
  }

  // 批次分页操作
  compileBatchPage = (batchPage, batchPageSize) => {
    this.setState({ batchPage, batchPageSize }, () => {
      this.getBatchData();
    })
  }

  // 操作弹框
  onClickRowPublic = (record) => {
    return {
      onClick: () => {
        this.setState({ stkLocID: record.stkLocID }, () => { this.getBatchData() })
      }
    }
  }

  // 查询时间
  onDateChange = (value) => {
    let changeDate = moment(value).format('YYYY-MM-DD')
    this.setState({ startDate: changeDate })
  }

  // 行类名
  setRowClassNamePublic = (record) => {
    if (record.stkLocID === this.state.stkLocID) {
      return 'clickRowStyle'
    }
  }

  handleUnzeroFlagChange = e => {
    this.setState({ unzeroFlag: e, batchPage: 1 }, () => {
      this.getBatchData();
    })
  }

  // 查看在途数
  handleViewTransit = record => {
    this.viewTransitRef && this.viewTransitRef.modifyVisible(true, record);
  }

  render() {
    let { selectData, loc, stkSubCat, stockData, batchData, stockTotal, stockPage, batchTotal, batchLoading, batchPage, batchTotalWidth, stockTotalWidth, stockColumns, batchColumns, loading, exportLoading, unzeroFlag, inputNo,
      patInfo
    } = this.state;
    const stockOptions = [
      { label: '全部', value: '', key: '1' },
      { label: '库存不为0', value: 'NZ', key: '2' },
      { label: '库存为0', value: 'Z', key: '3' }
    ];
    const useOptions = [
      { label: '全部', value: '', key: '1' },
      { label: '在用产品', value: 'Y', key: '2' },
      { label: '不在用产品', value: 'N', key: '3' },
    ];

    return (
      <div className="product-inventory-inquiry">
        <Row>
          <Col span={5}>
            <div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
              <Card
                title={(
                  <div className="card-title-left-img">
                    <img src={iconInquire} alt="" />
                    查询条件
                  </div>
                )}
                bordered={false}
                size='small'
              >
                <div style={{ height: store.getState().tableHeight.y + 182 + 'px' }}>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">查询科室：</span>
                    <Select
                      allowClear
                      showSearch
                      placeholder="请选择"
                      style={{ width: '75%' }}
                      optionFilterProp="search"
                      defaultValue={this.userData.locID}
                      onChange={this.handleInputChange}
                    >
                      {loc && loc.map(item => {
                        return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                      })}
                    </Select>
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">查询日期：</span>
                    <DatePicker onChange={this.onDateChange} style={{ width: '75%' }} />
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">库存子类：</span>
                    <Select
                      allowClear
                      showSearch
                      optionFilterProp="seachprop"
                      placeholder="请选择"
                      onChange={this.stkSubCatChange}
                      style={{ width: '75%' }}
                    >
                      {stkSubCat && stkSubCat.map(item => {
                        return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                      })}
                    </Select>
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">产品信息：</span>
                    <Input style={{ width: '75%' }} placeholder="输入代码/描述/名称查询" value={this.state.productAlias}
                      onChange={this.changeAliasInput} />
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">产品编码：</span>
                    <Input
                      style={{ width: '75%' }}
                      placeholder="输入产品编码"
                      value={inputNo}
                      onChange={Util.commonInputChange.bind(this, 'inputNo')}
                    />
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">患者信息：</span>
                    <Input
                      style={{ width: '75%' }}
                      placeholder="输入病人ID/姓名"
                      value={patInfo}
                      onChange={Util.commonInputChange.bind(this, 'patInfo')}
                    />
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">
                      库存状态：
                    </span>
                    <Radio.Group defaultValue={this.state.checkStatus} options={stockOptions} onChange={this.checkOptionsChange} />
                  </div>
                  <div style={{ marginBottom: 20 }}>
                    <span className="pii-input-label">
                      使用情况：
                    </span>
                    <Radio.Group defaultValue={this.state.useStatus} options={useOptions} onChange={this.useOptionsChange} />
                  </div>
                  <div className="flex-center">
                    <Button ghost type="primary" style={{ marginRight: 15 }} loading={exportLoading} onClick={this.handleExport}>导出</Button>
                    <Button type="primary" onClick={this.getStockData}>查询</Button>
                  </div>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={19}>
            <Card
              title={(
                <div className="card-title-left-img">
                  <img src={iconListVisits} alt="" />
                  产品信息
                </div>
              )}
              bordered={false}
              size="small"
              className="table-body-height"
            >
              <PublicTablePagination
                param={{
                  page: stockPage,
                  total: stockTotal,
                  loading,
                  x: stockTotalWidth,
                  data: stockData,
                  rowKey: 'stkLocID',
                  componentName: 'OptometryInventoryInquiry',
                  y: store.getState().tableHeight.y * 0.52,
                  height: store.getState().tableHeight.y * 0.6,
                  columns: stockColumns && stockColumns.length > 0 ? stockColumns : [],
                }}
                compilePage={this.compileStockPage}
                getColumns={this.getStockTableColumns}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </Card>
            <div className="common-query-split-line" style={{ height: 8 }}></div>
            <Card
              title={(
                <div className="card-title-left-img">
                  <img src={iconListVisits} alt="" />
                  产品批次信息
                </div>
              )}
              bordered={false}
              size="small"
              className="table-body-height"
              extra={(
                <div>
                  不显示0库存：
                  <Switch
                    checkedChildren="是"
                    unCheckedChildren="否"
                    checked={unzeroFlag}
                    onChange={this.handleUnzeroFlagChange} />
                </div>
              )}
            >
              <PublicTablePagination
                param={{
                  page: batchPage,
                  total: batchTotal,
                  loading: batchLoading,
                  x: batchTotalWidth,
                  data: batchData,
                  rowKey: 'stkLocBatID',
                  componentName: 'OptometryInventoryInquiryDetail',
                  y: store.getState().tableHeight.y * 0.36,
                  height: store.getState().tableHeight.y * 0.44,
                  columns: batchColumns && batchColumns.length > 0 ? batchColumns : [],
                }}
                compilePage={this.compileBatchPage}
                getColumns={this.getBatchTableColumns}
              />
            </Card>
          </Col>
        </Row>
        {/* 查看在途数 */}
        <ViewTheNumberOfInTransit onRef={ref => this.viewTransitRef = ref} selectData={selectData} />
      </div>
    );
  }
}

export default ProductInventoryInquiry;