/*
 * Creater:     shizi
 * CreateDate:  2022/05/25
 * Describe：   新增收费项
 * */
import React, { Component } from 'react';
import { Card, Button, message, Spin, Divider, Popconfirm, Modal } from 'antd';
import { Util } from 'tools';
import { $http } from 'containers/config/https';
import Moment from 'moment';
import ChargeItemInformation from './ChargeItemInformation';
import PubilcTablePagination from 'pages/common/PubilcTablePagination.jsx';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';
import '../style/order-item.less';

const { confirm } = Modal;

class AddChargItem extends Component {
  constructor(props) {
    super(props);
    var userData = JSON.parse(sessionStorage.getItem('userData'));
    this.state = {
      userData,
      rowData: {},
      selectData: {},
      priceColumns: [], // 价格信息表头数据
      priceTableData: [],
      priceLoading: false,
      priceTotalwidth: 910,
      contrastColumns: [], // 医保对照表头数据
      contrastTableData: [],
      contrastLoading: false,
      contrastTotalwidth: 800,
      priceFormData: [],
      priceRowData: {},
      contrastFormData: [],
      contrastRowData: {},
      insuranceCatalogSelectData: [], // 医保目录下拉数据
      loading: false
    };
    this.timeout = null;
  }

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

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    this.getPriceColumns();
    this.getPriceFormData();
    // this.getContrastColumns();
    // this.getContrastFormData();
  }

  componentDidUpdate(prevProps, prevState) {
    if ('selectData' in prevProps && (JSON.stringify(prevProps.selectData) !== JSON.stringify(this.state.selectData))) {
      this.getPriceFormData();
      // this.getContrastFormData();
    }
  }

  // 查询医嘱维护的详细信息
  queryRowDataByID = async (id, isCopy) => {
    try {
      let data = {
        params: [{
          hospChargeItemID: id
        }]
      }
      let res = await React.$asyncPost(this, '02020391', data);
      let priceTableData = 'chargePriceArr' in res.result && Array.isArray(res.result.chargePriceArr) && res.result.chargePriceArr.length > 0 ? res.result.chargePriceArr : [];
      for (var i = 0; i < priceTableData.length; i++) {
        priceTableData[i].key = 1 + i;
        priceTableData[i].chargePriceID = isCopy ? '' : (priceTableData[i]?.chargePriceID || '');
      }
      this.setState({
        rowData: {
          ...res.result,
          chargeItemHospID: isCopy ? '' : id,
          chargePriceArr: isCopy ? [] : priceTableData, // 另存不复制价格信息
          chargeCode: isCopy ? undefined : (res.result?.chargeCode || undefined), // 另存去掉相关信息
          chargeID: isCopy ? '' : (res.result?.chargeID || undefined),
          stDate: isCopy ? undefined : (res.result?.stDate || undefined),
          endDate: isCopy ? undefined : (res.result?.endDate || undefined),
        },
        priceTableData: isCopy ? [] : (priceTableData ? JSON.parse(JSON.stringify(priceTableData)) : []),
        loading: false
      })
    } catch (error) {
      this.props.resetFields && this.props.resetFields();
    }
  }

  // 获取加个信息表头数据
  getPriceColumns = () => {
    let columns = [{
      title: '级别',
      dataIndex: 'gradeDesc',
      align: 'center',
      width: '80px'
    }, {
      title: '费别',
      dataIndex: 'admReasonDesc',
      align: 'center',
      width: '80px'
    }, {
      title: '价格',
      dataIndex: 'chargePrice',
      align: 'center',
      width: '80px'
    }, {
      title: '开始日期',
      dataIndex: 'stDate',
      align: 'center',
      width: '80px'
    }, {
      title: '结束日期',
      dataIndex: 'endDate',
      align: 'center',
      width: '80px'
    }, {
      title: '状态',
      dataIndex: 'status',
      align: 'center',
      width: '80px',
      render: (text, record) => (
        <span style={{ color: text === '当前价格' ? 'red' : '#000000a6' }}>{text}</span>
      )
    }, {
      title: '物价依据',
      dataIndex: 'chargePriceBasis',
      align: 'center',
      width: '200px'
    }, {
      title: '操作',
      dataIndex: 'operation',
      align: "center",
      width: 130,
      render: (text, record) => (
        <span>
          <span className="span" onClick={(e) => this.handleShowPriceModal(record, e)}>编辑</span>
          <Divider type="vertical" />
          <Popconfirm title="删除不可恢复，你确定要删除吗?" onCancel={this.handlePopconfirm} onClick={this.handlePopconfirm} onConfirm={(e) => this.handleDelete(record, e)} >
            <span className="span" style={{ color: 'rgba(240,65,52,1)' }}>删除</span>
          </Popconfirm>
        </span>
      ),
    }];
    this.setState({ priceColumns: columns })
  }

  // 点击删除时阻止事件冒泡
  handlePopconfirm = (e) => {
    e.stopPropagation();
  };

  // 编辑
  handleShowPriceModal = (record) => {
    this.setState({ priceRowData: record }, () => {
      this.priceModalFormRef?.modifyVisible(true);
      this.getPriceFormData();
    })
  }

  // 删除
  handleDelete = (record, e) => {
    let { priceTableData, rowData } = this.state;
    if (record && record.chargePriceID) {
      priceTableData[record?.key - 1] = {
        ...priceTableData[record.key - 1],
        endDate: Moment().subtract(1, 'days').format('YYYY-MM-DD')
      }
      this.setState({ priceTableData }, () => {
        this.handleSave();
      })
    } else {
      this.deleteRow(record?.key)
    }
  }

  // 本地删除数据
  deleteRow = (key) => {
    let priceTableData = JSON.parse(JSON.stringify(this.state.priceTableData));
    priceTableData = priceTableData.filter(item => item.key !== key);
    this.setState({ priceTableData: Util.addKeyValueToDataSource(priceTableData), rowID: '' });
  }

  // 获取医保对照表头数据
  getContrastColumns = () => {
    let columns = [{
      title: '医院',
      dataIndex: 'medAlias',
      align: 'center',
      width: '100px'
    }, {
      title: '费别',
      dataIndex: 'chargeAdmReasonID',
      align: 'center',
      width: '100px'
    }, {
      title: '对照ID',
      dataIndex: 'medAlias',
      align: 'center',
      width: '100px'
    }, {
      title: '医保结算代码',
      dataIndex: 'medAlias',
      align: 'center',
      width: '100px'
    }, {
      title: '医保目录代码',
      dataIndex: 'medAlias',
      align: 'center',
      width: '100px'
    }, {
      title: '国药标准',
      dataIndex: 'medAlias',
      align: 'center',
      width: '100px'
    }, {
      title: '型号',
      dataIndex: 'medAlias',
      align: 'center',
      width: '100px'
    }, {
      title: '规格',
      dataIndex: 'medAlias',
      align: 'center',
      width: '100px'
    }];
    this.setState({ contrastColumns: columns })
  }

  // 获取表单数据
  getPriceFormData = () => {
    let { selectData, priceRowData } = this.state;
    let formData = [{
      dataIndex: 'chargeGradeID',
      title: '级别',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'hospGrade' in selectData && selectData.hospGrade ? selectData.hospGrade : [],
      default: '2', // 默认二级
    }, {
      dataIndex: 'chargeAdmReasonID',
      title: '费别',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'admReason' in selectData && selectData.admReason ? selectData.admReason : [],
      default: '1', // 默认自费
    }, {
      dataIndex: 'chargePrice',
      title: '价格',
      typeCode: 'Input',
      required: 'Y',
    }, {
      dataIndex: 'stDate',
      title: '生效日期',
      typeCode: 'Date',
      required: 'Y',
      disabled: 'chargePriceID' in priceRowData && priceRowData.chargePriceID ? 'Y' : 'N',
      default: 0,
      disabledDate: this.disabledStDate
    }, {
      dataIndex: 'endDate',
      title: '失效日期',
      typeCode: 'Date',
      disabledDate: this.disabledEndDate
    }, {
      dataIndex: 'chargePriceBasis',
      title: '物价依据',
      typeCode: 'Input',
    }];
    this.setState({ priceFormData: 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');
  }

  // 保存价格信息
  handlePriceSave = values => {
    let { priceTableData, priceRowData, selectData } = this.state;
    values = {
      ...Util.convertUndefinedToNull(values),
      gradeDesc: values.chargeGradeID ? Util.returnDataCccordingToAttributes(selectData && 'hospGrade' in selectData ? selectData.hospGrade : [], values.chargeGradeID, 'id')?.descripts : '',
      admReasonDesc: values.chargeAdmReasonID ? Util.returnDataCccordingToAttributes(selectData && 'admReason' in selectData ? selectData.admReason : [], values.chargeAdmReasonID, 'id')?.descripts : '',
    }
    if (priceRowData && priceRowData.key) {
      priceTableData[priceRowData.key - 1] = {
        ...priceTableData[priceRowData.key - 1],
        ...values
      }
    } else {
      priceTableData.push({
        ...values,
        key: priceTableData && priceTableData.length > 0 ? priceTableData.length + 1 : 1,
      })
    }
    this.setState({ priceTableData }, () => {
      this.priceModalFormRef && this.priceModalFormRef.modifyVisible(false, 'Y');
    })
  }

  // 记录价格信息表单的值
  priceRecordFormInput = record => {
    this.setState({ priceRowData: { ...this.state.priceRowData, ...record } })
  }

  // 获取医保对照表单数据
  getContrastFormData = () => {
    let { selectData, insuranceCatalogSelectData, manfSelectData } = this.state;
    let formData = [{
      dataIndex: 'orderCatID',
      title: '费别',
      typeCode: 'Select',
      required: 'Y',
      detailItem: selectData && 'admReason' in selectData && selectData.admReason ? selectData.admReason : []
    }, {
      dataIndex: 'orderResourceID',
      title: '医保目录',
      required: 'Y',
      typeCode: 'SearchSelect',
      valueindex: 'descripts', // 下拉value对应的值
      valueID: 'itemID', // 选择的valueID
      onSearch: this.handleOrderResourceSearch,
      detailItem: insuranceCatalogSelectData,
      loading: false
    }, {
      dataIndex: 'orderSubCatID',
      title: '规格',
      typeCode: 'Input',
      required: 'Y',
    }, {
      dataIndex: 'chargeManfDesc',
      title: '厂家',
      required: 'Y',
      typeCode: 'SearchSelect',
      valueindex: 'descripts', // 显示在界面上的值 -> 对应下拉数据返回的描述
      valueID: 'chargeManfID', // 需要存到后台的字段对应的id值
      onSearch: this.handleManfDescSearch,
      detailItem: manfSelectData,
      loading: false
    }, {
      dataIndex: 'remarks',
      title: '批准文号',
      typeCode: 'Input',
      required: 'Y',
    }, {
      dataIndex: 'startDate',
      title: '生效日期',
      typeCode: 'Date',
      required: 'Y',
      default: 0,
    }, {
      dataIndex: 'stopDate',
      title: '失效日期',
      typeCode: 'Date'
    }];
    this.setState({ contrastFormData: formData })
  }

  // 医嘱目录搜索事件
  handleOrderResourceSearch = (value) => {
    this.state.contrastFormData[1].loading = true;
    this.setState({})
    this.fetchOrderResourceCharge(value, insuranceCatalogSelectData => this.setState({ insuranceCatalogSelectData }, () => {
      this.state.contrastFormData[1].loading = false;
      this.getContrastFormData();
    }));
  }

  // 搜索医嘱目录
  fetchOrderResourceCharge = (value, callback) => {
    value = value.replace(/^\s+/, '').replace(/\s+$/, '');
    if (value === '') {
      callback([]);
      return;
    }
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
    function fakeCharge() {
      let data = {
        params: [{
          inputValue: value,
        }],
        pagination: [{
          pageSize: 100,
          currentPage: 1,
        }]
      }
      $http.post('urlS', this, {
        code: '02020392',
        data,
        success: function (res) {
          if (res.errorCode === '0') {
            let selectData = res.result && 'rows' in res.result && res.result.rows ? res.result.rows : [];
            callback(selectData);
          }
        }
      });
    }
    this.timeout = setTimeout(fakeCharge, 500);
  }

  // 厂家搜索事件
  handleManfDescSearch = (value) => {
    this.state.contrastFormData[3].loading = true;
    this.setState({});
    this.fetchManfCharge(value, manfSelectData => this.setState({ manfSelectData }, () => {
      this.state.contrastFormData[3].loading = true;
      this.getBasicInfoFormData();
    }));
  }

  // 厂家搜索
  fetchManfCharge = (value, callback) => {
    value = value.replace(/^\s+/, '').replace(/\s+$/, '');
    if (value === '') {
      callback([]);
      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, 500);
  }

  // 保存价格信息
  handleContrastSave = values => {
    console.log('values', values)
  }

  contrastRecordFormInput = record => {
    this.setState({ contrastRowData: { ...this.state.contrastRowData, ...record } })
  }

  // 保存
  handleSave = () => {
    let { rowData, priceTableData } = this.state;
    this.chargeItemInfoRef && this.chargeItemInfoRef.handleSave && this.chargeItemInfoRef.handleSave();
    console.log('rowData', rowData)
    setTimeout(() => {
      let chargeItemInfoData = this.chargeItemInfoRef && this.chargeItemInfoRef.getStaticFieldsValue && this.chargeItemInfoRef.getStaticFieldsValue();
      // 收费项信息验证
      if (chargeItemInfoData && chargeItemInfoData.error) {
        message.error('请先完善必填信息再保存。')
        return;
      }
      if (rowData && 'chargeItemHospID' in rowData && rowData.chargeItemHospID) {
        let diffData = this.chargeItemInfoRef && this.chargeItemInfoRef.getDiffData && this.chargeItemInfoRef.getDiffData();
        console.log('rowData', rowData);
        console.log('priceTableData', priceTableData)
        if ((diffData && diffData.length > 0) || (rowData && 'chargePriceArr' in rowData && (JSON.stringify(rowData.chargePriceArr) !== JSON.stringify(priceTableData)))) {
          confirm({
            title: '修改提醒',
            content: `收费项${chargeItemInfoData?.chargeDesc}(${chargeItemInfoData?.chargeCode})中存在内容被修改，是否确认保存?`,
            onOk: () => {
              this.handleHttpSave(chargeItemInfoData);
            },
            onCancel: () => {
              console.log('取消了')
            },
          });
        } else {
          message.error('没有修改的数据需要保存。')
        }
      } else {
        this.handleHttpSave(chargeItemInfoData);
      }
    }, 300)
  }

  // 调用接口保存
  handleHttpSave = async (chargeItemInfoData) => {
    try {
      // 保存触发loading
      this.setState({ loading: true });
      let { priceTableData, rowData } = this.state;
      let data = {
        params: [{
          ...rowData,
          ...chargeItemInfoData,
          chargePriceArr: priceTableData
        }]
      }
      // 调用接口保存
      let res = await React.$asyncPost(this, '02020390', data);
      message.success(res && res.errorMessage ? res.errorMessage : '保存成功');
      let rowID = res && res.result ? String(res.result) : '';
      this.setState({ loading: false, rowData: { ...this.state.rowData, chargeItemHospID: rowID } });
      this.props.getTableData && this.props.getTableData(res.result);
    } catch (error) {
      this.setState({ loading: false });
    }
  }

  resetFields = () => {
    this.setState({ rowData: {}, priceTableData: [] }, () => {
      this.chargeItemInfoRef && this.chargeItemInfoRef.resetFields && this.chargeItemInfoRef.resetFields();
    })
  }

  render() {
    let { height } = this.props;
    let { loading, rowData, selectData, priceColumns, priceTableData, priceLoading, priceTotalwidth, priceFormData, priceRowData } = this.state;

    return (
      <Spin spinning={loading} tip="数据保存中...">
        <div style={{ height: height + 'px' }} className='add-charg-item scroll-bar-style'>
          <ChargeItemInformation
            type="chargeItem"
            cardType="inner"
            priceCard="none"
            selectData={selectData}
            rowData={rowData}
            onRef={ref => this.chargeItemInfoRef = ref}
          />

          <Card
            type="inner"
            size="small"
            style={{ marginTop: '16px' }}
            title={<div>医保信息展示</div>}
          >
            <div className='contrast-info'>
              <p><span>医保代码：</span>{rowData?.insuCode}</p>
              <p><span>医保代码：</span>{rowData?.insuDesc}</p>
              <p><span>规格：</span>{rowData?.specifications}</p>
              <p><span>国家标准：</span>{rowData?.bitCode}</p>
            </div>
          </Card>

          <Card
            type="inner"
            size="small"
            style={{ marginTop: '16px' }}
            title={<div>价格信息</div>}
            extra={(
              <Button
                className="add-btn add-btn-nohover"
                icon="plus"
                onClick={() => this.handleShowPriceModal({})}
              >
                新增价格
              </Button>
            )}
          >
            <div className="add-charg-item-table">
              <PubilcTablePagination
                param={{
                  // 表头配置
                  columns: priceColumns && priceColumns.length > 0 ? priceColumns : [],
                  // 表格数据
                  data: priceTableData,
                  loading: priceLoading,
                  // 表格的宽度
                  x: priceTotalwidth,
                  y: 'N',
                  height: 'auto'
                }}
              />
            </div>
          </Card>

          {/* 医保对照 */}
          {/* <Card
          type="inner"
          size="small"
          style={{ marginTop: '16px' }}
          title={<div>医保对照</div>}
          extra={(
            <Button
              className="add-btn add-btn-nohover"
              icon="plus"
              onClick={() => this.contrastModalFormRef?.modifyVisible(true)}
            >
              新建对照
            </Button>
          )}
        >
          <div className='add-charg-item-table'>
            <PubilcTablePagination
              param={{
                columns: contrastColumns && contrastColumns.length > 0 ? contrastColumns : [],
                data: contrastTableData,
                loading: contrastLoading,
                x: contrastTotalwidth,
                y: 'N',
                height: 'auto'
              }}
            />
          </div>
        </Card> */}

          <PublicModalFormHooks
            onRef={ref => this.priceModalFormRef = ref}
            formData={priceFormData}
            rowData={priceRowData}
            formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
            recordFormInput={this.priceRecordFormInput}
            handleSave={this.handlePriceSave}
          />

          {/* <PublicModalFormHooks
          onRef={ref => this.contrastModalFormRef = ref}
          formData={contrastFormData}
          rowData={contrastRowData}
          formItemCol={{ labelCol: 5, wrapperCol: 16, col: 24 }}
          recordFormInput={this.contrastRecordFormInput}
          handleSave={this.handleContrastSave}
        /> */}
        </div>
      </Spin>
    )
  }
};

export default AddChargItem;