/*
 * Creator:     WRX
 * CreatDate:   2022-08-25
 * descripts：  视光 - 库房 - 调价制单【弃用】
 * */
import React, {Component} from 'react';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import {Button, Card, Col, Row, Modal, message, Icon, Tooltip} from 'antd';
import {$http} from "../../../containers/config/https";
import HistoryPriceAdjustList from "./HistoryPriceAdjustList";
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import moment from "moment";
import store from 'store';


class PriceAdjustBillEntry 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
      SelectData: {}, // 下拉框数据
      detailInfo: [], // 明细列表数据
      inOpLocDr: '',
      toLocDr: '',
      stkCat: '',
      inputRowData: {},
      inputFormData: [],
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      formVisible: false,
      tempArr: [],
      defaultSelect: {},
      perData: moment().format('YYYY-MM-DD'),
      modalSelectData: {},
      queryParams:{}
    }
    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.getSelectData();
    this.getQueryFormData();
    this.getTableColumns();
    this.defaultSelectList();
  }

  // 通用下拉列表 -- 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})
        }
      }
    })
  };

  // 获取下拉框数据
  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: {}});
    }
  }

  // 获取查询表单数据
  getQueryFormData = () => {
    let {defaultSelect} = this.state;
    let queryFormData = [
      {
        title: '制单日期',
        typeCode: 'Date',
        dataIndex: 'createDate',
      },
      {
        //required: 'Y',
        title: '调价人员',
        typeCode: 'Select',
        dataIndex: 'purUserID',
        detailItem: [{"id":this.userData.userID,"descripts":this.userData.userName}],
      },
      {
        disabled: 'Y',
        title: '调价单号',
        typeCode: 'Input',
        dataIndex: 'adjNO',
      },
      {
        disabled: 'Y',
        title: '单据状态',
        typeCode: 'Select',
        dataIndex: 'stateID',
        detailItem: defaultSelect && 'adjStatus' in defaultSelect ? defaultSelect.adjStatus : [],
      },
      {
        title: '调价备注',
        typeCode: 'Input',
        dataIndex: 'remark',
      }];
    this.setState({queryFormData}, () => {
      let clientHeight = this.headerCardRef.current?.clientHeight || 242;
      this.setState({headerClientHeight: clientHeight})
    })
  }

  // 调价单保存 -- 17033008
  adjustBillHandle = () => {
    const paramsArr = this.state.tempArr
    let data = {
      params: [
        {
          stockDesc: paramsArr[0].stockDesc,
          priorSp: paramsArr[0].priorSp,
          resultSp: paramsArr[0].resultSp,
          preExeDate: paramsArr[0].preExeDate,
          hosp: 50,
          warrentNO: paramsArr[0].warrentNO,
          WNODate: paramsArr[0].WNODate,
          remark: paramsArr[0].remark,
          batNo: "",
          preDate: this.state.perData,
          unitDesc: "盒",
          unitID: paramsArr[0].unitID,
          reasonDesc: "政策性调价",
          reasonID: paramsArr[0].reason,
          stockID: this.state.modalSelectData.stockID,
          stkBatID: "",
          key: "0detail",
          unit: this.state.modalSelectData.unitArr,
          reason: [
            {
              "id": "32",
              "code": "75",
              "descripts": "政策性调价"
            }
          ],
        }
      ],
    }
    $http.post('urlS', this, {
      code: '17033003',
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          //message.success('调价成功')
          message.success('调价成功')
          this.queryFormRef && this.queryFormRef.setFieldsValue(
            {
              //createDate:res.result[0].createDate,
              adjNO: res.result[0].adjNO,
              remark: res.result[0].remark,
              purUserID: res.result[0].createUser.id,
              stateID: res.result[0].state.id,
            }
          );
          this.setState({tableData: [], tempArr: []})
        }
      }
    })
  };

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

  handleBillSave = async () => {
    try {
      let values = await this.inputFormRef.handleSave();
      if(values.stockCode===undefined||values.stockDesc===undefined||values.unitID===undefined||values.resultSp===undefined||values.priorSp===undefined){
        message.warn("请录入完整数据")
      }else{
        this.queryFormRef && this.queryFormRef.setFieldsValue({stateID: '正在录入'})
        let newArr = this.state.tableData
        newArr.push(values)
        this.setState({tableData: newArr, tempArr: newArr})
      }
    } catch (error) {
      console.log(error)
    }
  }


  // 重置表单数据
  handleReset = () => {
    this.queryFormRef && this.queryFormRef.resetFields();
    this.setState({tableData: [], tempArr: []})
  }

  // +---------------------历史调价记录弹窗相关------------------+
  showModal = async () => {
    let values = await this.queryFormRef.handleSave();
    this.setState({
      visibleModal: true,
      queryParams:values
    });
  };

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

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

  //显示选取请求单
  selectRequisition = () => {
    this.getInOpLocDr();
    this.childSelect.showModal(this.state.SelectData);
  }
  changeStkCat = (v) => {
    this.setState({stkCat: v})
  };
  changesDesc = (v) => {
    this.setState({toLocDr: v})
  };


  detailOnRef = (ref) => {
    this.childDetail = ref;
  };

  // 重置所有内容
  resetFieldsAll = () => {
    this.props.form.resetFields(); //清空所有
    this.setState({detailInfo: [], rowId: "", statusId: '', filterLoc: ''});
    this.childDetail.resetFields();
    this.childDetail.deleteData();
  }

  //获取中英版
  getChineseEnglishSize = (v) => {
    this.setState({ChineseEnglishSize: v})
  };

  // 获取表头数据
  getTableColumns = async () => {
    let operationObj = {
      width: 80,
      title: '操作',
      fixed: 'right',
      align: 'center',
      key: 'operation',
      render: (text, record) => (
        <Button type="link" style={{color: "red"}} size="small" onClick={() => {this.onRowDelete(record)}}>删除</Button>
      ),
    };
    try {
      let data = {
        params: [{
          compontName: 'ProductPriceAdjustmentDetail',
          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,operationObj] : []
        this.setState({
          columns: columns,
          totalWidth: res.totalWidth
        })
      }
    } catch (error) {
      console.log(error)
    }
  }

  // 删除行数据
  onRowDelete=(record)=>{
    let newArr = this.state.tableData
    newArr.map((item,index)=>{
      if(record===item){
        newArr.splice(index,1)
        this.setState({tableData: newArr, tempArr: newArr})
      }
    })
  }

  // 确认选择产品
  handleConfirmSelect = record => {
    this.setState({modalSelectData: record});
    this.inputFormRef && this.inputFormRef.setFieldsValue({
      stockDesc: record?.stockDesc || '',
      stockCode: record?.stockCode || '',
      unitID: record?.unitID || '',
      preExeDate: record?.preExeDate || '',
      warrentNO: record?.warrentNO || '',
      WNODate: record?.WNODate || '',
      remark: record?.remark || '',
      rp: record?.rp || '',
      resultSp: record?.sp || '',
      priorSp: record?.sp || '',
      spAmt: record?.spAmt || '',
      rpAmt: record?.rpAmt || '',
      key: record?.stockCode || '',
    })
  }

  // 清空产品选择数据
  handleModalSelectClear = () => {
    this.setState({modalSelectData: {}});
    this.inputFormRef && this.inputFormRef.setFieldsValue({
      stockDesc: undefined,
      stockCode: undefined,
      stockID: undefined,
      unitID: undefined,
      preExeDate: undefined,
      reason: undefined,
      warrentNO: undefined,
      WNODate: undefined,
      remark: undefined,
      spAmt: undefined,
      rpAmt: undefined,
      rp: undefined,
      key: undefined,
    })
  }

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

  // 获取明细表头数据
  getDetailColumns = async () => {
    try {
      const {category} = this.state;
      let componentName = Util.getValueByUrlStr(category, 'componentName');
      let data = {
        params: [{
          compontName: componentName + 'Detail',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let detailColumns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (detailColumns && detailColumns.length > 0) {
        detailColumns = detailColumns.map(item => {
          return {
            ...item,
            render: (text) => {
              return (
                <Tooltip title={text}>
                  <span className='ellipsis' style={{width: '100%', display: 'inline-block'}}>{text}</span>
                </Tooltip>
              );
            },
          }
        })
        this.setState({
          detailColumns,
          detailTotalWidth: res.totalWidth
        });
      }
      // 表单操作数据
      let inputFormData = res.result && res.result.formData && res.result.formData.length > 0 ? res.result.formData : [];
      let inputFormButton = [{
        col: 4,
        title: '清空',
        typeCode: 'Button',
        onClick: this.handleDetailEmpty,
        style: {textAlign: 'right', lineHeight: '40px', paddingRight: '30px'}
      }, {
        col: 2,
        title: '保存',
        ghost: true,
        type: 'primary',
        typeCode: 'Button',
        onClick: this.handleDetailSave,
        style: {lineHeight: '40px'}
      }]
      if (!(inputFormData && inputFormData.length > 0)) {
        inputFormData = this.getInputFormData();
      }
      this.setState({inputFormData: [...inputFormData, ...inputFormButton]}, () => {
        this.handleSelectDataAssignment('inputFormData');
      });
    } catch (error) {
      console.log(error);
    }
  }

  getModalTableColumns = async () => {
    try {
      const {category} = this.state;
      let componentName = Util.getValueByUrlStr(category, 'componentName');
      let data = {
        params: [{
          compontName: componentName + 'ModalTable',
          type: 'C',
        }]
      }
      let res = await React.$asyncPost(this, '01040073', data);
      let modalTableColumns = res.result && res.result.C && res.result.C.length > 0 ? res.result.C : [];
      if (modalTableColumns && modalTableColumns.length > 0) {
        this.setState({
          modalTableColumns,
          modalTotalWidth: res.totalWidth
        });
      }
    } catch (error) {
      console.log(error);
    }
  }

  // 明细行操作
  handleDetailRowClick = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.detailRowID === '' || (this.state.detailRowID && (this.state.detailRowID !== record.key))) {
          this.setState({detailRowID: record.key, detailRowData: record}, () => {
            this.handleModifyBtnTitle();
          });
        } else {
          this.handleDetailEmpty();
        }
      }
    }
  }

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

  // 数据选择
  historyDataFill = (record)=>{
    console.log(record)
    // WNODate: ""
    // adjID: 130
    // adjNO: "SGCPKOPTADJ202209300001"
    // auditDate: "2022-09-30"
    // auditTime: "09:23:51"
    // auditUser: {id: "1028", desc: "单颖彬"}
    // auditUserName: "单颖彬"
    // batNo: ""
    // createDate: "2022-09-30"
    // createTime: "09:18:42"
    // createUser: {id: "1028", desc: "单颖彬"}
    // createUserName: "单颖彬"
    // exeDate: ""
    // groupRp: 5900
    // hosp: "50"
    // hospDesc: "演示医院"
    // hospRp: 8800
    // preExeDate: "2022-10-10"
    // priorSp: 111
    // reasonDesc: "政策性调价"
    // reasonID: "32"
    // remark: ""
    // resultBaseSp: 112
    // resultSp: 112
    // state: {id: "97", desc: "已审核"}
    // stateDesc: "已审核"
    // stkDescAstkBatNo: "亨泰角膜塑形镜3.00-5.00--"
    // stock: {stockID: 585, stockDesc: "亨泰角膜塑形镜3.00-5.00", stkBatID: "", stkBatNo: ""}
    // stockDesc: "亨泰角膜塑形镜3.00-5.00"
    // stockID: 585
    // tradeName: ""
    // unit: {id: "395", desc: "片"}
    // unitDesc: "片"
    // unitID: "395"
    // warrentNO: ""
    this.inputFormRef && this.inputFormRef.setFieldsValue({
      stockDesc: record?.stockDesc || '',
    })
    this.queryFormRef && this.queryFormRef.setFieldsValue({
      adjNO: record?.adjNO || '',
    })
    this.handleOk()
  }

  // 操作弹框
  onClickRowPublic = (record) => {
    return {
      onClick: () => {

      }
    }
  }

  // 行样式
  setRowClassNamePublic = (record) => {
    return  'clickRowStyle'
  }

  disabledDate(current) {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }

  render() {
    const {modalSelectData, modalTableColumns, modalTotalWidth, defaultSelect, 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 : [],
      },
      {
        disabled: 'Y',
        title: '调前售价',
        typeCode: 'Input',
        dataIndex: 'priorSp',
      },
      {
        required: 'Y',
        title: '调后售价',
        typeCode: 'Input',
        dataIndex: 'resultSp',
      },
      {
        required: 'Y',
        title: '生效日期',
        key:'preExeDate',
        typeCode: 'Date',
        dataIndex: 'preExeDate',
        disabledDate:this.disabledDate
      },
      {
        required: 'Y',
        title: '调价原因',
        typeCode: 'Select',
        dataIndex: 'reason',
        detailItem: defaultSelect && 'reason' in defaultSelect ? defaultSelect.reason : [],
      },
      {
        title: '批准文号',
        typeCode: 'Input',
        dataIndex: 'warrentNO',
      },
      {
        title: '批文日期',
        typeCode: 'Date',
        dataIndex: 'WNODate',
        key:'WNODate',
      }, {
        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">
              <Icon type="minus-square" theme="twoTone" style={{marginRight: 5}}/>
              调价制单
            </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: 15}}>
                <Button style={{width: '88px'}} onClick={() => {
                  this.showModal()
                }}>历史单据</Button>
                <Button style={{width: '88px', marginLeft: 20}} onClick={this.handleReset}>重置</Button>
              </Row>
              <Row>
                <Button style={{width: '88px', marginRight: 20}} type="primary" onClick={this.handleSave}>保存</Button>
                <Button style={{width: '88px'}} type="danger" disabled>删除</Button>
                <Button style={{width: '88px', marginLeft: 20}} disabled>打印</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: 'ProductPriceAdjustmentDetail',
                  height: store.getState().tableHeight.y + 174 - headerClientHeight + 'px',
                  columns: columns && columns.length > 0 ? columns : [], // 表头配置
                }}
                getColumns={this.getTableColumns}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </Card>
          </div>
        </div>
        {/*<VoucherPageDetails headerHeight={headerClientHeight} selectData={selectData} formData={this.inputFormData} componentName='PriceAdjustmentFormEnt'/>*/}
        <Modal
          key={modalKey}
          title="历史调价单"
          visible={this.state.visibleModal}
          onCancel={this.handleCancel}
          footer={false}
          width="60%"
          destroyOnClose
          bodyStyle={{padding: 0, height: store.getState().tableHeight.y * 0.78 + 50}}
        >
          <HistoryPriceAdjustList
            rowFill={this.historyDataFill}
            compontName="HistorySheetList"
            interfaceCode="17033004"
            params={{
              startDate:this.state.queryParams.createDate,
              endDate:this.state.queryParams.createDate
            }}
          />
        </Modal>
      </div>
    )
  }
}

export default PriceAdjustBillEntry;