/*
 * Create:      柿子
 * CreateDate:  2022/10/20 
 * Describe：   微信支付
 * */
import React, { Component } from 'react';
import { Modal, Button, Result, Statistic } from 'antd';
import QRCode from 'qrcode.react';
import '../style/index.less';
import weixin from 'assets/images/weixin.png';
const Countdown = Statistic.Countdown;

class WeChatPayment extends Component {
  constructor(props) {
    super(props);
    this.state = {
      rowData: {},
      visible: false,
      payStatus: 'N',
      currentCount: 0,
      deadline: 0, // 支付倒计时
    };
    this.timer = null;
  }

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

  // 修改弹窗状态
  modifyVisible = (visible, rowData = {}) => {
    if (visible) {
      this.timer = setInterval(() => {
        this.getPayStatus();
      }, 3 * 1000);
      const deadline = Date.now() + 1000 * 60 * 10;
      this.setState({ rowData, deadline });
    }
    this.setState({ visible }, () => {
      if (!this.state.visible) {
        clearInterval(this.timer);
        setTimeout(() => {
          this.setState({ payStatus: 'N' });
        }, 100)
      }
    })
  }

  // 获取支付状态
  getPayStatus = async () => {
    try {
      let { rowData } = this.state;
      if (!(rowData && rowData.processID)) return;
      let data = {
        params: [{
          processID: rowData?.processID || ''
        }]
      }
      let res = await React.$asyncPost(this, '17030073', data);
      let payStatus = res?.result || 'N';
      this.setState({ payStatus }, () => {
        if (this.state.payStatus === 'Y') {
          clearInterval(this.timer);
          let currentCount = Date.now() + 1000 * 10;
          this.setState({ currentCount, deadline: 0 });
        }
      });
    } catch (error) {
      console.log(error);
    }
  }

  // 取消支付
  handleCancelPay = () => {
    this.modifyVisible(false);
  }

  // 倒计时完成
  handleCountFinish = (isQuery) => {
    this.modifyVisible(false);
    isQuery !== 'N' && this.props.handleQuery && this.props.handleQuery();
  }

  render() {
    let { visible, rowData, payStatus, currentCount, deadline } = this.state;

    return (
      <Modal
        width="520px"
        title="微信支付"
        className="weChat-payment"
        footer={null}
        maskClosable={false}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => this.modifyVisible(false)}
      >
        {payStatus === 'Y' ? (
          <div>
            <Result
              status="success"
              title="支付成功"
              subTitle={(
                <span>
                  支付金额：<strong style={{ color: '#fa8c17' }}>{rowData?.patAmt || 0}</strong>
                </span>
              )}
            />
            <div className="flex-justify-center">
              <Button
                className="flex-center"
                style={{ width: '180px', marginTop: 12 }}
                onClick={this.handleCountFinish}
              >
                我知道了( <Countdown value={currentCount} format="ss" onFinish={this.handleCountFinish} /> s)
              </Button>
            </div>
          </div>
        ) : (
          <div className="flex-column-center">
            <h3>请扫描二维码支付预交款</h3>
            <p>支付金额：<strong style={{ color: '#fa8c17' }}>{rowData?.patAmt || 0}</strong></p>
            <QRCode
              renderAs="svg" // 渲染方式默认canvas
              level="Q" // L(<7%),M(<15%),Q(<25%),H(<30%)
              value={rowData.qrUrl}
              size={168} // 二维码的大小
              fgColor="#000000" // 二维码的颜色
              imageSettings={{ // 二维码中间的logo图片
                src: weixin,
                height: 46,
                width: 46,
                excavate: true, // 中间图片所在的位置是否镂空
              }}
            />
            <div className="wcp-deadline flex-center" style={{ marginTop: 16, fontSize: '12px', fontWeight: 'normal' }}>
              <Countdown value={deadline} format="mm:ss" onFinish={() => this.handleCountFinish('N')} /> 后自动取消并关闭支付窗口！
            </div>
            <Button
              ghost
              type="danger"
              style={{ width: '180px', marginTop: 2 }}
              onClick={this.handleCancelPay}
            >
              取消支付
            </Button>
          </div>
        )}

      </Modal>
    );
  }
}

export default WeChatPayment;