import React, { useState } from 'react'
import { useHistory, useLocation } from 'react-router-dom'
import useRequest from '@ahooksjs/use-request'
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
import wx from 'weixin-js-sdk'

import { Col, Row, Card, Input, Button, Select, Form, message } from 'antd'
import { WechatOutlined } from '@ant-design/icons'

import { Login2pService } from './Login2p.service'
import { useLogin2p } from './Login2pContext'
import { useMedia } from 'Context/Media/MediaContext'
import styles from '../styles/NewPage.module.scss'

const { Option } = Select

const Login2p: React.FC = () => {
  const media = useMedia()
  const login2p = useLogin2p()
  const [form] = Form.useForm()
  const history = useHistory()
  const wechatToken = new URLSearchParams(useLocation().search).get('smtoken')
  const next = new URLSearchParams(useLocation().search).get('next')
  const [isDisabled, setIsDisabled] = useState<boolean>(false)
  const [captchaBtnText, setCaptchaBtnText] = useState<string>('发送验证码')
  const [phoneArea, setPhoneArea] = useState<number>(86)
  const colSpanBlank = { xs: 1, sm: 1, md: 4, lg: 4, xl: 8 }
  const colSpanForm = { xs: 22, sm: 22, md: 16, lg: 16, xl: 8 }
  const colPadding = media.isSmallMax === media.isBigMax ? '150px 0px 0px ' : '20px 0px'
  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 checkLogin = () => {
    if (login2p.jwt) {
      if (!login2p.isWechat) {
        history.push(`/${login2p.inviteCode ? '?invite_code=' + login2p.inviteCode : ''}`)
        message.info('您已登录').then(r => undefined)
      } else {
        //如果是微信小程序则直接退出
        // wx.miniProgram.navigateBack()
      }
    } else if (login2p.isWechat && !wechatToken) {
      login2p.loginWechatLaunch(
        `${process.env.REACT_APP_URL}login2p/wechat?next=${next ? next : encodeURIComponent('/')}`
      )
    }
  }
  const handleLoginegByCode = (value: any) => {
    login2p
      .login2pByCode(value.phone_number, value.code, next ? next : '/', wechatToken ? wechatToken : undefined)
      .then(r => undefined)
  }

  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'))) {
      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(), form.getFieldValue('phone_number'))
  }

  React.useEffect(checkLogin, [])

  return (
    <Row gutter={24} style={{ width: '100%' }}>
      {/*0-780px*/}
      {/*780px-1280px*/}
      {/*1280px-max*/}
      <Col {...colSpanBlank} />
      <Col
        {...colSpanForm}
        style={{
          padding: colPadding,
          fontSize: '18px'
        }}
      >
        <Card>
          <Form form={form} onFinish={handleLoginegByCode}>
            <div className={styles['login-title']}>验证码登录</div>
            <Form.Item style={{ marginBottom: '5px' }}>
              <p style={{ lineHeight: '24px', fontSize: '16px' }}>手机号</p>
              <Form.Item name="phone_number" rules={[{ required: true, message: 'Please input your phone number!' }]}>
                <Input
                  addonBefore={
                    <Select
                      defaultValue={phoneArea}
                      onChange={value => {
                        setPhoneArea(value)
                      }}
                    >
                      {phoneAreaList.map(item => (
                        <Option value={item.id} key={item.id}>
                          {item.optionName}
                        </Option>
                      ))}
                    </Select>
                  }
                  placeholder="请输入手机号"
                />
              </Form.Item>
            </Form.Item>
            <Form.Item style={{ marginBottom: '5px' }}>
              <p style={{ lineHeight: '24px', fontSize: '16px' }}>验证码</p>
              <Form.Item>
                <Form.Item
                  name={'code'}
                  style={{ width: '65%', display: 'inline-block' }}
                  rules={[{ required: true, message: 'Please input Captcha!' }]}
                >
                  <Input placeholder="请输入验证码" />
                </Form.Item>
                <Button onClick={getVCodeData} style={{ width: '35%' }} loading={loadingVCode} disabled={isDisabled}>
                  {captchaBtnText}
                </Button>
              </Form.Item>
            </Form.Item>
            <Form.Item>
              <Button type="primary" block htmlType="submit">
                验证码登录
              </Button>
            </Form.Item>
            <Form.Item style={{ textAlign: 'center' }}>
              <Button
                icon={<WechatOutlined style={{ color: '#60C84D' }} />}
                onClick={() =>
                  login2p.loginWechatLaunch(
                    `${process.env.REACT_APP_URL}login2p/wechat?next=${next ? next : encodeURIComponent('/')}`
                  )
                }
                shape="circle"
                size="large"
                style={{ paddingTop: '7px' }}
              ></Button>
            </Form.Item>
          </Form>
        </Card>
      </Col>
      <Col {...colSpanBlank} />
    </Row>
  )
}

export default Login2p
