// 医院以及就诊人弹窗
import React from 'react';
import { Modal, List, PickerView, Radio } from 'antd-mobile';
import { $http } from "containers/config/https";
import store from "store";
import './style/index.less';
import { Util } from 'tools';

const RadioItem = Radio.RadioItem;

export default class HospAndPatModal extends React.Component {
  constructor() {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    let weChatParams = sessionStorage.getItem("weChatParams") ? JSON.parse(sessionStorage.getItem("weChatParams")) : {};
    this.state = {
      weChatParams,
      userData,
      visible: false,
      admVisible: false,
      hospData: {},
      hospSelectData: [],
      admSelectData: [],
      admID: [],
      header: 'false',
      home: 'false'
    };
    this.count = 0;
    this.getAdmSelectData = Util.debounce(this.getAdmSelectData, 300);
    this.getHospSelectData = Util.debounce(this.getHospSelectData, 300);
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    // console.log(nextProps)
    if (nextProps && nextProps.header && (nextProps.header !== this.state.header)) {
      // console.log("触发了header")
      this.setState({ header: nextProps.header }, () => {
        this.getHospSelectData();
      })
    }
    if (nextProps && nextProps.home && (nextProps.home !== this.state.home)) { // 首页进入时
      // console.log("触发了home")
      this.setState({ home: nextProps.home }, () => {
        this.getHospSelectData();
      })
    }
  }

  // static getDerivedStateFromProps(nextProps, nextState) {
  //   console.log(nextProps, nextState)
  //   if (nextProps && nextProps.header && (nextProps.header !== nextState.header)) {
  //     return {
  //       header: nextProps.header
  //     }
  //   }
  //   if (nextProps && nextProps.home && (nextProps.home !== nextState.home)) { // 首页进入时
  //     return {
  //       home: nextProps.home
  //     }
  //   }
  //   new HospAndPatModal(nextProps).getHospSelectData();

  //   return null;
  // }

  componentWillUnmount() {
    // 组件销毁前将静止让setState修改state的状态
    this.setState = (state, callback) => { return; }
  }

