/*
 * Create:      柿子
 * CreateDate:  2024/2/21
 * Describe：   验证码登录（金税）
 * */
import React, { Component } from 'react';
import { Modal, Statistic } from 'antd';
import QRCode from 'qrcode.react';
import PublicModalFormHooks from 'pages/common/PublicModalFormHooks';

const Countdown = Statistic.Countdown;

class VerificationCodeLogin extends Component {
  constructor(props) {
    super(props);
    this.state = {
      codeFormData: [], // 验证码表单数据
      codeVisible: false, // 验证码弹框显示
      deadline: 0, // 支付倒计时
      codeUrl: '', // 验证码图片地址
      codeOkLoading: false, // 验证码验证
      codeErrorTip: '', // 验证码错误提示
    }
  };

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

  // 初始化数据
  handleInit = (formData = []) => {
    const { codeFormData } = this.state;
    if (!(codeFormData && Array.isArray(codeFormData) && codeFormData.length > 0)) {
      this.setState({ codeFormData: formData }, () => {
        this.handleVerificationCodeLogin('');
      });
    } else {
      this.handleVerificationCodeLogin('');
    }
  };

  // 验证码登录
  handleVerificationCodeLogin = async (code) => {
    try {
      if (!code) {
        this.setState({ codeErrorTip: '' });
      } else {
        this.setState({ codeOkLoading: true });
      }
      let data = {
        params: [{
          SMSCODE: code || '', // 验证码
        }]
      }
      let res = await React.$asyncPost(this, '05210102', data);
      let codeUrl = res?.EWM || '';
      if (!codeUrl) { // 发送验证码
        message.success(res?.errorMessage || '验证码已发送至手机，请注意查收');
        this.setState({ codeOkLoading: false, codeErrorTip: res?.tip || '' });
        this.codeRef && this.codeRef.modifyVisible(true, 'Y');
      } else { // 验证成功，生产二维码
        const deadline = Date.now() + 1000 * 60 * 3; // 三分钟自动关闭扫码弹窗
        this.setState({ deadline, codeUrl, codeOkLoading: false, codeErrorTip: res?.tip || '' }, () => {
          this.codeRef && this.codeRef.modifyVisible(false);
          this.modifyCodeVisible(true);
        });
      }
    } catch (error) {
      this.codeRef && this.codeRef.modifyVisible(true, 'Y');
      this.setState({ codeOkLoading: false, codeErrorTip: error?.tip || '' });
    }
    this.props.closeLoading && this.props.closeLoading();
  };

  // 验证码登录
  handleCodeSave = (values) => {
    this.handleVerificationCodeLogin(values?.code || '');
  };

  modifyCodeVisible = (visible) => {
    this.setState({ codeVisible: visible });
  };

  render() {
    const { codeOkLoading, codeFormData, codeVisible, codeUrl, deadline, codeErrorTip } = this.state;

    return (
      <div>
        {/* 输入验证码 */}
        <PublicModalFormHooks
          width="520px"
          okText="确定"
          title={'验证码输入' + (codeErrorTip ? ('【' + codeErrorTip + '】') : '')}
          selectData={{}}
          rowData={{}}
          okLoading={codeOkLoading}
          formData={codeFormData}
          onRef={ref => this.codeRef = ref}
          handleSave={this.handleCodeSave}
        />

        <Modal
          width="520px"
          title="认证二维码"
          footer={null}
          maskClosable={false}
          visible={codeVisible}
          onCancel={() => this.modifyCodeVisible(false)}
        >
          <div className="flex-column-center">
            <QRCode
              renderAs="svg" // 渲染方式默认canvas
              level="Q" // L(<7%),M(<15%),Q(<25%),H(<30%)
              value={codeUrl}
              size={168} // 二维码的大小
              fgColor="#000000" // 二维码的颜色
            />
            <div className="flex-center" style={{ marginTop: 16, fontSize: '12px', fontWeight: 'normal' }}>
              <Countdown value={deadline} format="mm:ss" onFinish={() => this.modifyCodeVisible(false)} /> 后自动取消并关闭认证窗口！
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default VerificationCodeLogin;