/*
 * Creator:     WRX
 * CreatDate:   2022-09-19
 * descripts：  视光 - 库存 - 产品退货单审核【弃用】
 * */
import React, {Component} from 'react';
import moment from "moment";
import {$http} from "../../../containers/config/https";
import {Button, Card, Icon, message, Select, Radio} from 'antd';
import RangeDatePicker from "../../../components/rangePicker";
import PubilcTablePagination from "../../common/PubilcTablePagination";
import store from 'store';

const {Option} = Select;

class SalesReturnVoucherReview extends Component {
  constructor(props) {
    super(props);
    this.userData = React.$getSessionData();
    this.patData = React.$getSessionData('titleData');
    this.state = {
      selectData: {},
      page: 1,
      pageSize: 20,
      total: 0,// 预约人数
      startDate: moment(),// 开始日期
      endDate: moment(),// 结束日期
      tableData: [],
      columns: [],
      totalWidth: '100%',
      loading: false,
      mainPage: 1,
      mainPageSize: 20,
      mainTotal: 0,
      detailsPage: 1,
      detailsPageSize: 20,
      detailsTotal: 0,
      mainData: [],
      mainColumns: [],
      detailsData: [],
      detailsColumns: [],
      mainWidth: '100%',
      detailsWidth: '100%',
      stkReturnIDs: [],
      detailSelectedRowKeys: [],
      stkReturnID: '',// 退货单ID
      stateID: 10,// 审核状态ID,
      loc: [], //科室下拉
      locID: '', // 科室ID
      vendor: [], // 供应商下拉
      vendorID: '',// 供应商ID
    }
  }

  componentDidMount() {
    this.getDefaultSelect();
    this.getMainTableColumns(); // 获取列表头数据 -- 01040073
    this.getDetailsTableColumns(); // 获取列表头数据 -- 01040073
  }

  // +----------------接口相关---------------+

  // 视光库存通用下拉
  getDefaultSelect = async () => {
    try {
      let data = {
        params: []
      }
      let res = await React.$asyncPost(this, '17030036', data);
      this.setState({vendor: res.vendor, loc: res.loc});
    } catch (error) {
      this.setState({vendor: [], loc: []});
    }
  }

