// 充值
import React from 'react';
import { InputItem, Button, Toast } from 'antd-mobile';
import './style/index.less';
import { $http } from "containers/config/https";
import { Util } from 'tools';
import store from "store";

let btnClick;

export default class Recharge extends React.Component {
  constructor({ history }) {
    super();
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    let weChatParams = sessionStorage.getItem("weChatParams") ? JSON.parse(sessionStorage.getItem("weChatParams")) : {};
    this.state = {
      userData,
      weChatParams,
      adminStatus: true,
      visible: false,
      admID: "2",
      rechargeAmount: undefined,
      gridData: [],
      activeKey: "",
      admData: {}
    }
    this.history = history;

    this.handleRecharge = Util.debounce(this.handleRecharge, 300);
  }

  componentDidMount() {
    store.dispatch({
      type: "isSelectPatient",
      value: "no"
    });
    this.getGridData();
    let admData = this.props.location && this.props.location.state ? this.props.location.state : "";
    if (admData && admData.admID) {
      this.setState({ admData })
    } else {
      // let storeAdmData = sessionStorage.getItem("admData") ? JSON.parse(sessionStorage.getItem("admData")) : {};
      // if (storeAdmData && storeAdmData.admID) {
      //   this.setState({ admData: storeAdmData })
      // } else {
      let url = window.location.href.indexOf("?") !== -1 ? String(window.location.href).split("?")[1] : "";
      let admID = Util.interceptTheValueOfTheURL(Util.interceptTheValueOfTheURL(url, "params", "&", "="), "admID", "^", ":");
      let patNo = Util.interceptTheValueOfTheURL(Util.interceptTheValueOfTheURL(url, "params", "&", "="), "patNo", "^", ":");
      let urlObj = {};
      urlObj.admID = admID;
      urlObj.patNo = patNo;
      this.setState({ admData: urlObj }, () => {
        this.getVisitRecordsListData();
      })
      // }
    }
  }

  componentWillUnmount() {
    store.dispatch({
      type: "isSelectPatient",
      value: "yes"
    });
  }

  // 获取就诊记录
  getVisitRecordsListData = () => {
    let { userData, admData } = this.state;
    // console.log(admData)
    let data = {
      params: [{
        hospCode: userData && userData.hisHospID ? userData.hisHospID : "",
        patDesc: userData && userData.patDesc ? userData.patDesc : "",
        userCode: "wxsf",
        patNO: admData.patNo,
        // patNO: "0000038961",
        admID: admData.admID
      }]
    }
    $http.post("urlS", this, {
      code: "130972",
      data: data,
      namespace: "UPP",
      success: function (res) {
        if (+res.errorCode === 0) {
          let newAdmData = res.result && res.result.length > 0 && res.result[0].admDetail.length > 0 ? res.result[0].admDetail[0] : {};
          this.setState({ admData: { ...this.state.admData, ...newAdmData } }, () => {
            // console.log("newAdmData", newAdmData)
            this.getAdmSelectData();
          });
        } else {
          Toast.info(res.errorMessage, 3, () => { }, false)
        }
      }
    });
  }

