/*
 * Creator:     WRX
 * CreatDate:   2022-09-19
 * descripts：  视光 - 库存 - 产品退货制单【弃用】
 * */
import React, {Component} from 'react';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import {Button, Card, Col, Row, Modal, Icon, message} from 'antd';
import {$http} from "../../../containers/config/https";
import HistoryPriceAdjustList from "./HistoryPriceAdjustList";
import iconInquire from 'assets/images/icon_Inquire.png';
import PubilcTablePagination from "../../common/PubilcTablePagination";
import store from 'store';

class SalesReturnVoucherEntry extends Component {
  constructor(props) {
    super(props);
    this.userData = React.$getSessionData();
    this.patData = React.$getSessionData('titleData');
    let userData = React.$getSessionData();
    this.state = {
      userData,
      selectData: {},
      queryRowData: {},
      queryFormData: [],
      headerClientHeight: 242,
      modalKey: '',// 历史单据弹窗KEY
      getDefaultSelect: {},
      modalSelectData: {},
      tableData: [],
      tempArr: [],
      vendorID:''
    }
    this.headerCardRef = React.createRef();
    this.staticModalTableColumns = [
      {
        key: 1,
        title: '产品代码',
        dataIndex: 'stockCode',
        align: 'center',
        width: 150
      }, {
        key: 2,
        title: '产品名称',
        dataIndex: 'stockDesc',
        align: 'center',
        width: 300
      }, {
        key: 3,
        title: '品牌',
        dataIndex: 'brandDesc',
        align: 'center',
        width: 100
      }, {
        key: 3,
        title: '品种',
        dataIndex: 'varietyDesc',
        align: 'center',
        width: 100
      }, {
        key: 4,
        title: '包装规格',
        dataIndex: 'stockSpec',
        align: 'center',
        width: 100
      }, {
        key: 5,
        title: '产地',
        dataIndex: 'sourceDesc',
        align: 'center',
        width: 100
      }, {
        key: 6,
        title: '医院进价',
        dataIndex: 'hospRp',
        align: 'center',
        width: 100
      }]
  }

  componentDidMount() {
    this.getQueryFormData();
    this.defaultSelectList();
    this.getSelectData();
    this.getTableColumns();
    this.getDefaultSelect();
    // console.log('userData',this.userData)
  }