  // 获取医院数据
  getHospSelectData = () => {
    // let hospSelectData = sessionStorage.getItem("hospSelectData") ? JSON.parse(sessionStorage.getItem("hospSelectData")) : [];
    // if (hospSelectData && hospSelectData.length > 0) {
    //   this.setState({ hospSelectData }, () => {
    //     this.defaultHospData();
    //   })
    //   return;
    // }
    console.log("公共组件获取医院数据")
    let weChatParams = sessionStorage.getItem("weChatParams") ? JSON.parse(sessionStorage.getItem("weChatParams")) : {};
    if (this.count > 10) {
      return;
    }
    if (!(weChatParams && weChatParams.openID)) {
      setTimeout(() => {
        this.count++;
        this.getHospSelectData();
      }, 300);
      return;
    }
    let data = {
      params: []
    }
    $http.post("urlS", this, {
      code: "02010009",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          this.setState({ hospSelectData: res.result }, () => {
            // window.sessionStorage.setItem('hospSelectData', JSON.stringify(this.state.hospSelectData));
            this.defaultHospData();
          });
        } else {
          this.setState({ hospSelectData: [] })
        }
      }
    });
  }

  // 处理医院默认数据
  defaultHospData = () => {
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    if (!(userData && userData.hospID)) { // 判断seession中是否存在医院信息
      if (this.state.hospSelectData.length === 1) {
        let hospData = {
          hospID: this.state.hospSelectData[0].hospID || "",
          hospDesc: this.state.hospSelectData[0].hospDesc || "",
          hisHospID: this.state.hospSelectData[0].hisHospID || "",
          upLoadUrl: this.state.hospSelectData[0].upLoadUrl || "",
          downLoadUrl: this.state.hospSelectData[0].downLoadUrl || ""
        }
        window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...hospData }));
        this.setState({ userData: { ...userData, ...hospData }, hospData }, () => {
          this.getAdmSelectData();
        })
      } else {
        this.handleShowModal();
      }
    } else { // 存在
      let isMatching = false;
      let hospRowData = {};
      for (var i = 0; i < this.state.hospSelectData.length; i++) {
        if (this.state.hospSelectData[i].hospID === userData.hospID) {
          hospRowData = this.state.hospSelectData[i];
          isMatching = true;
          break
        }
      }
      if (isMatching) {
        let hospData = {
          hospID: hospRowData.hospID || "",
          hospDesc: hospRowData.hospDesc || "",
          hisHospID: hospRowData.hisHospID || "",
          upLoadUrl: hospRowData.upLoadUrl || "",
          downLoadUrl: hospRowData.downLoadUrl || ""
        }
        window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...hospData }));
        this.setState({ userData: { ...userData, ...hospData }, hospData }, () => {
          this.getAdmSelectData();
        })
      } else {
        let hospObj = {
          hospID: "",
          hospDesc: "",
          hisHospID: "",
          upLoadUrl: "",
          downLoadUrl: ""
        }
        window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...hospObj }));
        this.setState({ hospData: {} });
      }
    }
  }

  // 获取就诊人下拉数据
  getAdmSelectData = () => {
    store.dispatch({
      type: "isAddAdm",
      value: false
    });
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    let { home } = this.state;
    let sessionAmdSelectData = sessionStorage.getItem("admSelectData") ? JSON.parse(sessionStorage.getItem("admSelectData")) : [];
    // console.log(sessionAmdSelectData, userData)
    if (sessionAmdSelectData && sessionAmdSelectData.length > 0 && userData && (userData.patID === sessionAmdSelectData[0].patID)) {
      this.setState({ admSelectData: sessionAmdSelectData }, () => {
        this.defaultAmdSelectData();
        if (home === "true") {
          this.props.getAdmData(this.state.admSelectData)
        }
      })
      return;
    }
    console.log("公共组件获取就诊人下拉数据");
    let data = {
      params: [{

      }]
    }
    $http.post("urlS", this, {
      code: "01030001",
      data: data,
      success: function (res) {
        if (+res.errorCode === 0) {
          let admSelectData = res.result.rows && res.result.rows.length > 0 ? res.result.rows : [];
          for (var i = 0; i < admSelectData.length; i++) {
            admSelectData[i].value = admSelectData[i].patID;
            admSelectData[i].label = admSelectData[i].patName + '（' + admSelectData[i].hisPatNo + '）';
          }
          window.sessionStorage.setItem('admSelectData', JSON.stringify([...admSelectData]));
          this.setState({ admSelectData }, () => {
            this.defaultAmdSelectData(true);
            if (home === "true") {
              this.props.getAdmData(this.state.admSelectData)
            }
          });
        } else {
          this.setState({ admSelectData: [] });
        }
      }
    });
  }

  // 处理就诊人默认数据
  defaultAmdSelectData = (isReRenderHead) => {
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    if (userData && userData.patID) {
      let isAdmInfo = false;
      let newUserData = {};
      for (var i = 0; i < this.state.admSelectData.length; i++) {
        if (this.state.admSelectData[i].patID === userData.patID) {
          newUserData = this.state.admSelectData[i];
          isAdmInfo = true;
          break;
        }
      }
      if (isAdmInfo) {
        let admObj = {};
        admObj.patID = newUserData.patID;
        admObj.patDesc = newUserData.patName;
        admObj.idCardNo = newUserData.idCardNo;
        admObj.hisPatID = newUserData.hisPatID;
        admObj.hisPatNo = newUserData.hisPatNo;
        admObj.imUserID = newUserData.imUserID;
        admObj.patMobile = newUserData.mobile;
        window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...admObj }));
        this.setState({ admData: newUserData, admID: userData && userData.patID ? [userData.patID] : [] }, () => {
          if (isReRenderHead) {
            store.dispatch({
              type: "isReRenderHead",
              value: true
            });
          }
        });
      } else {
        let admObj = {};
        admObj.patID = "";
        admObj.patDesc = "";
        admObj.idCardNo = "";
        admObj.hisPatID = "";
        admObj.hisPatNo = "";
        admObj.imUserID = "";
        admObj.patMobile = "";
        window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...admObj }));
        this.setState({ admData: admObj, admID: [] }, () => {
          if (isReRenderHead) {
            store.dispatch({
              type: "isReRenderHead",
              value: true
            });
          }
        })
      }
    }
  }

  // 打开弹窗
  handleShowModal = () => {
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    if (!(userData && userData.hospID && userData.hisHospID)) { // 判断seession中是否存在医院信息
      this.setState({ hospData: {}, visible: true })
    } else { // 存在
      let isMatching = false;
      let hospRowData = {};
      for (var i = 0; i < this.state.hospSelectData.length; i++) {
        if (this.state.hospSelectData[i].hospID === userData.hospID) {
          hospRowData = this.state.hospSelectData[i];
          isMatching = true;
          break
        }
      }
      if (isMatching) {
        this.setState({ hospData: hospRowData, visible: true })
      }
    }
  }

  // 关闭弹窗
  handleClose = () => {
    if (this.props.modifyModalVisible) {
      this.props.modifyModalVisible("hospModalVisible", false)
    }
    this.setState({
      visible: false
    });
  }

  // 确认
  handleOk = () => {
    let { hospData } = this.state;
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    let obj = {
      hospID: hospData.hospID || "",
      hospDesc: hospData.hospDesc || "",
      hisHospID: hospData.hisHospID || "",
      upLoadUrl: hospData.upLoadUrl || "",
      downLoadUrl: hospData.downLoadUrl || "",
      patID: "",
      patDesc: "",
      idCardNo: "",
      hisPatID: "",
      hisPatNo: "",
      imUserID: "",
      patMobile: ""
    }
    window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...obj }));
    window.location.reload();
    this.handleClose();


    // 当切换医院后刷新当前界面
    // if (this.props.getAdmSelectData) {
    // this.props.getAdmSelectData()
    // }
  }

  handleRadioChange = item => {
    this.setState({ hospData: item })
  }

  // 打开选择就诊人弹窗
  handleShowAdmModal = () => {
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    let newUserData = {};
    for (var i = 0; i < this.state.admSelectData.length; i++) {
      if (this.state.admSelectData[i].patID === userData.patID) {
        newUserData = this.state.admSelectData[i];
        break;
      }
    }
    this.setState({ admVisible: true, admData: newUserData, admID: userData && userData.patID ? [userData.patID] : [] })
  }

  // 关闭就诊人弹窗
  handleAdmClose = () => {
    if (this.props.modifyModalVisible) {
      this.props.modifyModalVisible("admModalVisible", false)
    }
    this.setState({ admVisible: false })
  }

  // 选择就诊人
  handleAdmSelectChange = (val) => {
    this.setState({ admID: val })
  }

  handleModalOK = () => {
    let { admID, admSelectData } = this.state;
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    let obj = {};
    if (!(admID && admID.length > 0)) {
      obj.patID = admSelectData[0].patID;
      obj.patDesc = admSelectData[0].patName;
      obj.idCardNo = admSelectData[0].idCardNo;
      obj.hisPatID = admSelectData[0].hisPatID;
      obj.hisPatNo = admSelectData[0].hisPatNo;
      obj.imUserID = admSelectData[0].imUserID;
      obj.patMobile = admSelectData[0].mobile;
    } else {
      for (var i = 0; i < admSelectData.length; i++) {
        if (admSelectData[i].patID === admID[0]) {
          obj.patID = admSelectData[i].patID;
          obj.patDesc = admSelectData[i].patName;
          obj.idCardNo = admSelectData[i].idCardNo;
          obj.hisPatID = admSelectData[i].hisPatID;
          obj.hisPatNo = admSelectData[i].hisPatNo;
          obj.imUserID = admSelectData[i].imUserID;
          obj.patMobile = admSelectData[i].mobile;
        }
      }
    }
    window.localStorage.setItem('userData', JSON.stringify({ ...userData, ...obj }));
    this.setState({ admData: obj }, () => {
      this.handleAdmClose();
      // 当切换医院后刷新当前界面
      window.location.reload();
    })
  }

  render() {
    let { visible, admVisible, hospData, hospSelectData, admSelectData, admID } = this.state;
    return (
      <div>
        <Modal
          visible={visible}
          transparent
          maskClosable={hospData && hospData.hospID ? true : false}
          onClose={this.handleClose}
          title="切换医院"
          closable={hospData && hospData.hospID ? true : false}
          footer={[{ text: '确认', onPress: () => this.handleOk() }]}
        >
          <div style={{ height: 200, overflow: 'scroll' }}>
            <List className="hosp-list">
              {hospSelectData && hospSelectData.map(i => (
                <RadioItem key={i.hospID} checked={hospData && hospData.hospID === i.hospID} onChange={() => this.handleRadioChange(i)}>
                  {i.hospDesc}
                </RadioItem>
              ))}
            </List>
          </div>
        </Modal>
        <Modal
          popup
          visible={admVisible}
          maskClosable={true}
          onClose={this.handleAdmClose}
          animationType="slide-up"
        >
          <div className="modal-operating"><span className="float-left" onClick={this.handleAdmClose}>取消</span>选择就诊人<span className="float-right" onClick={this.handleModalOK}>确认</span></div>
          <PickerView
            data={admSelectData}
            value={admID}
            cascade={false}
            onChange={this.handleAdmSelectChange}
          >
            <List.Item arrow="horizontal">选择就诊人</List.Item>
          </PickerView>
        </Modal>
      </div>
    )
  }
}