/*
 * Creater:     shizi
 * CreateDate:  2022/05/24
 * Describe：   收费项信息
 * */
import React, { Component } from 'react';
import { Card } from 'antd';
import { Util, dayFormat } from 'tools';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import DynamicRenderingForm from 'pages/common/DynamicRenderingForm';
import '../style/order-item.less';

class ChargeItemInformation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectData: {},
      rowData: {},
      basicInfoFormData: [], // 收费项基本信息表单数据
      priceInfoFormData: [], // 收费项价格信息表单数据
    };
    this.staticFieldsValue = {};
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    // 该方法内禁止访问this
    if (('selectData' in nextProps && (JSON.stringify(nextProps.selectData) !== JSON.stringify(prevState.selectData)))) {
      // 通过对比nextProps和prevState，返回一个用于更新状态的对象
      return {
        selectData: nextProps.selectData
      }
    }
    if (('rowData' in nextProps && (JSON.stringify(nextProps.rowData) !== JSON.stringify(prevState.rowData)))) {
      return {
        rowData: nextProps.rowData
      }
    }
    // 不需要更新状态，返回null
    return null
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    this.getBasicInfoFormData();
    this.getPriceInfoFormData();
  }

  componentDidUpdate(prevProps, prevState) {
    if (('selectData' in prevProps && (JSON.stringify(prevProps.selectData) !== JSON.stringify(this.state.selectData))) || ('rowData' in prevProps && (JSON.stringify(prevProps.rowData) !== JSON.stringify(this.state.rowData)))) {
      this.getBasicInfoFormData();
      this.getPriceInfoFormData();
    }
  }

  // 获取收费项基本信息表单数据
  getBasicInfoFormData = () => {
    let { priceCard } = this.props;
    let { selectData, manfSelectData, rowData } = this.state;
    let formData = [{
      key: 1,
      dataIndex: 'chargeTCID',
      title: '收费子类',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'TC' in selectData ? selectData.TC : [],
      // changeCallBack: this.handleChargeTCChange,
      // callBackResult: 'Fn',
      col: 6
    },
    {
      key: 2,
      dataIndex: 'chargeCode',
      title: '收费代码',
      typeCode: 'Input',
      required: 'Y',
      // disabled: 'Y',
      // disabled: rowData && 'chargeID' in rowData && rowData.chargeID ? 'Y' : 'N',
      col: 6
    },
    {
      key: 3,
      dataIndex: 'chargeDesc',
      title: '收费描述',
      typeCode: 'Input',
      required: 'Y',
      col: 6
    }, {
      key: 4,
      dataIndex: 'chargeUnitID',
      title: '单位',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'unit' in selectData ? selectData.unit : [],
      col: 6
    }, {
      key: 5,
      dataIndex: 'chargePCID',
      title: '物价分类',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'PC' in selectData ? selectData.PC : [],
      col: 6
    }, {
      key: 6,
      dataIndex: 'chargeMCID',
      title: '病案分类',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'MC' in selectData ? selectData.MC : [],
      col: 6
    }, {
      key: 7,
      dataIndex: 'chargeOCID',
      title: '门诊收据费用',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'OC' in selectData ? selectData.OC : [],
      col: 6
    }, {
      key: 8,
      dataIndex: 'chargeICID',
      title: '住院收据费用',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'IC' in selectData ? selectData.IC : [],
      col: 6
    }, {
      key: 9,
      dataIndex: 'chargeACID',
      title: '会计科目',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'AC' in selectData ? selectData.AC : [],
      col: 6
    }, {
      key: 10,
      dataIndex: 'chargeECID',
      title: '核算项目分类',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'EC' in selectData ? selectData.EC : [],
      col: 6
    }, {
      key: 11,
      dataIndex: 'chargeRegionTypeID',
      title: '地区',
      typeCode: 'Select',
      detailItem: selectData && 'regionType' in selectData ? selectData.regionType : [],
      col: 6
    }, {
      key: 12,
      dataIndex: 'chargeManfDesc',
      title: '厂家',
      typeCode: 'SearchSelect',
      valueindex: 'descripts', // 显示在界面上的值 -> 对应下拉数据返回的描述
      valueID: 'chargeManfID', // 需要存到后台的字段对应的id值
      onSearch: (e) => this.handleChargeSearch(e, 'basicInfoFormData', 11),
      detailItem: manfSelectData,
      loading: false,
      col: 6
    }];
    // 价格信息，供医嘱项目维护界面使用
    let priceData = [{
      key: 71,
      dataIndex: 'chargePrice',
      title: '价格',
      typeCode: 'Input',
      required: 'Y',
      disabled: rowData && 'chargeID' in rowData && rowData.chargeID ? 'Y' : 'N',
      col: 6
    }, {
      key: 72,
      dataIndex: "chargeApprovalNo",
      title: "批准文号",
      typeCode: 'Input',
      col: 6
    }, {
      key: 73,
      dataIndex: "chargeSpec",
      title: "规格",
      typeCode: 'Input',
      col: 6
    }, {
      key: 74,
      dataIndex: "pcCode",
      title: "物价代码",
      typeCode: 'Input',
      col: 6
    }, {
      key: 75,
      dataIndex: "pcDesc",
      title: "物价名称",
      typeCode: 'Input',
      col: 6
    }];
    // 其他信息，供收费项维护使用
    let otherData = [{
      key: 16,
      dataIndex: "chargeApprovalNo",
      title: "批准文号",
      typeCode: 'Input',
      col: 6
    }, {
      key: 17,
      dataIndex: "chargeSpec",
      title: "规格",
      typeCode: 'Input',
      col: 6
    }, {
      key: 18,
      dataIndex: "pcCode",
      title: "物价代码",
      typeCode: 'Input',
      col: 6
    }, {
      key: 19,
      dataIndex: "pcDesc",
      title: "物价名称",
      typeCode: 'Input',
      col: 6
    }, {
      key: 20,
      title: '备注',
      dataIndex: 'chargeRemarks',
      typeCode: 'Input',
      col: 24,
      formItemCol: { labelCol: 2, wrapperCol: 22 }
    }, {
      key: 21,
      title: '除外内容',
      dataIndex: 'chargeExcluded',
      typeCode: 'Input',
      col: 24,
      formItemCol: { labelCol: 2, wrapperCol: 22 }
    }, {
      key: 22,
      dataIndex: "chargeInclusion",
      title: '项目内涵',
      typeCode: 'Input',
      col: 24,
      formItemCol: { labelCol: 2, wrapperCol: 22 }
    }, {
      key: 23,
      dataIndex: "chargeExplain",
      title: '收费说明',
      typeCode: 'Input',
      col: 24,
      formItemCol: { labelCol: 2, wrapperCol: 22 }
    }]
    if (priceCard === 'none') {
      formData = [
        ...formData,
        ...otherData
      ]
    } else {
      formData = [
        ...formData,
        ...priceData
      ]
    }
    this.setState({ basicInfoFormData: formData })
  }

  // 根据收费子类获取书费代码
  handleChargeTCChange = async (e) => {
    // let { type } = this.props;
    let { rowData, selectData } = this.state;
    if (rowData && 'chargeID' in rowData && rowData.chargeID) return; // 存在收费项ID是不修改收费项描述
    let fieldsValue = {}
    try {
      let data = {
        params: [{
          subCatID: e
        }]
      }
      let res = await React.$asyncPost(this, '02020396', data);
      fieldsValue.chargeCode = res.result;
    } catch (error) {
      console.log(error)
    }
    let chargeTCDesc = Util.returnDataCccordingToAttributes(selectData?.TC, e)?.descripts;
    fieldsValue.chargePCID = Util.returnDataCccordingToAttributes(selectData?.PC, chargeTCDesc, 'descripts')?.id || undefined;
    fieldsValue.chargeMCID = Util.returnDataCccordingToAttributes(selectData?.MC, chargeTCDesc, 'descripts')?.id || undefined;
    fieldsValue.chargeOCID = Util.returnDataCccordingToAttributes(selectData?.OC, chargeTCDesc, 'descripts')?.id || undefined;
    fieldsValue.chargeICID = Util.returnDataCccordingToAttributes(selectData?.IC, chargeTCDesc, 'descripts')?.id || undefined;
    fieldsValue.chargeACID = Util.returnDataCccordingToAttributes(selectData?.AC, chargeTCDesc, 'descripts')?.id || undefined;
    fieldsValue.chargeECID = Util.returnDataCccordingToAttributes(selectData?.EC, chargeTCDesc, 'descripts')?.id || undefined;
    // 设置收费项相关信息
    this.setFieldsValue(fieldsValue);
  }

  // 厂家搜索事件
  handleChargeSearch = (value, dataSource, index) => {
    this.state[dataSource][index].loading = true;
    this.setState({});
    this.fetchCharge(value, manfSelectData => this.setState({ manfSelectData }, () => {
      this.state[dataSource][index].loading = false;
      this.getBasicInfoFormData();
    }));
  }

  fetchCharge = (value, callback) => {
    value = value.replace(/^\s+/, "").replace(/\s+$/, "");
    if (value === "") {
      let resData = [];
      callback(resData);
      return;
    }
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
    function fakeCharge() {
      let data = {
        params: [{
          desc: value
        }]
      }
      $http.post('urlS', this, {
        code: "02020352",
        data,
        success: function (res) {
          if (res.errorCode === '0') {
            callback(res.manf);
          }
        }
      });
    }
    this.timeout = setTimeout(fakeCharge, 300);
  }

  // 获取收费项价格信息表单数据
  getPriceInfoFormData = () => {
    let { rowData } = this.state;
    let formData = [{
      dataIndex: "chargeNum",
      title: '计费数量',
      typeCode: 'InputNumber',
      required: 'Y',
      col: 6,
    }, {
      dataIndex: 'startDate',
      title: '生效日期',
      typeCode: 'Date',
      required: 'Y',
      // defaultValue: Moment().add(1, 'days').format(dayFormat),
      defaultValue: Moment().format(dayFormat),
      // disabled: rowData && 'medLinkChargeID' in rowData && rowData.medLinkChargeID ? 'Y' : 'N',
      col: 6,
      disabledDate: rowData && 'medLinkChargeID' in rowData && rowData.medLinkChargeID ? this.disabledStDate : null
    }, {
      dataIndex: 'endDate',
      title: '失效日期',
      typeCode: 'Date',
      col: 6,
      disabledDate: this.disabledEndDate
    }];
    this.setState({ priceInfoFormData: formData })
  }

  // 开始日期不能选择今天和之前的日期
  disabledStDate = (current) => {
    return current && current < Moment().subtract(1, 'days').endOf('day');
  }

  // 结束日期不能选择今天之前的日期
  disabledEndDate = (current) => {
    return current && current < Moment(new Date(Date.parse(new Date()) - 86400000)).endOf('day');
  }

  // 获取数据
  getFieldsValue = () => {
    let basicInfoValues = this.basicInfoRef && this.basicInfoRef.getFieldsValue();
    let priceInfoValues = this.priceInfoRef && this.priceInfoRef.getFieldsValue();
    return {
      ...Util.convertUndefinedToNull(basicInfoValues),
      ...Util.convertUndefinedToNull(priceInfoValues),
      chargeNum: priceInfoValues && 'chargeNum' in priceInfoValues && (priceInfoValues.chargeNum || priceInfoValues.chargeNum === 0) ? Number(priceInfoValues.chargeNum) : ''
    }
  }

  // 表单赋值
  setFieldsValue = (values) => {
    this.basicInfoRef && this.basicInfoRef.setFieldsValue(values);
  }

  // 重置
  resetFields = () => {
    const { priceCard } = this.props;
    this.basicInfoRef && this.basicInfoRef.resetFields(); // 库存项基本信息数据
    if (priceCard !== 'none') {
      this.priceInfoRef && this.priceInfoRef.resetFields(); // 收费项信息
    }
  }

  // 保存
  handleSave = () => {
    const { selectData } = this.state;
    const { priceCard } = this.props;
    const unit = selectData && 'unit' in selectData ? selectData.unit : [];
    // 收费项信息
    this.basicInfoRef && this.basicInfoRef.handleSave().then(result => {
      this.staticFieldsValue = {
        ...this.staticFieldsValue,
        ...result
      }
    });
    if (priceCard !== 'none') {
      // 收费项信息
      this.priceInfoRef && this.priceInfoRef.handleSave().then(result => {
        this.staticFieldsValue = {
          ...this.staticFieldsValue,
          ...result,
          priceError: result.error,
          error: this.staticFieldsValue?.error,
          chargeUnitDesc: Util.returnDataCccordingToAttributes(unit, result?.chargeUnitID)?.descripts, // 单位
        }
      });
    }
  }

  // 获取表单数据
  getStaticFieldsValue = () => {
    return this.staticFieldsValue;
  }

  // 获取更改的数据
  getDiffData = () => {
    let { basicInfoFormData, rowData } = this.state;
    let newValues = this.getFieldsValue();
    let diffData = [];
    for (var i = 0; i < basicInfoFormData.length; i++) {
      let detailItem = 'detailItem' in basicInfoFormData[i] && basicInfoFormData[i].detailItem ? basicInfoFormData[i].detailItem : [];
      if (rowData[basicInfoFormData[i].dataIndex] !== newValues[basicInfoFormData[i].dataIndex]) {
        diffData.push({
          dataIndex: basicInfoFormData[i].dataIndex,
          title: basicInfoFormData[i].title,
          new: basicInfoFormData[i].typeCode === 'Select' && newValues[basicInfoFormData[i].dataIndex] && detailItem ? Util.returnDataCccordingToAttributes(detailItem, newValues[basicInfoFormData[i].dataIndex], 'id').descripts : newValues[basicInfoFormData[i].dataIndex],
          old: basicInfoFormData[i].typeCode === 'Select' && rowData[basicInfoFormData[i].dataIndex] && detailItem ? Util.returnDataCccordingToAttributes(detailItem, rowData[basicInfoFormData[i].dataIndex], 'id').descripts : rowData[basicInfoFormData[i].dataIndex]
        })
      }
    }
    return diffData;
  }

  render() {
    let { rowData, cardType, priceCard } = this.props;
    let { basicInfoFormData, priceInfoFormData } = this.state;
    return (
      <div className={cardType ? '' : 'charge-item-information'}>
        <Card
          type={cardType || ''}
          size="small"
          bordered={cardType ? true : false}
          title={cardType ? <div>基本信息</div> : <div className="card-title-left-icon"><div></div>收费项基本信息</div>}
        >
          <DynamicRenderingForm
            rowData={rowData || {}}
            formData={basicInfoFormData}
            formItemCol={{ labelCol: 8, wrapperCol: 16 }}
            onRef={ref => this.basicInfoRef = ref}
          />
        </Card>
        {priceCard === 'none' ? '' : (
          <Card
            size="small"
            bordered={false}
            title={(
              <div className="card-title-left-icon">
                <div></div>
                医嘱项关联收费项信息
                <span style={{ fontSize: '12px', color: '#999' }}>（以下信息为医嘱项与收费项关联的信息。）</span>
              </div>
            )}
          >
            <DynamicRenderingForm
              rowData={rowData || {}}
              formData={priceInfoFormData}
              formItemCol={{ labelCol: 8, wrapperCol: 16 }}
              onRef={ref => this.priceInfoRef = ref}
            />
          </Card>
        )}
      </div>
    )
  }
};

export default ChargeItemInformation;