import React, { useEffect, useState } from 'react'
import useRequest from '@ahooksjs/use-request'

import { Modal, QRCode } from 'antd'
import WechartSvg from 'assets/wechat.svg'

import { EOrderStatus, IOrderPayStatusRes, MaterialService } from '../Material.service'
import { useLogin2p } from 'Login2p/Login2pContext'
import Countdown from './Countdown'
import styles from '../css/NoPermission.module.scss'

interface IQRCodeModelProps {
  visible: boolean
  codeUrl: string
  orderCode: string
  countDown?: number
  onCloseModel: () => void
  onSendPayResult: (orderResut: IOrderPayStatusRes) => void
}
let payTimer: NodeJS.Timeout

/**
 * 二维码付款弹框
 */
const QRCodeModel: React.FC<IQRCodeModelProps> = props => {
  const { visible, codeUrl, orderCode, countDown = 600, onCloseModel, onSendPayResult } = props
  const login2p = useLogin2p()

  // 获取订单查询结果
  const { data: orderResut, run: getOrderPayStatus } = useRequest(MaterialService.getOrderPayStatus, {
    manual: true,
    formatResult: res => res?.data?.Data,
    onSuccess: res => {
      console.log('订单查询结果', res)
    }
  })

  useEffect(() => {
    // 获取订单支付状态
    if (visible) {
      payTimer = setTimeout(() => {
        getOrderPayStatus(orderCode)
      }, 2000)
    }
    if (visible && orderResut && orderResut?.OrderStatus !== EOrderStatus.WaitPay) {
      console.log('订单查询结束')
      payTimer && clearTimeout(payTimer)
      onSendPayResult(orderResut)
    }
    return () => {
      console.log('清除定时器')
      payTimer && clearTimeout(payTimer)
    }
  }, [visible, orderResut])

  const handleToClose = () => {
    onCloseModel()
  }
  return (
    <Modal
      open={visible}
      centered={true}
      onCancel={handleToClose}
      destroyOnClose={true}
      maskClosable={false}
      title="付费"
      footer={null}
    >
      <div className={styles['paymodel-content-wrapper']}>
        <div className="paymodel-title">
          <span>请使用 </span>
          <img src={WechartSvg} alt="图标" className="paymodel-wechat-icon" />
          <span className="paymodel-text-green"> 微信</span>
          <span> 扫描二维码完成支付</span>
        </div>
        <div className="paymodel-code-wrapper">
          <QRCode
            size={283}
            value={codeUrl}
            className="paymodel-qrcode"
            // 加上icon不好扫
            // icon="https://verticalmind.oss-accelerate.aliyuncs.com/new/article/img/wechat-pay_1709100398995.png"
          />
        </div>
        <div className="paymodel-title">
          <span>订单剩余支付时间 </span>
          <span className="paymodel-redtext">
            <Countdown countdown={countDown} onTimeChange={handleToClose} />
          </span>
        </div>
      </div>
    </Modal>
  )
}

export default QRCodeModel
