/*
 * Create:      柿子
 * CreateDate:  2022/07/18
 * Describe：   获取患者信息
 * */
import React, { Component } from 'react';
import { Select, Input, message } from 'antd';
import { $http } from 'containers/config/https';

import ReadCard from 'components/readcard/ReadCard';
import FindPatients from 'pages/registercard/FindPatients';

const { Search } = Input;
const InputGroup = Input.Group;

class GetPatientInformation extends Component {
  constructor(props) {
    super(props);
    this.state = {
      patID: '', // 病人Id
      defaultCardType: undefined, // 默认卡类型
      cardType: undefined, // 卡类型,
      cardNo: undefined, // 卡号,
      patNo: undefined, // 病人
      cardSelectData: [],
      loading: false
    };
    this.buttonStatus = true;
    this.myRef1 = React.createRef();
  }

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    setTimeout(() => {
      this.myRef1 && this.myRef1.current && this.myRef1.current.focus();
    }, 300)
  }

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

  componentWillUnmount() {
    this.setState = (state, callback) => { return; }
  }

  // 获取卡类型下拉框数据 - 提供给外部调用
  getCardSelectData = () => {
    let data = {
      params: [{}]
    }
    $http.post('urlS', this, {
      code: '02030052',
      data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let defaultValue = '';
          for (var i = 0; i < res.result.length; i++) {
            if (res.result[i].defaultFlag === 'Y') {
              defaultValue = res.result[i].id;
            }
          }
          this.setState({ cardSelectData: res.result, cardType: defaultValue, defaultCardType: defaultValue })
        }
      }
    })
  }

  // 卡号
  handleCardNoChange = (e) => {
    if (!e.target.value) {
      setTimeout(() => {
        this.setState({ patID: '' })
      }, 500);
    }
    this.setState({ cardNo: e.target.value })
  }

  // 卡类型
  handleCardTypeOnChange = (e) => {
    this.setState({ cardType: e })
  }

  // 读卡 --- 根据卡号取病人信息
  handleSearch = () => {
    if (!this.buttonStatus) {
      return;
    }
    let { cardType } = this.state;
    this.readCard.ReadCard(cardType, 'R', (json) => {
      this.setState({ patID: json && json.patInfo ? json.patInfo.patID : '', patNo: json && json.patInfo ? json.patInfo.patNo : undefined, cardNo: json.cardNo }, () => {
        this.props.handleQuery && this.props.handleQuery(this.state.patID); // 调取查询接口
      })
    })
  }

  // 读卡操作
  handleReadCardOnBlur = (e, name) => {
    if (!e.target.value) {
      this.setState({ patID: '' });
      return;
    }
    if (name === 'blur') {
      this.buttonStatus = false;
      this.setState({ patNo: undefined }, () => {
        this.handleCardReading('readCard', name);
      })
    } else {
      this.setState({ patNo: undefined }, () => {
        this.handleCardReading('readCard', name);
      })
    }
  }

  // 病人id
  handlePatientChange = (e) => {
    if (!e.target.value) {
      this.setState({ patID: '' });
    }
    this.setState({ patNo: e.target.value });
  }

  // 查询病人id
  handlePatientSearch = (value) => {
    if (!value) {
      this.setState({ patID: '', patNo: undefined }, () => {
        this.props.handleQuery && this.props.handleQuery('', {});
      });
      return;
    }
    if (this.props.queryType && this.props.queryType === 'fuzzySearch') { // fuzzySearch: 模糊查找
      let { patNo } = this.state;
      this.props.handleQuery && this.props.handleQuery(patNo);
    } else {
      this.getPatientData();
    }
  }

  // 请求列表数据
  getPatientData = () => {
    let { patNo } = this.state;
    if (!patNo) return;
    this.setState({ loading: true });
    let data = {}
    data = {
      params: [{
        number: patNo,
      }],
      pagination: [{
        pageSize: 100,
        currentPage: 1,
      }]
    }
    $http.post('urlS', this, {
      code: '03030004',
      data: data,
      success: function (res) {
        this.setState({ loading: false });
        if (res.errorCode === '0') {
          let patData = res.result?.Data || [];
          if (patData && patData.length === 1) {
            // patNo: patData[0]?.patNo || ''
            let patInfo = patData[0];
            this.setState({ patID: patInfo?.patID || '' }, () => {
              this.props.handleQuery && this.props.handleQuery(this.state.patID, patInfo);
            });
          } else if (patData && patData.length > 1) {
            this.findPatientsRef && this.findPatientsRef.showModal();
            this.findPatientsRef && this.findPatientsRef.setValue(patNo);
          } else {
            message.error('未查询到患者信息。')
          }
        }
      },
      error: function () {
        this.setState({ loading: false });
      }
    })
  }

  // 根据卡号取病人信息
  handleCardReading = (flag, name) => {
    let { cardType, cardNo } = this.state;
    let data = {
      params: [{
        cardTypeID: flag === 'readCard' ? cardType : undefined, // 卡类型id
        cardNo, // 卡号
      }]
    }
    setTimeout(() => {
      this.buttonStatus = true;
    }, 500)
    $http.post('urlS', this, {
      code: '03040004',
      data: data,
      success: function (res) {
        if (res.errorCode === '0') {
          let cardNo = flag === "readCard" && res.data && res.data.patCardNo ? res.data.patCardNo : undefined; // 给卡号赋值
          // patNo: res.data && res.data.patNo ? res.data.patNo : '', 病人ID赋值-自动补零
          this.setState({ patID: res.data && res.data.patID ? res.data.patID : '', cardNo, patNo: res.data?.patNo || undefined }, () => {
            if (name === 'enter') {
              this.props.handleQuery && this.props.handleQuery(this.state.patID);
            }
          })
        } else if (res.errorFlag === 'N') {
          this.setState({ patID: '', patNo: undefined })
          message.error(res.errorMessage, this.state.userData && this.state.userData.messageTime)
        } else {
          this.setState({ patNo: undefined });
        }
      },
      error: function () {
        this.setState({ patNo: undefined });
      }
    })
  }

  // 确认选择改患者
  handleConfirm = (patientInfo) => {
    // patNo: patientInfo?.patNo || ''
    this.setState({ patID: patientInfo?.patID || '' }, () => {
      this.props.handleQuery && this.props.handleQuery(this.state.patID, patientInfo);
    })
  }

  // 获取患者信息
  getPatientID = () => {
    let { patID, patNo } = this.state;
    return this.props.queryType && this.props.queryType === 'fuzzySearch' ? patNo : (patNo ? patID : ''); // 模糊查询直接传入输入域内容
  }

  getPatientInfo = () => {
    let { cardType, cardNo, patNo, patID } = this.state;
    return {
      cardType,
      cardNo,
      patID,
      patNo
    }
  }

  // 重置表单
  resetFields = () => {
    const { defaultCardType } = this.state;
    this.setState({ cardType: defaultCardType, cardNo: undefined, patNo: undefined });
  }

  // 设置内容
  setFieldsValue = (values) => {
    this.setState({ ...values });
  }

  render() {
    let { isEnter, patWidth, parLabelClass, enterMargin, patNoPlaceholder } = this.props;
    let { loading, cardSelectData, cardType, cardNo, patNo } = this.state;

    return (
      <div style={{ display: 'inline-block', width: isEnter && isEnter === 'Y' ? '100%' : 'auto' }}>
        <div style={{ display: isEnter && isEnter === 'Y' ? 'flex' : 'inline-block' }}>
          {isEnter && isEnter === 'Y' ? (
            <InputGroup compact>
              <Select
                showSearch
                allowClear
                value={cardType}
                placeholder="条形码"
                optionFilterProp="seachprop"
                style={{ width: '25%' }}
                onChange={this.handleCardTypeOnChange}
              >
                {React.$SelectOptions(cardSelectData || [])}
              </Select>
              <Search
                allowClear
                value={cardNo}
                enterButton="读卡"
                placeholder="请输入或者读卡"
                style={{ width: '75%' }}
                onSearch={this.handleSearch}
                onChange={this.handleCardNoChange}
                onBlur={(e) => this.handleReadCardOnBlur(e, 'blur')}
                onPressEnter={(e) => this.handleReadCardOnBlur(e, 'enter')}
              />
            </InputGroup>
          ) : (
            <>
              <Select
                showSearch
                allowClear
                value={cardType}
                placeholder="条形码"
                optionFilterProp="seachprop"
                style={{ width: 100, marginRight: 15 }}
                onChange={this.handleCardTypeOnChange}
              >
                {React.$SelectOptions(cardSelectData || [])}
              </Select>
              <Search
                allowClear
                value={cardNo}
                enterButton="读卡"
                placeholder="请输入或者读卡"
                style={{ width: 220, marginRight: 15 }}
                onSearch={this.handleSearch}
                onChange={this.handleCardNoChange}
                onBlur={(e) => this.handleReadCardOnBlur(e, 'blur')}
                onPressEnter={(e) => this.handleReadCardOnBlur(e, 'enter')}
              />
            </>
          )}
        </div>
        <div style={{ display: isEnter && isEnter === 'Y' ? 'block' : 'inline-block', margin: isEnter && isEnter === 'Y' ? enterMargin || '20px 0' : 0 }}>
          <span className={parLabelClass || ''}>人员标识：</span>
          <Search
            allowClear={!loading}
            value={patNo}
            loading={loading}
            ref={this.myRef1}
            placeholder={patNoPlaceholder || '病人ID/姓名/身份证号码/手机号码'}
            title="回车触发病人ID查询"
            className="common-query-input"
            style={{ width: patWidth || 260, marginRight: isEnter && isEnter === 'Y' ? 0 : 15 }}
            onChange={this.handlePatientChange}
            onSearch={this.handlePatientSearch}
            onPressEnter={(e) => this.handlePatientSearch(e.target.value)}
          />
        </div>
        <ReadCard ref={r => this.readCard = r} />
        <FindPatients handleParms={this.handleConfirm} OnChildrefs={ref => this.findPatientsRef = ref} />
      </div>
    )
  }
};

export default GetPatientInformation;