  // 获取退货单列表头数据 -- 01040073
  getMainTableColumns = async () => {
    let operationObj = {
      width: 80,
      title: '操作',
      fixed: 'right',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <Button type="link" style={{color: "rgb(24, 141, 244)"}} size="small" disabled={record.stateDesc === '审核'}
                onClick={() => {
                  this.voucherAdjustHandle(record.stkReturnID)
                }}>审核</Button>
      ),
    };
    try {
      let data = {
        params: [{
          compontName: 'SalesReturnVoucherList',
          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, operationObj] : []
        this.setState({
          mainColumns: filterArr,
          mainWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取退货单详情列表头数据 -- 01040073
  getDetailsTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SalesReturnVoucherDetailsList',
          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,
          detailsWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取库存数据
  getMainTableData = (isTips) => {
    let {vendorID, locID, mainPage, mainPageSize, startDate, endDate, stateID} = this.state;
    let data = {
      params: [{
        begin: startDate.format('YYYY-MM-DD'),
        end: endDate.format('YYYY-MM-DD'),
        stateID: stateID,
        locID,
        vendorID,
      }],
      pagination: [{
        currentPage: mainPage,
        pageSize: mainPageSize,
        sort: "",
        dir: "Asc"
      }]
    }
    $http.post('urlS', this, {
      code: '17030040',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res.result?.rows || [];
          if (tableData && tableData.length > 0) {
            this.setState({mainData: tableData, mainTotal: res.result?.total || 0});
          } else {
            this.setState({mainData: [], mainTotal: 0});
            isTips === 'N' ? '' : message.error('未查询到数据');
          }
        }
      }
    })
  }

  // 获取退货详情列表
  getDetailsTableData = () => {
    let {detailsPage, detailsPageSize, stkReturnID} = this.state;
    let data = {
      params: [{
        stkReturnID   //主表ID
      }],
      pagination: [{
        currentPage: detailsPage,
        pageSize: detailsPageSize,
        sort: "",
        dir: "Asc"
      }]
    }
    $http.post('urlS', this, {
      code: '17030042',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let tableData = res.result?.rows || [];
          if (tableData && tableData.length > 0) {
            this.setState({detailsData: tableData, detailsTotal: res.result?.total || 0});
          } else {
            this.setState({detailsData: [], detailsTotal: 0});
            message.error('未查询到数据')
          }
        }
      }
    })
  }

  // 退货审核 -- 17030045
  voucherAdjustHandle = (record) => {
    let data = {
      params: [{
        stkReturnID: record   //主表ID
      }],
    }
    $http.post('urlS', this, {
      code: '17030045',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('审核成功')
          this.getMainTableData('N')
        }
      }
    })
  };

  // 调价批量审核 -- 17030045
  voucherAdjustHandleMass = () => {
    const {stkReturnIDs} = this.state
    let data = {
      params: [
        {
          stkReturnIDs   //主表ID
        }
      ],
    }
    $http.post('urlS', this, {
      code: '17030045',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('审核成功')
          this.getMainTableData('N')
        }
      }
    })
  };

  // +---------------查询条件相关-----------------+
  // 开始时间更换
  startDateChange = (e) => {
    this.setState({startDate: moment(e)})
  }

  // 结束时间更换
  endDateChange = (e) => {
    this.setState({endDate: moment(e)})
  }

  // 科室选择
  handleLocChange = (e) => {
    this.setState({locID: e})
  }
  // 供应商选择
  handleVendorChange = (e) => {
    this.setState({vendorID: e})
  }

  // 审核状态条件切换
  onChange = (checkedValues) => {
    this.setState({stateID: checkedValues.target.value, detailSelectedRowKeys: []})
  }

  // table复选项
  handleDetailSelectedRowKeysChange = (selectedRowKeys, selectedRows) => {
    let objArr = []
    let statusArr = []
    objArr = selectedRows
    objArr.map(item => {
      statusArr.push(item.stkReturnID)
    })
    this.setState({stkReturnIDs: statusArr})
  }

  // 行类名
  setRowClassNamePublic = (record) => {
    let rowStyle = ''
    let rowIdArr = []
    rowIdArr = this.state.stkReturnIDs
    rowIdArr.map(item => {
      if (item === record.stkReturnID) {
        rowStyle = 'clickRowStyle'
      }
    })
    return rowStyle
  }

  // 退货单分页操作
  compilePage = (page, pageSize) => {
    this.setState({page, pageSize}, () => {
      this.getMainTableData('N');
    })
  }

  // 退货单明细查询操作
  onMainRowChange = (record) => {
    this.setState({stkReturnID: record}, () => {
      this.getDetailsTableData()
    })
  }

  // 退货单明细分页操作
  compileDetailsPage = (page, pageSize) => {
    this.setState({page, pageSize}, () => {
      this.getDetailsTableData();
    })
  }

  // 选择一行退货单
  onClickRowPublic = (record) => {
    return {
      onClick: () => {
        if (record.stkReturnID !== '') {
          this.setState({stkReturnID: record.stkReturnID}, () => {
            this.getDetailsTableData()
          })
        }
      }
    }
  }

  render() {
    const {startDate, endDate, loc, vendor, mainWidth, detailsWidth, mainPage, mainTotal, detailsPage, detailsTotal, mainData, mainColumns, detailsData, detailsColumns, loading, detailSelectedRowKeys} = this.state;
    const options = [
      {label: '未审核', value: 10},
      {label: '已审核', value: 20}
    ];
    const detailRowSelection = {
      selectedRowKeys: detailSelectedRowKeys,
      onChange: this.handleDetailSelectedRowKeysChange
    };
    return (
      <div className="sales-return-voucher-review" style={{background: 'rgb(245,247,254)'}}>
        <Card title={<div><Icon type="minus-square" theme="twoTone" style={{marginRight: 5}}/>查询条件</div>}
              bordered={true} size='small'
              bodyStyle={{padding: "15px 20px"}}
              style={{marginBottom: 8}}
        >
          <div className="gmaf-header flex-wrap-align-items">
            <div style={{marginRight: 15}}>
              退货科室：
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                style={{width: 220}}
                optionFilterProp="search"
                onChange={this.handleLocChange}
              >
                {loc.map(item => {
                  return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                })}
              </Select>
            </div>
            <div style={{marginRight: 30}}>
              供应商：
              <Select
                allowClear
                showSearch
                placeholder="请选择"
                style={{width: 220}}
                optionFilterProp="search"
                onChange={this.handleVendorChange}
              >
                {vendor.map(item => {
                  return <Option key={item.id} value={item.id}>{item.descripts}</Option>
                })}
              </Select>
            </div>
            <div style={{marginRight: 15}}>
              <RangeDatePicker
                width="300px"
                label="日期："
                isChange={true}
                format='YYYY-MM-DD'
                className='express-select-border'
                startDate={startDate}
                endDate={endDate}
                startChange={this.startDateChange}
                endChange={this.endDateChange}
              />
            </div>
            <div style={{marginRight: 30}}>
              审核状态：
              <Radio.Group options={options} onChange={this.onChange} value={this.state.stateID}/>
              {/*<Checkbox.Group options={options} onChange={this.onChange} />*/}
            </div>
            <div style={{marginRight: 30}}>
              <Button style={{width: 80, padding: '0px 5px'}} type="primary" onClick={this.getMainTableData}>查询</Button>
            </div>
          </div>
        </Card>
        <Card title={<div><Icon type="minus-square" theme="twoTone" style={{marginRight: 5}}/>退货单列表</div>}
              bordered={true} size='small'
              bodyStyle={{padding: '20px 10px 0px 10px'}}
              style={{marginBottom: 2}}
        >
          <div style={{marginTop: -20}}>
            <Button type="link" style={{color: "black", padding: 0}} onClick={() => {
              this.voucherAdjustHandleMass()
            }}>
              <Icon type="snippets" style={{color: "rgb(250, 140, 23)"}}/>批量审核
            </Button>
          </div>
          <PubilcTablePagination
            param={{
              page: mainPage,
              total: mainTotal,
              loading,
              data: mainData, // 表格数据
              x: mainWidth, // 表格的宽度
              y: store.getState().tableHeight.y * 0.4,
              componentName: 'SalesReturnVoucherList', // 待处理表头
              height: store.getState().tableHeight.y * 0.475,
              columns: mainColumns && mainColumns.length > 0 ? mainColumns : [], // 表头配置
            }}
            compilePage={this.compilePage}
            getColumns={this.getMainTableColumns}
            onRef={ref => this.commonTableRef = ref}
            rowSelectionPublic={detailRowSelection}
            setRowClassNamePublic={this.setRowClassNamePublic}
            onClickRowPublic={this.onClickRowPublic}
          />
        </Card>
        <Card title={<div><Icon type="minus-square" theme="twoTone" style={{marginRight: 5}}/>退货单列表</div>}
              bordered={true} size='small'
              bodyStyle={{padding: '10px 10px 0px 10px'}}
        >
          <PubilcTablePagination
            param={{
              page: detailsPage,
              total: detailsTotal,
              loading,
              data: detailsData, // 表格数据
              x: detailsWidth, // 表格的宽度
              y: store.getState().tableHeight.y * 0.4,
              componentName: 'SalesReturnVoucherDetailsList', // 待处理表头
              height: store.getState().tableHeight.y * 0.45,
              columns: detailsColumns && detailsColumns.length > 0 ? detailsColumns : [], // 表头配置
            }}
            compilePage={this.compileDetailsPage}
            getColumns={this.getDetailsTableColumns}
            onRef={ref => this.commonTableRef = ref}
          />
        </Card>
      </div>
    );
  }
}

export default SalesReturnVoucherReview;