import React, { useState } from 'react'
import useRequest from '@ahooksjs/use-request'
import { Input, Button, Form, message, Modal } from 'antd'

import styles from 'styles/NewPage.module.scss'
import { SafetyCertificateOutlined } from '@ant-design/icons'
import { ReactComponent as LoginPassword } from 'assets/login_passwode.svg'
import { Login2pService } from 'Login2p/Login2p.service'
import { useLogin2p } from 'Login2p/Login2pContext'

import md5 from 'js-md5'

interface ISetUpPasswordProps {
  visible: boolean
  encryptionPhone: string
  phoneAreaCode: string
  onCancelPassword: () => void
}

/**
 * 编辑专栏信息
 */
const SetUpPassword: React.FC<ISetUpPasswordProps> = props => {
  const login2p = useLogin2p()
  const { visible, encryptionPhone, phoneAreaCode, onCancelPassword } = props
  const [form] = Form.useForm()

  const [isDisabled, setIsDisabled] = useState<boolean>(false)
  const [captchaBtnText, setCaptchaBtnText] = useState<string>('获取验证码')

  const { run: getLoginCode, loading: loadingVCode } = useRequest(Login2pService.getVCode, {
    manual: true,
    formatResult: response => response.data,
    onSuccess: result => message.success('验证码请求成功!'),
    onError: e => message.error('验证码请求失败~')
  })

  // 点击了登录
  const handleLoginegByCode = async (value: any) => {
    // 至少 6 位字符，包含字母和数字
    const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,}$/

    if (passwordRegex.test(value.password)) {
      const res = await Login2pService.postSetPassword(encryptionPhone, value.code, md5(value.password))
      if (res.data.Ret === 200) {
        message.success('操作成功')
        login2p.getUserDetail()
        closeModalHandler()
      } else {
        message.error(res.data.Msg)
      }
    } else {
      message.error('请设置6位以上数字字母组合')
      return
    }
  }

  // 手机验证码
  const getVCodeData = () => {
    if (!encryptionPhone) {
      message.warning('格式错误，请输入正确的手机号码')
      return
    }
    setIsDisabled(true)
    let countdown = 60
    const captchaCountdown = setInterval(() => {
      setCaptchaBtnText(`${countdown--}s`)
    }, 1000)
    setTimeout(() => {
      setIsDisabled(false)
      setCaptchaBtnText('获取验证码')
      clearInterval(captchaCountdown)
    }, 60000)
    getLoginCode(phoneAreaCode, encryptionPhone)
  }
  // 关闭弹框事件
  const closeModalHandler = () => {
    onCancelPassword()
  }
  return (
    <Modal open={visible} closable={false} destroyOnClose={true} maskClosable={false} footer={null} width={600}>
      <div className={`${styles['login-content-bg-img']} ${styles['login-content-box-set-up']} `}>
        <div className="password-dlg-title">设置密码</div>
        <div className={styles['login-columncenter-content']}>
          <Form form={form} onFinish={handleLoginegByCode}>
            <div className={styles['encryption-phone-text']}>
              +{phoneAreaCode} &nbsp;
              {encryptionPhone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')}
            </div>
            <Form.Item style={{ marginBottom: '5px' }}>
              <Form.Item name={'code'} rules={[{ required: true, message: 'Please input Captcha!' }]}>
                <div className={styles['input-content']}>
                  <Input
                    prefix={<SafetyCertificateOutlined style={{ color: '#E37318', fontSize: 20, marginRight: 10 }} />}
                    placeholder="请输入验证码"
                  />
                  <Button
                    onClick={getVCodeData}
                    style={{ width: 160, marginLeft: '12px' }}
                    loading={loadingVCode}
                    disabled={isDisabled}
                    className="custom-style-bottom"
                  >
                    {captchaBtnText}
                  </Button>
                </div>
              </Form.Item>
            </Form.Item>
            <Form.Item style={{ marginBottom: '-19px' }}>
              <Form.Item>
                <div className={styles['input-content']}>
                  <Form.Item
                    name={'password'}
                    style={{ width: '100%', display: 'inline-block' }}
                    rules={[{ required: true, message: 'Please input Password!' }]}
                  >
                    <Input.Password
                      style={{ height: 40 }}
                      prefix={<LoginPassword style={{ width: 20, marginRight: 10 }} />}
                      placeholder="请设置登录密码（6位以上数字字母组合）"
                    />
                  </Form.Item>
                </div>
              </Form.Item>
            </Form.Item>
            <Form.Item>
              <div className="password-btn-box">
                <Button
                  onClick={closeModalHandler}
                  htmlType="button"
                  className="password-btn"
                  style={{ color: '#faa12f' }}
                >
                  取消
                </Button>
                <Button type="primary" htmlType="submit" className="password-btn">
                  确定
                </Button>
              </div>
            </Form.Item>
          </Form>
        </div>
      </div>
    </Modal>
  )
}

export default SetUpPassword
