import styles from './index.module.scss'

import { Input } from 'antd'
import { UserOutlined, LockOutlined, NumberOutlined } from '@ant-design/icons'
import { useCallback, useEffect, useRef, useState } from 'react'
import { Base64 } from 'js-base64'
import encodeStr from '@/utils/pass'
import { setTokenInfo } from '@/utils/storage'
import history from '@/utils/history'
import { MessageFu } from '@/utils/message'
import { API_LoginGetCode, userLoginAPI } from '@/store/action/layout'
import store, { RootState } from '@/store'
import PassEdit from '../Layout/PassEdit'
import { useSelector } from 'react-redux'
import { defaultPassWord } from '@/utils/http'

export default function Login() {
  // 获取验证码
  const LoginGetCodeFu = useCallback(async () => {
    const res: any = await API_LoginGetCode()
    const reader = new FileReader()
    reader.readAsDataURL(res)
    reader.onload = () => {
      setCodeImg(reader.result)
    }
  }, [])

  useEffect(() => {
    LoginGetCodeFu()
  }, [LoginGetCodeFu])

  // 账号密码 - 验证码
  const [userName, setUserName] = useState('')
  const [passWord, setPassWord] = useState('')
  const [code, setCode] = useState<any>('')
  const [codeImg, setCodeImg] = useState<any>('')

  // 键盘按下回车事件
  const keyUpEntFu = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') loginClickFu()
  }

  const userTokenInfoRef = useRef<any>({})

  // 点击登录
  const loginClickFu = useCallback(async () => {
    // 非空判断
    if (userName === '') return MessageFu.warning('请输入账号!')
    else if (passWord === '') return MessageFu.warning('请输入密码!')
    const obj = {
      userName,
      password: encodeStr(Base64.encode(passWord)),
      randCode: code
    }
    const res: any = await userLoginAPI(obj)
    if (res.code === 0) {
      userTokenInfoRef.current = { ...res.data, token: res.data.satoken }

      // 检查密码是不是默认密码，是的话给提示
      if (passWord === defaultPassWord) {
        MessageFu.warning('为保障账号安全，请修改默认密码')
        setCode('')
        LoginGetCodeFu()
        store.dispatch({ type: 'layout/passEditShow', payload: true })
      } else {
        MessageFu.success('登录成功')
        // 用户信息存到本地
        setTokenInfo(userTokenInfoRef.current)
        const urlAll = window.location.href
        if (urlAll.includes('?back=')) {
          const url = urlAll.split('?back=')[1]
          if (url) history.replace(`/${url}`)
          else history.replace('/')
        } else history.replace('/')
      }
    } else if (res.code === 3014) {
      MessageFu.warning('账号不存在或密码错误，请联系管理员!')
    } else if (res.code === -1 && res.msg === '验证码有误') {
      LoginGetCodeFu()
    }
  }, [LoginGetCodeFu, code, passWord, userName])

  const { passEditShow } = useSelector((state: RootState) => state.A0Layout)

  return (
    <div className={styles.Login}>
      {/* logg */}
      <div className='LogoImg'>
        <img src={require('@/assets/img/logo2.png')} alt='' />
      </div>

      <div className='mainRight'>
        <h3>青岛啤酒博物馆藏品管理系统</h3>

        {/* 账号密码输入框 */}
        <div className='inputBox'>
          <div className='inputBoxRow'>
            <Input
              onKeyUp={e => keyUpEntFu(e)}
              value={userName}
              onChange={e => setUserName(e.target.value.trim())}
              prefix={<UserOutlined rev={undefined} />}
              placeholder='请输入账号'
              maxLength={15}
            />
          </div>
          <div className='inputBoxRow'>
            <Input.Password
              onKeyUp={e => keyUpEntFu(e)}
              value={passWord}
              onChange={e => setPassWord(e.target.value.trim())}
              prefix={<LockOutlined rev={undefined} />}
              placeholder='请输入密码'
              maxLength={20}
            />
          </div>
          <div className='inputBoxRow inputBoxRow2'>
            <Input
              onKeyUp={e => keyUpEntFu(e)}
              value={code}
              onChange={e => setCode(e.target.value.trim())}
              prefix={<NumberOutlined rev={undefined} />}
              placeholder='请输入验证码'
              maxLength={5}
            />
            {codeImg ? (
              <img onClick={LoginGetCodeFu} className='loginCode' src={codeImg} alt='' />
            ) : null}
          </div>
          {/* 登录按钮 */}
          <div className='loginBtn' onClick={loginClickFu}>
            <img src={require('@/assets/img/loginBtn.png')} alt='' />登 录
          </div>
        </div>
      </div>
      {passEditShow ? <PassEdit userTokenInfo={userTokenInfoRef.current} /> : null}
    </div>
  )
}
