import React, { useEffect, useState } from 'react'
import useRequest from '@ahooksjs/use-request'
import { useHistory, useLocation } from 'react-router-dom'
import { Col, Row, Divider, Input, Button, Select, Form, message, Modal, TabsProps, Tabs } from 'antd'

import styles from 'styles/NewPage.module.scss'
import { SafetyCertificateOutlined, ExclamationCircleFilled } from '@ant-design/icons'
import { useLogin2p } from '../Login2pContext'
import { ReactComponent as LoginMobile } from 'assets/login_mobile.svg'
import { ReactComponent as LoginPassword } from 'assets/login_passwode.svg'
import { Login2pService } from '../Login2p.service'
interface ISetUpPasswordProps {
  visible: boolean
  isBindMobile: number
  encryptionPhone: string
  phoneAreaCode: number
  onCancelPassword: () => void
  onRefresh?: () => void
}

/**
 * 编辑专栏信息
 */
const SetUpPassword: React.FC<ISetUpPasswordProps> = props => {
  const { Option } = Select
  const { visible, isBindMobile, encryptionPhone, phoneAreaCode, onCancelPassword, onRefresh } = props
  const [form] = Form.useForm()
  const login2p = useLogin2p()
  const next = new URLSearchParams(useLocation().search).get('next')
  const wechatToken = new URLSearchParams(useLocation().search).get('smtoken')
  const [phoneArea, setPhoneArea] = useState<number>(86)

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

  const phoneAreaList = [
    { id: 86, optionName: '中国(+86)', regText: /^1\d{10}$/ },
    { id: 853, optionName: '中国澳门(+853)', regText: /^6\d{7}$/ },
    { id: 852, optionName: '中国香港(+852)', regText: /^[569]\d{3}\-?\d{4}$/ },
    { id: 61, optionName: '澳大利亚(+61)', regText: /^4\d{8}$/ },
    { id: 65, optionName: '新加坡(+65)', regText: /^[89]\d{7}$/ },
    { id: 1, optionName: '美国(+001)', regText: /^[2-9]\d{2}[2-9](?!11)\d{6}$/ },
    { id: 81, optionName: '日本(+81)', regText: /^\d{1,4}[ \-]?\d{1,4}[ \-]?\d{4}$/ },
    { id: 44, optionName: '英国(+44)', regText: /^\+?[0-9,\-,\s]{5,20}$/ },
    { id: 886, optionName: '中国台湾(+886)', regText: /^[0][9]\d{8}$/ }
  ]
  const { run: getLoginCode, loading: loadingVCode } = useRequest(Login2pService.getVCode, {
    manual: true,
    formatResult: response => response.data,
    onSuccess: result => message.success('验证码请求成功!'),
    onError: e => message.error('验证码请求失败~')
  })

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

    if (passwordRegex.test(value.password)) {
      login2p.initPassword(
        value.phone_number || encryptionPhone,
        value.code || phoneAreaCode,
        isBindMobile + '',
        value.password,
        next ? next : '/'
      )
    } else {
      message.error('请设置6位以上数字字母组合')
      return
    }
  }

  const checkPhoneNumber = (phoneNumber: string) => {
    const findItem = phoneAreaList.find(item => item.id === phoneArea)
    return findItem ? findItem.regText.test(phoneNumber) : false
  }

  // 手机验证码
  const getVCodeData = () => {
    if (!checkPhoneNumber(form.getFieldValue('phone_number')) && !encryptionPhone) {
      message.warning('格式错误，请输入正确的手机号码')
      return
    }
    setIsDisabled(true)
    let countdown = 60
    const captchaCountdown = setInterval(() => {
      setCaptchaBtnText(`${countdown--}s`)
    }, 1000)
    setTimeout(() => {
      setIsDisabled(false)
      setCaptchaBtnText('获取验证码')
      clearInterval(captchaCountdown)
    }, 60000)
    getLoginCode(
      phoneArea.toString() || phoneAreaCode.toString(),
      form.getFieldValue('phone_number') || encryptionPhone
    )
  }
  // 关闭弹框事件
  const closeModalHandler = () => {
    onCancelPassword()
  }
  return (
    <Modal open={visible} closable={false} destroyOnClose={true} maskClosable={false} footer={null} width={800}>
      {isBindMobile === 1 && (
        <div className={styles['set-up-password-text']}>
          <ExclamationCircleFilled style={{ color: '#E37318', fontSize: 18, marginRight: 8 }} />
          该账号尚未设置登录密码，请先设置登录密码
        </div>
      )}

      <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}>
            {isBindMobile === 1 ? (
              <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="phone_number" rules={[{ required: true, message: 'Please input your phone number!' }]}>
                  <div className={styles['input-content']}>
                    <Select
                      defaultValue={phoneArea}
                      className="select-input"
                      onChange={value => {
                        setPhoneArea(value)
                      }}
                    >
                      {phoneAreaList.map(item => (
                        <Option value={item.id} key={item.id}>
                          {item.optionName}
                        </Option>
                      ))}
                    </Select>
                    <Input prefix={<LoginMobile style={{ width: 15 }} />} placeholder="请输入手机号" />
                  </div>
                </Form.Item>
              </Form.Item>
            )}

            <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 }} />}
                    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: 60 }}
                      prefix={<LoginPassword style={{ width: 20 }} />}
                      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
