/*
 * @Description: 这是输入mobile和code页面，可用于登录、绑定
 * @Author: zhoupeng
 * @Date: 2020-04-22 15:29:53
 * @LastEditTime: 2020-07-31 13:54:13
 */

import React, { Component } from 'react';
import { connect } from 'react-redux';

import router from 'umi/router';
import styles from './index.less';
import wx from 'weixin-js-sdk';

import { Toast } from 'antd-mobile';

import { getPayInfo, checkPayOrder } from '../services/index';

import { getQuery } from '../../../utils/helper';
//img
const wechatImg = require('../assets/pay/wechat.png');
const rightImg = require('../assets/pay/right.png');
@connect(({}) => ({}))
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      payData: {},
      title: '',
      detail: '',

      checkPayNum: 0,
    };
  }

  goback = () => {
    console.log('popstate');
    const { location } = this.props;
    const fromPage = getQuery(location, 'fromPage') || '';
    if (fromPage === 'register') {
      router.replace(`/ckuh5/index`);
    }
  };

  componentDidMount = () => {
    //初始化支付信息
    this.initPayData();
    window.addEventListener('popstate', this.goback);
  };

  componentWillUnmount = () => {
    Toast.hide();
    window.removeEventListener('popstate', this.goback);
  };

  //初始化支付信息
  initPayData = () => {
    var payData = window.sessionStorage.getItem('payInfo');

    if (payData) {
      const obj = JSON.parse(payData);
      this.setState({
        payData: obj,
        title: obj && obj.title ? obj.title : '',
        detail: obj && obj.detail ? obj.detail : '',
      });
    }
  };

  //支付
  pay = async item => {
    const openId = sessionStorage.getItem('openId');
    const { payData } = this.state;
    const orderId = payData.orderId ? payData.orderId : '';

    //设置loading
    Toast.loading('支付中', 0, null, true);
    const { rc, msg, data } = await getPayInfo({ orderId, openId });

    console.log('result:', rc, msg, data);
    if (rc === 0) {
      const _this = this;
      wx.chooseWXPay({
        // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。
        // 但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
        timestamp: data.timestamp,
        // 支付签名随机串，不长于 32 位
        nonceStr: data.nonceStr,
        package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
        signType: data.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
        paySign: data.sign, // 支付签名
        success: function(res) {
          // 支付成功后的回调函数
          console.log('支付成功');
          //_this.check(orderId);
          _this.timer = setTimeout(() => {
            _this.checkPay(orderId);
          }, 5000);
        },
        fail: function(res) {
          Toast.hide();
          Toast.fail('支付失败');
          router.replace('/ckuh5/payResult?payResult=fail');
        },
        cancel: function(res) {
          Toast.hide();
        },
        complete: function(res) {
          console.log(res, 'complete');
        },
      });
    } else {
      console.log('error:', rc, msg, data);
    }
  };

  check = orderId => {
    this.timer = setInterval(async () => {
      const { checkPayNum } = this.state;
      this.setState({
        checkPayNum: checkPayNum + 1,
      });
      if (checkPayNum >= 5) {
        router.replace('payResult?payResult=fail');
        clearInterval(this.timer);
        return;
      }

      const { rc, msg, data } = await checkPayOrder({ orderId });
      if (rc === 0 && data && data.result === 'SUCCESS') {
        router.replace('payResult?payResult=success');
        clearInterval(this.timer);
        return;
      }
    }, 1000);
  };

  //查询支付结果
  checkPay = async orderId => {
    console.log('payLogId：', orderId);
    if (!orderId) {
      this.setState({ loading: false });
      return;
    }

    const { rc, msg, data } = await checkPayOrder({ orderId });
    // console.log('rc:', rc, msg, data);
    Toast.hide();
    if (rc === 0 && data && data.result === 'SUCCESS') {
      router.replace('/ckuh5/payResult?payResult=success');
    } else if (rc === 0 && data && data.result === 'FAIL') {
      router.replace('/ckuh5/payResult?payResult=fail');
    } else {
      Toast.info(`${msg}`);
    }
  };

  render() {
    const { payData } = this.state;
    return (
      <div className={styles.pay_container}>
        <div className={styles.title_content}>
          <div className={styles.title_text}>{payData && payData.title ? payData.title : ''}</div>
          <div className={styles.title_second_text}>
            {payData && payData.detail ? payData.detail : ''}
          </div>
        </div>
        <div className={styles.pay_type_title}>选择支付方式</div>
        <div className={styles.wechat_container}>
          <div className={styles.wechat_left_box}>
            <img className={styles.wechat_img} src={wechatImg}></img>
            <div className={styles.wechat_text}>微信支付</div>
          </div>
          <img className={styles.right_img} src={rightImg}></img>
        </div>

        <div className={styles.fixed_content}>
          <div className={styles.price_content}>
            <span className={styles.price_label}>￥</span>
            <span className={styles.price_text}>
              {payData.orderAmount ? payData.orderAmount : '0'}
            </span>
          </div>
          <div className={styles.pay_button} onClick={this.pay}>
            <span>确认支付</span>
          </div>
        </div>
      </div>
    );
  }
}

export default Index;
