// 缴费单详情
import React from 'react';
import { Checkbox, List, Toast } from 'antd-mobile';
import './style/index.less';
import 'assets/less/common.less';
import { $http } from "containers/config/https";
import {Util} from 'tools';
import store from "store";

const Item = List.Item;
const AgreeItem = Checkbox.AgreeItem;
let btnClick;

export default class PaymentSlipDetails 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,
      payDetailData: {}
    }
    this.history = history;

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

  componentDidMount() {
    store.dispatch({
      type: "isSelectPatient",
      value: "no"
    });
    let payDetailData = this.props.location && this.props.location.state ? this.props.location.state : "";
    if (payDetailData && payDetailData.admID) {
      this.setState({ payDetailData }, () => {
        window.sessionStorage.setItem(
          "payDetailData",
          JSON.stringify(
            {...this.state.payDetailData}
          )
        );
      })
    } else {
      let storePayDetailData = sessionStorage.getItem("payDetailData") ? JSON.parse(sessionStorage.getItem("payDetailData")) : {};
      if (storePayDetailData && storePayDetailData.admID) {
        this.setState({ payDetailData: storePayDetailData })
      } else {
        this.history.push("/0001/00020005")
      }
    }
  }

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

  // 去缴费
  handleToPay = () => {
    if (btnClick) {
      return;
    }
    btnClick = true;
    const { userData, weChatParams, payDetailData } = this.state;
    if (!(payDetailData && payDetailData.payedFlag === "P")) {
      btnClick = false;
      return;
    };
    let data = {
      params: [{
        openID: weChatParams.openID || "",
        pubAccCode: weChatParams.pubAccCode || "",
        totalFee: payDetailData.blance ? payDetailData.blance :  "",
        // totalFee: 0.01,
        ipAddress: "",
        body: "出院结算",
        businessType: "IPPPAY",
        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: payDetailData.admID || '',
            payWayCode: "IPWECHAT",
            billID: payDetailData.billId,
            // amount: 0.01
            amount: payDetailData.blance ? payDetailData.blance : ""
          }]
        }
      }],
    }
    let that = this;
    $http.post("urlS", this, {
      code: "PrePay",
      data: data,
      namespace: "UPP",
      success: function (res) {
        if (+res.errorCode === 0) {
          let result = res.result
          if (result.payFlag === "N") {
            Toast.info(res.errorMessage, 3, () => {}, false);
            that.history.push("/0001/00020008");
            return
          }
          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) => {
        if (res.err_msg === "get_brand_wcpay_request:ok") {
          Toast.info("支付成功");
          that.history.push("/0001/00020008");
        } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
          btnClick = false;
          Toast.info('用户取消支付')
        } else if (res.err_msg === "get_brand_wcpay_request:fail") {
          btnClick = false;
          Toast.info('支付失败')
        } else {
          btnClick = false;
          Toast.info('支付失败')
        }
      }
    );
  }

  render() {
    let { payDetailData } = this.state;
    let activeTabs = payDetailData && payDetailData.activeTabs ? payDetailData.activeTabs : "1";
    let id = "2";
    return (
      <div className="electronic-health-card">
        <div className={activeTabs === "1" ? "account payment-slip-details payment-slip-details-bottom" : "account payment-slip-details"}>
          <List className="psd-list-header">
            <Item extra={payDetailData.admdate || ''}>就诊日期</Item>
            <Item extra={payDetailData.patamt}>总费用</Item>
            <Item extra={payDetailData.deposit}>押金金额</Item>
            <Item extra={payDetailData.ybamt}>医保金额</Item>
            <Item extra={payDetailData.blance}>本次需缴费</Item>
            <Item extra={<span style={{color: 'red'}}>{payDetailData.foreignNotes}</span>} style={{color: 'red', display: payDetailData.foreignNotes ? 'flex' : 'none'}}>备注</Item>
          </List>
          <div className="use-balance" style={{ display: id === 1 ? "block" : "none" }}>
            <AgreeItem data-seed="logId" onChange={e => console.log('checkbox', e)}>
              使用可用账户余额 (288.88)
              <span>当前就诊人住院中，请预留余额，避免欠费</span>
            </AgreeItem>
          </div>
          {/* <div className="accordion-style">
            <p className="title">费用明细</p>
            <Accordion onChange={this.onChange}>
              <Accordion.Panel header="药品">
                <div className="list-baseinfo list-children">
                  <div>
                    <span>夏桑菊 ×2</span>
                    <span className="float-right">50.00</span>
                  </div>
                  <div>
                    <span>%5葡萄糖注射液 ×2</span>
                    <span className="float-right">40.00</span>
                  </div>
                  <div>
                    <span><i className="overflow-ellipsis">马来酸非尼拉敏12312313123312盐酸萘甲唑林滴...</i> ×2</span>
                    <span className="float-right">110.00</span>
                  </div>
                  <div>
                    <span>板蓝根颗粒 ×2</span>
                    <span className="float-right">100.00</span>
                  </div>
                </div>
              </Accordion.Panel>
              <Accordion.Panel header="检验检查">
                <div className="list-baseinfo list-children">
                  <div>
                    <span>夏桑菊 ×2</span>
                    <span className="float-right">50.00</span>
                  </div>
                  <div>
                    <span>%5葡萄糖注射液 ×2</span>
                    <span className="float-right">40.00</span>
                  </div>
                  <div>
                    <span><i className="overflow-ellipsis">马来酸非尼拉敏12312313123312盐酸萘甲唑林滴...</i> ×2</span>
                    <span className="float-right">110.00</span>
                  </div>
                  <div>
                    <span>板蓝根颗粒 ×2</span>
                    <span className="float-right">100.00</span>
                  </div>
                </div>
              </Accordion.Panel>
              <Accordion.Panel header="检验检查">
                <div className="list-baseinfo list-children">
                  <div>
                    <span>夏桑菊 ×2</span>
                    <span className="float-right">50.00</span>
                  </div>
                  <div>
                    <span>%5葡萄糖注射液 ×2</span>
                    <span className="float-right">40.00</span>
                  </div>
                  <div>
                    <span><i className="overflow-ellipsis">马来酸非尼拉敏12312313123312盐酸萘甲唑林滴...</i> ×2</span>
                    <span className="float-right">110.00</span>
                  </div>
                  <div>
                    <span>板蓝根颗粒 ×2</span>
                    <span className="float-right">100.00</span>
                  </div>
                </div>
              </Accordion.Panel>
            </Accordion>
          </div> */}
          <div className="to-pay" style={{ display: activeTabs === "1" ? "block" : "none" }}>
            <span>需交费：<i>¥{payDetailData.blance}</i></span>
            <span onClick={this.handleToPay} className={payDetailData&& payDetailData.payedFlag === "P" ? '' : 'to-pay-noclick'}>{payDetailData&& payDetailData.payedFlag === "P" ? '去缴费' : payDetailData.payedDesc }</span>
          </div>
        </div>
      </div>
    )
  }
}
