/*
 * Create:      柿子
 * CreateDate:  2022/09/06
 * Describe：   库房 - 制单明细录入公共组件【老版原型，已遗弃】
 * */
import React, { Component } from 'react';
import { Card, Button, Icon } from 'antd';
import store from 'store';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import iconListvisits from 'assets/images/icon_listvisits.png';
import iconMessages from 'assets/images/icon_messages.png';
import '../style/index.less';

class VoucherPreparationDetails extends Component {
  constructor(props) {
    let userData = React.$getSessionData();
    super(props);
    this.state = {
      userData,
      inputRowData: {},
      inputFormData: [],
      loading: false,
      tableData: [],
      totalWidth: 0,
      columns: [],
      formVisible: false
    };

    this.staticColumns = [{
      key: 1,
      title: '产品代码',
      dataIndex: 'medCode',
      align: 'center',
      width: 150
    }, {
      key: 2,
      title: '产品名称',
      dataIndex: 'medDesc',
      align: 'center',
      width: 300
    }, {
      key: 3,
      title: '数量',
      dataIndex: 'num',
      align: 'center',
      width: 100
    }, {
      key: 4,
      title: '单位',
      dataIndex: 'medUnitDesc',
      align: 'center',
      width: 100
    }, {
      key: 5,
      title: '医院进价',
      dataIndex: 'hospRp',
      align: 'center',
      width: 100
    }, {
      key: 6,
      title: '售价',
      dataIndex: 'sp',
      align: 'center',
      width: 100
    }, {
      key: 7,
      title: '医院进价金额',
      dataIndex: 'hospRpAmt',
      align: 'center',
      width: 150
    }, {
      key: 8,
      title: '售价金额',
      dataIndex: 'spAmt',
      align: 'center',
      width: 100
    }];
  }

  componentDidMount() {
    this.getTableColumns();
    this.getInputFormData();
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    if (JSON.stringify(nextProps.selectData) !== JSON.stringify(prevState.selectData)) {
      return {
        selectData: nextProps.selectData
      }
    }
    return null
  }

  componentDidUpdate(prevState) {
    if (JSON.stringify(prevState.selectData) !== JSON.stringify(this.state.selectData)) {
      this.updateInputFormData();
    }
  }

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

  // 获取表单录入数据
  getInputFormData = () => {
    const { componentName, formData } = this.props;
    if (componentName) {
      const { userData } = this.state;
      let data = {
        params: [{
          compontName: componentName,
        }]
      };
      $http.post('urlS', this, {
        code: "02020206",
        data: data,
        success: function (res) {
          if (res.errorCode === '0') {
            this.setState({
              inputFormData: userData.language === 'EN' ? res.result[0].ENRows : res.result[0].CNRows,
              // ColNum: res.result[0].columns,
              // typeID: res.result[0].typeID,
              // columnsData: res.result[0].componet.C,
              // languageSize: userData.language === 'EN' ? res.result[0].componet.language.EN : res.result[0].componet.language.CN
            });
          }
        }
      })
    } else {
      this.setState({ inputFormData: formData })
    }
  }

  // 下拉数据更新表单重新赋值
  updateInputFormData = () => {
    let { inputFormData, selectData } = this.state;
    if (inputFormData && inputFormData.length > 0) {
      for (let i = 0; i < inputFormData.length; i++) {
        if (selectData && Object.prototype.toString.call(selectData) === '[object Object]') {
          for (let keys in selectData) {
            if (inputFormData[i].dataIndex === keys) {
              inputFormData[i].detailItem = selectData[keys] || [];
            }
          }
        }
      }
      this.setState({});
    }
  }

  // 操作行
  onClickRowPublic = (record) => {
    return {
      // 单击行选中
      onClick: () => {
        if (this.state.rowID === '' || (this.state.rowID && (this.state.rowID !== record.key))) {
          this.setState({ rowID: record.key });
        } else {
          this.setState({ rowID: '' });
        }
      }
    }
  }