  // 获取表头数据
  getTableColumns = async () => {
    try {
      let data = {
        params: [{
          compontName: 'SalesReturnVoucherEntry',
          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) {
        let columns = []
        columns = filterArr && filterArr.length > 0 ? [...filterArr] : []
        this.setState({
          columns: columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 获取下拉框数据
  getSelectData = async () => {
    try {
      let {userData} = this.state;
      let data = {
        params: [{
          hospID: userData?.hospID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17060001', data);
      this.setState({selectData: res, statusID: res?.defaultStatusID || ''}, () => {
        this.getQueryFormData();
      });
    } catch (error) {
      this.setState({selectData: {}});
    }
  }

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

  // 通用下拉列表 -- 17033006
  defaultSelectList = () => {
    let data = {
      params: [
        {
          adjStatus: 'Y',
          reason: 'Y',
          subCat: 'Y'
        }
      ]
    };
    $http.post('urlS', this, {
      code: '17033006',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({defaultSelect: res.result})
        }
      }
    })
  };

  // 退货界面保存或修改退货单
  returnVoucherHandle = async () => {
    try {
      let data = {
        params: [{
          stkReturnID: 8, //修改时传
          locID: 155,
          vendorID: 3,
          stkCatID: 1,
          reasonID: 41,
          remark: "111",
          detail: [
            {
              stkReturnDetailID: "8||1",  //修改时传
              stkLocBatID: "11||3",
              qty: 10,
              unitID: 49,
              remark: "1111"
            }
          ]
        }]
      }
      let res = await React.$asyncPost(this, '17030036', data);
      this.setState({defaultSelect: res}, () => {
        this.getQueryFormData();
      });
    } catch (error) {
      this.setState({defaultSelect: {}});
    }
  }

  // 获取查询表单数据
  getQueryFormData = () => {
    let {defaultSelect} = this.state;
    // console.log(defaultSelect)
    let queryFormData = [
      {
        required: 'Y',
        title: '退货科室',
        typeCode: 'Select',
        dataIndex: 'loc',
        detailItem: defaultSelect && 'loc' in defaultSelect ? defaultSelect.loc : [],
      },
      {
        title: '退货原因',
        typeCode: 'Select',
        dataIndex: 'reason',
        detailItem: defaultSelect && 'reason' in defaultSelect ? defaultSelect.reason : [],
      },
      {
        title: '制单人',
        typeCode: 'Select',
        dataIndex: 'creatUser',
        detailItem: defaultSelect && 'user' in defaultSelect ? defaultSelect.user : [],
      },
      {
        title: '库存子类',
        typeCode: 'Select',
        dataIndex: 'stkSubCat',
        detailItem: defaultSelect && 'stkSubCat' in defaultSelect ? defaultSelect.stkSubCat : [],
      },
      {
        title: '制单日期',
        typeCode: 'Date',
        dataIndex: 'createDate',
      },
      {
        title: '退货备注',
        typeCode: 'Input',
        dataIndex: 'remark',
      },
      {
        required: 'Y',
        title: '供应商',
        typeCode: 'Select',
        dataIndex: 'manfID',
        detailItem: defaultSelect && 'manf' in defaultSelect ? defaultSelect.manf : [],
      },
      {
        title: '退货单号',
        typeCode: 'Input',
        dataIndex: 'stkReturnNO',
      },
      {
        disabled: 'Y',
        title: '单据状态',
        typeCode: 'Select',
        dataIndex: 'stateID',
        detailItem: defaultSelect && 'state' in defaultSelect ? defaultSelect.state : [],
      }
    ];
    this.setState({queryFormData}, () => {
      let clientHeight = this.headerCardRef.current?.clientHeight || 242;
      this.setState({headerClientHeight: clientHeight})
    })
  }

  // 保存
  handleSave = async () => {
    try {
      let values = await this.queryFormRef.handleSave();
      // console.log("values", values)
      this.salesReturnHandle(values)
    } catch (error) {
      console.log(error)
    }
  }

  // 重置表单数据
  handleReset = () => {
    this.queryFormRef && this.queryFormRef.resetFields();
  }

  // 退货单提交
  salesReturnHandle = (values) => {
    const paramsArr = this.state.tempArr
    let data = {
      params: [
        {
          //stkReturnID:8, //修改时传
          locID: values.loc,
          vendorID: paramsArr[0].vendorID,
          stkCatID: values.stkSubCat,
          reasonID: values.reason,
          remark: values.remark,
          detail: [
            {
              //stkReturnDetailID:"8||1"  //修改时传
              stkLocBatID: "11||3",
              qty: paramsArr[0].qty,
              manfID: paramsArr[0].manfID,
              unitID: paramsArr[0].unitID,
              remark: paramsArr[0].remark,
            }
          ]
        }
      ],
    }
    $http.post('urlS', this, {
      code: '17030037',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          message.success('退货成功')
        }
      }
    })
  }

  // +---------------------历史调价记录弹窗相关------------------+
  showModal = async () => {
    try {
      let values = await this.queryFormRef.handleSave();
      if (values.manfID!=='' && values.manfID!==undefined){
        this.setState({
          visibleModal: true,vendorID:values.manfID
        });
      }
    } catch (error) {
      console.log(error)
    }
  };

  handleOk = () => {
    this.setState({
      visibleModal: false,
    });
  };

  handleCancel = () => {
    this.setState({
      visibleModal: false,
    });
  };

  // 确认选择产品
  handleConfirmSelect = record => {
    let addObj = {
      key: record?.stockCode || '',
      stockID: record?.stockID || '',
      stockDesc: record?.stockDesc || '',
      stockCode: record?.stockCode || '',
      unitID: record?.unitID || '',
      unitDesc: record?.unitDesc || '',
      preExeDate: record?.preExeDate || '',
      warrentNO: record?.warrentNO || '',
      WNODate: record?.WNODate || '',
      remark: record?.remark || '',
      hospRp: record?.hospRp || '',
      hospSp: record?.sp || '',
      brandID: record?.brandID || '',
      brandDesc: record?.brandDesc || '',
      colorID: record?.colorID || '',
      colorDesc: record?.colorDesc || '',
      qty: record?.qty || '',
      stkSourceDesc: record?.impTypeDesc || '',
      stkSourceID: record?.impTypeID || '',
      medSpec: record?.stockSpec || '',
      stkVarietyID: record?.varietyID || '',
      stkVarietyDesc: record?.varietyDesc || '',
    }
    this.inputFormRef && this.inputFormRef.setFieldsValue(addObj)
  }

  // 清空产品选择数据
  handleModalSelectClear = () => {
    this.setState({modalSelectData: {}});
    this.inputFormRef && this.inputFormRef.setFieldsValue({
      key: undefined,
      stockID: undefined,
      stockDesc: undefined,
      stockCode: undefined,
      unitID: undefined,
      preExeDate: undefined,
      warrentNO: undefined,
      WNODate: undefined,
      remark: undefined,
      hospRp: undefined,
      hospSp: undefined,
      brandID: undefined,
      colorID: undefined,
      qty: undefined,
      stkSourceID: undefined,
      medSpec: undefined,
      stkVarietyID: undefined,
    })
  }

  // 重置数据录入表单
  handleBillReset = () => {
    this.inputFormRef && this.inputFormRef.resetFields();
  }

  handleBillSave = async () => {
    try {
      let values = await this.inputFormRef.handleSave();
      this.queryFormRef && this.queryFormRef.setFieldsValue({stateID: '正在录入'})
      // console.log("values", values)
      // 缓存录入数据
      let newArr = this.state.tableData
      newArr.push(values)
      this.setState({tableData: newArr, tempArr: newArr})
    } catch (error) {
      console.log(error)
    }
  }

  // 录入顺序
  handleEntrySequence = () => {
  }

  render() {
    const {defaultSelect, modalSelectData, modalTableColumns, modalTotalWidth, queryRowData, queryFormData, headerClientHeight, modalKey, inputRowData, loading, tableData, totalWidth, columns} = this.state;
    const inputFormData = [
      {
        required: 'Y',
        title: '产品名称',
        typeCode: 'InputTable',
        dataIndex: 'stockDesc',
        className: '17030033',
        methodName: 'inputDesc'
      },
      {
        disabled: 'Y',
        title: '产品代码',
        typeCode: 'Input',
        dataIndex: 'stockCode',
      },
      {
        required: 'Y',
        title: '单位',
        typeCode: 'Select',
        dataIndex: 'unitID',
        detailItem: modalSelectData && 'unitArr' in modalSelectData ? modalSelectData.unitArr : [],
      },
      {
        title: '退货数量',
        typeCode: 'Input',
        dataIndex: 'qty',
      },
      {
        disabled: 'Y',
        title: '品牌',
        typeCode: 'Select',
        dataIndex: 'brandID',
      },
      {
        disabled: 'Y',
        title: '品种',
        typeCode: 'Select',
        dataIndex: 'stkVarietyID',
      },
      {
        disabled: 'Y',
        title: '规格型号',
        typeCode: 'Input',
        dataIndex: 'medSpec',
      },
      {
        disabled: 'Y',
        title: '生产厂家',
        typeCode: 'Select',
        dataIndex: 'manuDesc',
        detailItem: defaultSelect && 'manf' in defaultSelect ? defaultSelect.manf : [],
      },
      {
        disabled: 'Y',
        title: '产地',
        typeCode: 'Select',
        dataIndex: 'stkSourceID',
      },
      {
        disabled: 'Y',
        title: '医院进价',
        typeCode: 'Input',
        dataIndex: 'hospRp',
      },
      {
        disabled: 'Y',
        title: '医院售价',
        typeCode: 'Input',
        dataIndex: 'hospSp',
      },
      {
        disabled: 'Y',
        title: '库存批次',
        typeCode: 'Input',
        dataIndex: 'batNO',
      },
      {
        title: '备注',
        typeCode: 'Input',
        dataIndex: 'remark',
      }];
    return (
      <div className="voucher-preparation receipt-voucher-preparation">
        <Card
          size="small"
          bordered={false}
          ref={this.headerCardRef}
          title={(
            <div className="card-title-left-img">
              <img src={iconInquire} alt=""/>
              退货制单
            </div>
          )}
        >
          <Row>
            <Col span={16}>
              <DynamicRenderingForm
                formItemCol={{labelCol: 8, wrapperCol: 16, col: 8}}
                rowData={queryRowData}
                formData={queryFormData}
                onRef={ref => this.queryFormRef = ref}
              />
            </Col>
            <Col offset={1} span={7} style={{marginTop: 5}}>
              <Row style={{marginBottom: 17}}>
                <Button style={{width: '88px', marginRight: 20}} onClick={() => {this.showModal()}}>历史单据</Button>
                <Button style={{width: '88px'}} onClick={() => {
                }} disabled>完成</Button>
                <Button style={{width: '88px', marginLeft: 20}} type="primary" onClick={this.handleSave}>保存</Button>
              </Row>
              <Row style={{marginBottom: 17}}>
                <Button style={{width: '88px', marginRight: 20}} onClick={this.handleReset}>重置</Button>
                <Button style={{width: '88px'}} onClick={() => {
                }} disabled>取消完成</Button>
                <Button style={{width: '88px', marginLeft: 20}} type="danger">删除</Button>
              </Row>
              <Row>
                <Button style={{width: '88px', marginRight: 20}}>打印</Button>
              </Row>
            </Col>
          </Row>
        </Card>

        <div className="common-query-split-line" style={{height: 8}}></div>
        <div className="vp-details-content flex">
          <div className="vp-details-left" style={{display: 'block', width: '40%'}}>
            <div style={{paddingRight: '6px', position: 'relative', height: '100%'}}>
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <Icon type="minus-square" theme="twoTone" style={{marginRight: 5}}/>
                    数据录入
                  </div>
                )}
              >
                <div className="scroll-bar-style" style={{
                  height: store.getState().tableHeight.y + 174 - headerClientHeight,
                  paddingRight: 32,
                  overflow: 'auto'
                }}>
                  <DynamicRenderingForm
                    isEnterJump='Y'
                    formItemCol={{labelCol: 8, wrapperCol: 16, col: 12}}
                    rowData={inputRowData}
                    formData={inputFormData}
                    modalTotalWidth={modalTotalWidth}
                    modalColumns={modalTableColumns && modalTableColumns.length > 0 ? modalTableColumns : this.staticModalTableColumns}
                    onRef={ref => this.inputFormRef = ref}
                    handleQueryFormData={this.getDetailColumns}
                    modalConfirmSelect={this.handleConfirmSelect}
                    modalSelectClear={this.handleModalSelectClear}
                  />
                  <div className="flex-center" style={{marginTop: 12, paddingLeft: 32}}>
                    <Button
                      ghost
                      type="primary"
                      onClick={this.handleEntrySequence}
                    >
                      录入顺序
                    </Button>
                    <Button
                      style={{margin: '0 20px'}}
                      onClick={this.handleBillReset}
                    >
                      重置
                    </Button>
                    <Button
                      type="primary"
                      onClick={this.handleBillSave}
                    >
                      添加到列表
                    </Button>
                  </div>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{width: 8}}></div>
            </div>
          </div>
          <div className="vp-details-right" style={{width: '60%'}}>
            <Card
              size="small"
              bordered={false}
              title={(
                <div className="card-title-left-img">
                  <Icon type="minus-square" theme="twoTone" style={{marginRight: 5}}/>
                  明细列表
                </div>
              )}
            >
              <PubilcTablePagination
                param={{
                  loading,
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y + 124 - headerClientHeight,
                  componentName: 'SalesReturnVoucherEntry',
                  height: store.getState().tableHeight.y + 174 - headerClientHeight + 'px',
                  columns: columns && columns.length > 0 ? columns : [], // 表头配置
                }}
                getColumns={this.getTableColumns}
                //onClickRowPublic={this.onClickRowPublic}
              />
            </Card>
          </div>
        </div>
        <Modal
          key={modalKey}
          title="历史调价单"
          visible={this.state.visibleModal}
          onCancel={this.handleCancel}
          footer={false}
          width="60%"
          destroyOnClose
          bodyStyle={{padding: 0, height: 570}}
        >
          <HistoryPriceAdjustList handleThis={this} compontName="SalesReturnVouchingCheck" interfaceCode="17030040" params={{vendorID:this.state.vendorID}}/>
        </Modal>
      </div>
    )
  }
}

export default SalesReturnVoucherEntry;