/* eslint-disable no-unused-expressions */
import React, { Component } from "react"
import "./veri-code-input.scss"
import { http, validateEmail } from "src/utils"
import { Toast } from "antd-mobile"
import { has, isEmpty } from "lodash"

import classnames from "classnames"

import Input from "../Input"

window.AliyunCaptchaConfig = {
  // 必填，验证码示例所属地区，支持中国内地（cn）、新加坡（sgp）。
  region: "cn",
  // 必填，身份标。开通阿里云验证码2.0后，您可以在控制台概览页面的实例基本信息卡片区域，获取身份标。
  prefix: "1fkufq",
}

class VeriCodeInput extends Component {
  count = 60
  state = {
    counting: false,
    count: this.count,
  }
  timer = null
  captcha = null
  captchaVerifyParams = null

  componentDidMount() {
    this.initAliyunCaptcha()
  }
  componentWillUnmount() {
    // 必须删除相关元素，否则再次mount多次调用 initAliyunCaptcha 会导致多次回调 captchaVerifyCallback
    document.getElementById("aliyunCaptcha-mask")?.remove()
    document.getElementById("aliyunCaptcha-window-popup")?.remove()
  }

  initAliyunCaptcha = () => {
    window.initAliyunCaptcha({
      SceneId: "1o4fd91z", // 场景ID。根据步骤二新建验证场景后，您可以在验证码场景列表，获取该场景的场景ID
      prefix: "1fkufq", // 身份标。开通阿里云验证码2.0后，您可以在控制台概览页面的实例基本信息卡片区域，获取身份标
      mode: "popup", // 验证码模式。popup表示要集成的验证码模式为弹出式。无需修改
      element: "#captcha-element", // 页面上预留的渲染验证码的元素，与原代码中预留的页面元素保持一致。
      button: "#captcha-button", // 触发验证码弹窗的元素。button表示单击登录按钮后，触发captchaVerifyCallback函数。您可以根据实际使用的元素修改element的值
      captchaVerifyCallback: (params) => {
        console.error("captchaVerifyCallback", params)
        this.captchaVerifyParams = params
        this.countDown()
        return { captchaResult: true }
      }, // 业务请求(带验证码校验)回调函数，无需修改
      onBizResultCallback: this.onBizResultCallback, // 业务请求结果回调函数，无需修改
      getInstance: this.getInstance, // 绑定验证码实例函数，无需修改
      slideStyle: {
        width: 360,
        height: 40,
      }, // 滑块验证码样式，支持自定义宽度和高度，单位为px。其中，width最小值为320 px
      language: "cn", // 验证码语言类型，支持简体中文（cn）、繁体中文（tw）、英文（en）
    })
  }

  getInstance = (instance) => {
    this.captcha = instance
  }

  // 验证通过后调用
  onBizResultCallback = () => {
    console.error("onBizResultCallback")
    // this.countDown();
  }

  countDown = async () => {
    let { count } = this.state
    if (!this.state.counting) {
      const res = await this.sendCode()
      if (!res) {
        return false
      }
      this.setState({ count: count--, counting: true })
      this.timer = setInterval(() => {
        if (count <= 0) {
          clearInterval(this.timer)
          this.setState({ counting: false, count: this.count })
          return
        }
        this.setState({ count: count-- })
      }, 1000)
      return true
    }
    return true
  }

  getType = () => {
    const { email } = this.props
    if (validateEmail(email)) {
      return "email"
    }
  }

  sendCode = async () => {
    if (!this.validate()) return false
    return this.getType() === "email"
      ? await this.sendEmail()
      : await this.sendSMS()
  }

  sendEmail = async () => {
    return new Promise((resolve, reject) => {
      const { email } = this.props
      http
        .post(`${API["passport-api"]}/send_email_code`, {
          email,
          captchaVerifyParam: this.captchaVerifyParams,
        })
        .then((res) => {
          if (res.data.errno === 0) {
            Toast.info("验证码发送成功", 2, null, false)
            resolve(true)
          } else {
            Toast.info(res.data.msg, 2, null, false)
            reject(false)
          }
        })
        .catch((err) => {
          reject(false)
        })
    })
  }

  sendSMS = async () => {
    return new Promise((resolve, reject) => {
      const { action, tel, account, checking, country } = this.props
      if (!tel) {
        Toast.info("请输入手机号")
        return
      }
      http
        .post(`${API["passport-api"]}/quick_sms`, {
          phone_num: tel || account,
          action: action || "login",
          area_code: "00" + country.num,
          checking,
          captchaVerifyParam: this.captchaVerifyParams,
        })
        .then((res) => {
          if (res.data.errno === 0) {
            Toast.info("验证码发送成功", 2, null, false)
            resolve(true)
          } else {
            Toast.info(res.data.msg, 2, null, false)
            reject(false)
          }
        })
        .catch(() => {
          reject(false)
        })
    })
  }

  validate = () => {
    const { tel, email } = this.props
    let hasTel = has(this.props, "tel")
    let content

    if (hasTel) {
      if (!tel) {
        content = "手机号码不能为空"
      }
      if (!/\d/.test(tel)) {
        content = "请输入正确格式的手机号码"
      }
    } else {
      if (!email) {
        content = "电子邮件不能为空"
      }
      if (!validateEmail(email)) {
        content = "请输入正确格式的电子邮件"
      }
    }

    if (content) {
      Toast.info(content, 2, null, false)
      return false
    }

    if (isEmpty(this.captchaVerifyParams)) {
      Toast.info("请进行滑块验证", 2, null, false)
      return false
    }
    return true
  }

  render() {
    let { className, ...rest } = this.props
    return (
      <Input type={"number"} wrapperClass={className} {...rest}>
        <button
          type="button"
          className={classnames("verify", { active: !this.state.counting })}
          id="captcha-button"
        >
          {this.state.counting ? `重新发送${this.state.count}s` : "发送验证码"}
        </button>
        <div id="captcha-element"></div>
      </Input>
    )
  }
}

export default VeriCodeInput