  // 选中行操作
  setRowClassNamePublic = (record) => {
    return record.key === this.state.rowID ? 'clickRowStyle' : '';
  }

  // 展开收起明细列表
  handleformVisible = () => {
    let { formVisible } = this.state;
    this.setState({ formVisible: !formVisible })
  }

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

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

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

  }

  render() {
    const { headerHeight, spTotal, rpTotal } = this.props;
    const { inputRowData, inputFormData, loading, tableData, totalWidth, columns, formVisible } = this.state;

    return (
      <div className="voucher-preparation-details">
        <div className="common-query-split-line" style={{ height: 8 }}></div>
        <div className="vp-details-content flex">
          <div className="vp-details-left" style={{ display: formVisible ? 'none' : 'block', width: formVisible ? 0 : '40%' }}>
            <div style={{ paddingRight: '6px', position: 'relative', height: '100%' }}>
              <Card
                size="small"
                bordered={false}
                title={(
                  <div className="card-title-left-img">
                    <img src={iconMessages} alt="" />
                    数据录入
                  </div>
                )}
                extra={(
                  formVisible ? '' : (
                    <Button type="link" onClick={this.handleformVisible}>
                      <Icon type="double-left" />
                      收起录入表单
                    </Button>
                  )
                )}
              >
                <div className="scroll-bar-style" style={{ height: store.getState().tableHeight.y + 174 - headerHeight, paddingRight: 32, overflow: 'auto' }}>
                  <DynamicRenderingForm
                    formItemCol={{ labelCol: 8, wrapperCol: 16, col: 12 }}
                    rowData={inputRowData}
                    formData={inputFormData}
                    onRef={ref => this.formRef = ref}
                  />
                  <div className="flex-center" style={{ marginTop: 12, paddingLeft: 32 }}>
                    <Button
                      ghost
                      type="primary"
                      onClick={this.handleEntrySequence}
                    >
                      录入顺序
                    </Button>
                    <Button
                      style={{ margin: '0 20px' }}
                      onClick={this.handleReset}
                    >
                      重置
                    </Button>
                    <Button
                      type="primary"
                      onClick={this.handleSave}
                    >
                      添加到列表
                    </Button>
                  </div>
                </div>
              </Card>
              <div className="common-card-right-split-line" style={{ width: 8 }}></div>
            </div>
          </div>
          <div className="vp-details-right" style={{ width: formVisible ? '100%' : '60%' }}>
            <Card
              size="small"
              bordered={false}
              title={(
                <div className="card-title-left-img">
                  <img src={iconListvisits} alt="" />
                  明细列表
                  <div className="vp-details-amt" style={{ display: spTotal && rpTotal ? 'block' : 'none' }}>
                    进价金额总计：<span style={{ marginRight: 12 }}>{rpTotal}</span>
                    售价金额总计：<span>{spTotal}</span>
                  </div>
                </div>
              )}
              extra={(
                formVisible ? (
                  <Button type="link" onClick={this.handleformVisible}>
                    展开录入表单
                    <Icon type="double-right" />
                  </Button>
                ) : ''
              )}
            >
              <PubilcTablePagination
                param={{
                  loading,
                  data: tableData, // 表格数据
                  x: totalWidth, // 表格的宽度
                  y: store.getState().tableHeight.y + 124 - headerHeight,
                  componentName: 'ReceiptVoucherPreparation',
                  height: store.getState().tableHeight.y + 174 - headerHeight + 'px',
                  columns: columns && columns.length > 0 ? columns : this.staticColumns, // 表头配置
                }}
                getColumns={this.getTableColumns}
                onClickRowPublic={this.onClickRowPublic}
                setRowClassNamePublic={this.setRowClassNamePublic}
              />
            </Card>
          </div>
        </div>
      </div>
    )
  }
};

export default VoucherPreparationDetails;