/*
 * Creator:     WRX
 * CreatDate:   2022-09-20
 * descripts：  视光 - 库存 - 产品台账查询
 * */
import React, { Component } from 'react';
import { Row, Col, Button, Card, message, Input, Select, Switch } from 'antd';
import { dayFormat } from 'tools';
import { handleExcel } from 'tools/handleExcel';
import { $http } from '../../../containers/config/https';
import moment from 'moment';
import PublicTablePagination from 'pages/common/PubilcTablePagination';
import store from 'store';
import RangeDatePicker from '../../../components/rangePicker';
import iconListVisits from 'assets/images/icon_listvisits.png';

class StandingBookQuery extends Component {
  constructor(props) {
    super(props);
    let userData = React.$getSessionData();
    this.state = {
      selectData: {},
      queryParam: {
        busType: undefined, // 验光类型
        consumeTypeID: undefined, // 验光类型
        locID: userData?.locID || undefined, // 验光类型
        poison: undefined, // 验光类型
        stkCat: undefined, // 验光类型
        stkSubCat: undefined, // 验光类型
        brandID: undefined, // 品牌
        alias: undefined,
        busLossFlag: 'N', // 显示业务损益
        endDate: moment().format(dayFormat),
        startDate: moment().format(dayFormat),
        productCode: undefined, // 产品编码
      },
      page: 1,
      pageSize: 20,
      total: 0,// 预约人数
      totalWidth: 0,
      loading: false,
      detailSelectedRowKeys: [],
      bookPage: 1,
      bookPageSize: 20,
      bookTotal: 0,// 预约人数
      detailsPage: 1,
      detailsPageSize: 20,
      detailsTotal: 0,// 预约人数
      bookData: [],
      bookColumns: [],
      detailsData: [],
      detailsColumns: [],
      detailTotalWidth: 0,
      stkLocID: '',
      exportLoading: false
    }
  }

  componentDidMount() {
    this.getDefaultData();
    this.getStandingBookColumns();
    this.getBookDetailsColumns()
  }

  // 获取卡类型下拉框数据
  getDefaultData = () => {
    let data = {
      params: [{}]
    }
    $http.post('urlS', this, {
      code: '17030057',
      data: data,
      success: function (res) {
        if (res.errorCode === '0') {
          let result = res?.result || [];
          let selectData = result && result.length > 0 ? result[0] : {};
          this.state.queryParam.startDate = selectData?.startDate || moment().format(dayFormat);
          this.state.queryParam.endDate = selectData?.endDate || moment().format(dayFormat);
          this.setState({
            selectData,
          }, () => {
            this.getStandingBookData('N');
          })
        }
      }
    })
  }