  // 获取就诊人下拉数据
  getAdmSelectData = () => {
    let { admData } = this.state;
    let sessionAmdSelectData = sessionStorage.getItem("admSelectData") ? JSON.parse(sessionStorage.getItem("admSelectData")) : [];
    // console.log(sessionAmdSelectData, admData)
    if (sessionAmdSelectData && sessionAmdSelectData.length > 0 && admData && (admData.hisPatNo === sessionAmdSelectData[0].hisPatNo)) {
      this.setState({ admSelectData: sessionAmdSelectData }, () => {
        this.defaultAmdSelectData();
      })
      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);
          });
        } else {
          this.setState({ admSelectData: [] });
        }
      }
    });
  }

  // 处理就诊人默认数据
  defaultAmdSelectData = (isReRenderHead) => {
    let { admData } = this.state;
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    if (admData && admData.hisPatNo) {
      let isAdmInfo = false;
      let newUserData = {};
      for (var i = 0; i < this.state.admSelectData.length; i++) {
        if (this.state.admSelectData[i].hisPatNo === admData.hisPatNo) {
          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: { ...admData, ...newUserData }, admID: admData && 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: { ...admData, ...admObj }, admID: [] }, () => {
          if (isReRenderHead) {
            store.dispatch({
              type: "isReRenderHead",
              value: true
            });
          }
        })
      }
    }
  }

  // 获取金额列表
  getGridData = () => {
    let gridData = [
      {
        id: "1",
        value: "200"
      }, {
        id: "2",
        value: "300"
      }, {
        id: "3",
        value: "500"
      }, {
        id: "4",
        value: "1000"
      }, {
        id: "5",
        value: "2000"
      }, {
        id: "6",
        value: "3000"
      }, {
        id: "7",
        value: "5000"
      }, {
        id: "8",
        value: "10000"
      }
    ];
    this.setState({ gridData })
  }

  handleRechargeAmountChange = val => {
    this.setState({ rechargeAmount: val, activeKey: "" })
  }

  // 选择金额
  handleSelectItem = item => {
    this.setState({ rechargeAmount: item.value, activeKey: item.id })
  }

  // 充值
  handleRecharge = () => {
    const { admData, rechargeAmount } = this.state;
    if (!(admData && admData.admID)) {
      Toast.info("就诊ID异常，请回到首页重新进入充值界面。", 3, () => { }, false)
      return;
    }
    let userData = localStorage.getItem("userData") ? JSON.parse(localStorage.getItem("userData")) : {};
    let weChatParams = sessionStorage.getItem("weChatParams") ? JSON.parse(sessionStorage.getItem("weChatParams")) : {};
    if (btnClick) {
      return;
    }
    btnClick = true;
    if ((admData && admData.depositflagDesc)) {
      btnClick = false;
      Toast.info("此住院记录已出院，不允许再缴费", 3, () => { }, false)
      return;
    }
    let data = {
      params: [{
        openID: weChatParams.openID || "",
        pubAccCode: weChatParams.pubAccCode || "",
        totalFee: rechargeAmount,
        ipAddress: "",
        body: "住院押金",
        businessType: "IPDEP",
        hospitalCode: userData.hisHospID || '',
        payWCode: "IPWECHAT",
        userCode: "wxsf",
        patID: userData.hisPatNo || '',
        patName: userData.patDesc || '',
        idCardNo: userData.idCardNo || '',
        mobile: userData.patMobile || '',
        data: {
          params: [{
            hospCode: userData.hisHospID || '',
            userCode: "wxsf",
            patNO: userData.hisPatNo || '',
            admID: admData.admID || '',
            payWayCode: "IPWECHAT",
            amount: rechargeAmount,
            payModeCode: 'wx'
          }]
        }
      }],
    }

    let that = this;
    $http.post("urlS", this, {
      code: "PrePay",
      data: data,
      namespace: "UPP",
      success: function (res) {
        if (+res.errorCode === 0) {
          let result = res.result
          this.onBridgeReady(result, that);
        } else {
          btnClick = false;
          Toast.info(res.errorMessage, 3, () => { }, false)
        }
      },
      error: function (error) {
        btnClick = false;
        Toast.info(error, 3, () => { }, false)
      }
    });
  }

  onBridgeReady = (result, that) => {
    let { appId, timeStamp, nonceStr, signType, paySign } = result;
    let package_value = result.package || "";
    window.WeixinJSBridge.invoke(
      'getBrandWCPayRequest', {
      "appId": appId,     //公众号名称，由商户传入     
      "timeStamp": timeStamp,         //时间戳，自1970年以来的秒数     
      "nonceStr": nonceStr, //随机串     
      "package": package_value,
      "signType": signType,         //微信签名方式：     
      "paySign": paySign //微信签名 
    },
      (res) => {
        btnClick = false;
        if (res.err_msg === "get_brand_wcpay_request:ok") {
          Toast.info("支付成功");
          that.history.push("/0001/00020001");
        } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
          Toast.info('用户取消支付')
        } else if (res.err_msg === "get_brand_wcpay_request:fail") {
          Toast.info('支付失败')
        } else {
          Toast.info('支付失败')
        }
      }
    );
  }

  // 跳转到首页
  handleGoHome = () => {
    this.history.push("/0001/00000001")
  }

  render() {
    let { rechargeAmount, gridData, activeKey } = this.state;
    const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
    let moneyKeyboardWrapProps;
    if (isIPhone) {
      moneyKeyboardWrapProps = {
        onTouchStart: e => e.preventDefault(),
      };
    }

    let gridListDom = gridData && gridData.map((item, index) => {
      return (<li className={item.id === activeKey ? "grid-list-active" : ""} key={index} onClick={() => this.handleSelectItem(item)}>{"¥" + item.value}</li>)
    })

    return (
      <div className="electronic-health-card">
        <div style={{ height: "100%", overflow: "auto" }} className="recharge">
          <p className="recharge-head">缴费金额</p>
          <div className="recharge-amount">
            <ul className="grid-list border-bottom-after">
              {gridListDom}
            </ul>
            <InputItem
              type="money"
              value={rechargeAmount}
              placeholder="请输入其他金额"
              onChange={this.handleRechargeAmountChange}
              clear
              moneyKeyboardAlign="left"
              moneyKeyboardWrapProps={moneyKeyboardWrapProps}
            >其他金额</InputItem>
          </div>
          <div className="margintop24" style={{ padding: '0 12px', boxSizing: 'border-box' }}>
            <Button type="primary" onClick={this.handleRecharge} disabled={rechargeAmount ? false : true}>缴费</Button>
            <Button style={{ marginTop: '12px', fontSize: '16px', color: "#666" }} onClick={this.handleGoHome}>返回首页</Button>
          </div>
        </div>
      </div>
    )
  }
}