  // 获取列表头数据 -- 01040073
  getStandingBookColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'optometryStandingBook',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let filterArr = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (filterArr && filterArr.length > 0) {
        filterArr = filterArr && filterArr.length > 0 ? [...filterArr] : []
        this.setState({
          bookColumns: filterArr,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取列表头数据 -- 01040073
  getBookDetailsColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'optometryStandingBookDetails',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let filterArr = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (filterArr && filterArr.length > 0) {
        filterArr = filterArr && filterArr.length > 0 ? [...filterArr] : []
        this.setState({
          detailsColumns: filterArr,
          detailTotalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取库存数据
  getStandingBookData = (isTips) => {
    let { bookPage, bookPageSize, queryParam } = this.state;
    let data = {
      params: [{
        ...queryParam,
      }],
      pagination: [{
        currentPage: bookPage,
        pageSize: bookPageSize,
        sort: '',
        dir: 'Asc'
      }]
    }
    $http.post('urlS', this, {
      code: '17030051',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res.result?.rows || [];
          this.setState({ bookData: tableData, bookTotal: res.result?.total || 0, detailsData: [], detailsTotal: 0, stkLocID: '' });
          if (!(tableData && tableData.length > 0)) {
            isTips === 'N' ? '' : message.error('未查询到数据');
          }
        }
      }
    })
  }

  // 获取台账详情列表
  getBookDetailsData = (values) => {
    let { detailsPage, detailsPageSize } = this.state;
    let data = {
      params: [{
        stkLocID: values,
      }],
      pagination: [{
        currentPage: detailsPage,
        pageSize: detailsPageSize,
        sort: "",
        dir: "Asc"
      }]
    }
    $http.post('urlS', this, {
      code: '17030052',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res.result?.rows || [];
          this.setState({ detailsData: tableData, detailsTotal: res.result?.total || 0 });
          if (!(tableData && tableData.length > 0)) {
            message.error('未查询到产品详情数据')
          }
        }
      }
    })
  }

  // 修改查询接口入参
  handleInputChange = (e, dataIndex) => {
    let { queryParam } = this.state;
    queryParam[dataIndex] = e;
    this.setState({ queryParam })
  }

  // 导出
  handleExport = async () => {
    try {
      this.setState({ exportLoading: true });
      let { bookPage, bookPageSize, queryParam } = this.state;
      let data = {
        params: [{
          ...queryParam,
        }],
        pagination: [{
          currentPage: bookPage,
          pageSize: bookPageSize,
          sort: '',
          dir: 'Asc'
        }]
      }
      let res = await React.$asyncPost(this, '17060141', data);
      handleExcel.downloadExcel(res.result);
      this.setState({ exportLoading: false });
    } catch (error) {
      this.setState({ exportLoading: false });
    }
  }

  // 选择行
  onClickRowPublic = (record) => {
    return {
      onClick: () => {
        if (record.stkLocID !== '') {
          this.setState({ stkLocID: record.stkLocID }, () => {
            this.getBookDetailsData(this.state.stkLocID)
          })
        }
      }
    }
  }

  // 台账分页操作
  compileBookPage = (page, pageSize) => {
    this.setState({ bookPage: page, bookPageSize: pageSize }, () => {
      this.getStandingBookData();
    })
  }

  // 台账明细分页操作
  compileDetailsPage = (page, pageSize) => {
    this.setState({ detailsPage: page, detailsPageSize: pageSize }, () => {
      this.getBookDetailsData(this.state.stkLocID)
    })
  }

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

  render() {
    const { queryParam, selectData, bookData, bookColumns, detailsData, detailsColumns, bookPage, bookTotal, detailsPage, detailsTotal, totalWidth, loading, detailTotalWidth, exportLoading } = this.state;
    return (
      <div className="opt-standing-book-query">
        <Row style={{ padding: '0 24px' }}>
          <Col span={24} style={{ minHeight: '64px', paddingBottom: '12px' }} className="flex-wrap-align-items">
            <div className="flex-align-items" style={{ marginRight: 12, marginTop: '12px' }}>
              <span className="common-input-label">台账日期：</span>
              <RangeDatePicker
                width="280px"
                label=""
                isChange={true}
                format='YYYY-MM-DD'
                className='express-select-border'
                endDate={queryParam?.endDate}
                startDate={queryParam?.startDate}
                endChange={(e) => this.handleInputChange(e, 'endDate')}
                startChange={(e) => this.handleInputChange(e, 'startDate')}
              />
            </div>
            <div style={{ marginTop: '12px' }}>
              <span className="common-input-label">科室：</span>
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                className="common-query-input"
                optionFilterProp="search"
                value={queryParam?.locID || undefined}
                onChange={(e) => this.handleInputChange(e, 'locID')}
              >
                {React.$SelectOptions(selectData?.loc || [])}
              </Select>
            </div>
            <div style={{ marginTop: '12px' }}>
              <span className="common-input-label">库存子类：</span>
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                className="common-query-input"
                optionFilterProp="search"
                value={queryParam?.stkSubCat || undefined}
                onChange={(e) => this.handleInputChange(e, 'stkSubCat')}
              >
                {React.$SelectOptions(selectData?.stkSubCat || [])}
              </Select>
            </div>
            <div style={{ marginTop: '12px' }}>
              <span className="common-input-label">业务类型：</span>
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                className="common-query-input"
                optionFilterProp="search"
                value={queryParam?.busType || undefined}
                onChange={(e) => this.handleInputChange(e, 'busType')}
              >
                {React.$SelectOptions(selectData?.busType || [])}
              </Select>
            </div>
            <div style={{ marginTop: '12px' }}>
              <span className="common-input-label">统计标志：</span>
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                className="common-query-input"
                optionFilterProp="search"
                value={queryParam?.consumeTypeID || undefined}
                onChange={(e) => this.handleInputChange(e, 'consumeTypeID')}
              >
                {React.$SelectOptions(selectData?.consumeType || [])}
              </Select>
            </div>
            <div style={{ marginTop: '12px' }}>
              <span className="common-input-label">产品名称：</span>
              <Input
                placeholder="请输入"
                className="common-query-input"
                value={queryParam?.alias || undefined}
                onChange={(e) => this.handleInputChange(e.target.value, 'alias')}
              />
            </div>
            <div style={{ marginTop: '12px' }}>
              <span className="common-input-label">品牌：</span>
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                className="common-query-input"
                optionFilterProp="search"
                value={queryParam?.brandID || undefined}
                onChange={(e) => this.handleInputChange(e, 'brandID')}
              >
                {React.$SelectOptions(selectData?.brand || [])}
              </Select>
            </div>
            <div style={{ marginTop: '12px' }}>
              <span className="common-input-label">产品编码：</span>
              <Input
                placeholder="请输入"
                className="common-query-input"
                value={queryParam?.productCode || undefined}
                onChange={(e) => this.handleInputChange(e.target.value, 'productCode')}
              />
            </div>
            <div className="flex-align-items">
              <div style={{ marginTop: '12px' }}>
                <span className="common-input-label">显示业务损益：</span>
                <Switch
                  checkedChildren="开"
                  unCheckedChildren="关"
                  defaultChecked={false}
                  onChange={(e) => this.handleInputChange(e ? 'Y' : 'N', 'busLossFlag')}
                />
              </div>
              <Button style={{ marginLeft: '20px', marginTop: '12px' }} type="primary" onClick={this.getStandingBookData}>查询</Button>
              <Button
                ghost
                type="primary"
                style={{ marginLeft: '20px', marginTop: '12px' }}
                loading={exportLoading}
                onClick={this.handleExport}
              >
                导出
              </Button>
            </div>
          </Col>
        </Row>
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <Row className="table-body-height">
          <Col span={10}>
            <div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
              <Card
                title={(
                  <div className="card-title-left-img">
                    <img src={iconListVisits} alt="" />
                    产品列表
                  </div>
                )}
                bordered={false}
                size='small'
              >
                <PublicTablePagination
                  param={{
                    page: bookPage,
                    total: bookTotal,
                    loading,
                    x: totalWidth,
                    data: bookData,
                    rowKey: 'queID',
                    pageSize: '20',
                    componentName: 'optometryStandingBook',
                    y: store.getState().tableHeight.y - 14,
                    height: store.getState().tableHeight.y + 36,
                    columns: bookColumns && bookColumns.length > 0 ? bookColumns : this.staticColumns,
                  }}
                  compilePage={this.compileBookPage}
                  getColumns={this.getStandingBookColumns}
                  onClickRowPublic={this.onClickRowPublic}
                  setRowClassNamePublic={this.setRowClassNamePublic}
                />
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </Col>
          <Col span={14}>
            <Card
              title={(
                <div className="card-title-left-img">
                  <img src={iconListVisits} alt="" />
                  产品详情
                </div>
              )}
              bordered={false}
              size='small'
            >
              <PublicTablePagination
                param={{
                  page: detailsPage,
                  total: detailsTotal,
                  loading,
                  x: detailTotalWidth,
                  data: detailsData,
                  rowKey: 'queID',
                  pageSize: '20',
                  componentName: 'optometryStandingBookDetails',
                  y: store.getState().tableHeight.y - 14,
                  height: store.getState().tableHeight.y + 36,
                  columns: detailsColumns && detailsColumns.length > 0 ? detailsColumns : this.staticColumns,
                }}
                compilePage={this.compileDetailsPage}
                getColumns={this.getBookDetailsColumns}
              />
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
};

export default StandingBookQuery;