import { LockOutlined, UserOutlined } from '@ant-design/icons'
import { Alert, message, Tabs } from 'antd'
import React, { useState } from 'react'
import ProForm, { ProFormCheckbox, ProFormText } from '@ant-design/pro-form'
import { useIntl, Link, history, FormattedMessage, SelectLang, useModel, useRequest } from 'umi'
import { login } from '@/services/api/login'
import { currentAccount as querycurrentAccount } from '@/services/api/login'
import consts from '@/utils/consts'
import styles from './index.less'

const LoginMessage: React.FC<{
  content: string
}> = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24
    }}
    message={content}
    type="error"
    showIcon
  />
)

/** 此方法会跳转到 redirect 参数所在的位置 */
const goto = () => {
  if (!history) return
  setTimeout(() => {
    const { query } = history.location
    const { redirect } = query as { redirect: string }
    history.push(redirect || '/')
  }, 10)
}

const Login: React.FC = () => {
  const { setAuthToken } = useModel('user')
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({})
  const [type, setType] = useState<string>('account')
  const { initialState, setInitialState } = useModel('@@initialState')

  const { run, loading } = useRequest(querycurrentAccount, {
    manual: true,
    onSuccess: async result => {
      setInitialState({
        ...initialState,
        currentUser: result.currentAccount
      })
      goto()
    }
  })

  const intl = useIntl()

  // const fetchUserInfo = async () => {
  //   const userInfo = await initialState?.fetchUserInfo?.()
  //   if (userInfo) {
  //     await setInitialState(s => ({
  //       ...s,
  //       currentUser: userInfo
  //     }))
  //   }
  // }

  const { run: tryLogin } = useRequest((values: API.LoginParams) => login(values), {
    manual: true,
    onSuccess: async result => {
      setAuthToken(result?.token)
      message.success('登录成功')
      await run()
      // await fetchUserInfo()
    },
    onError: () => {
      setUserLoginState({ ...userLoginState, code: -1 })
    }
  })

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      await tryLogin(values)
    } catch (error) {
      message.error('登录失败，请重试')
    }
    // try {
    //   // 登录
    //   const msg = await login({ ...values, type })
    //   if (msg.status === 'ok') {
    //     const defaultLoginSuccessMessage = intl.formatMessage({
    //       id: 'pages.login.success',
    //       defaultMessage: '登录成功！'
    //     })
    //     message.success(defaultLoginSuccessMessage)
    //     await fetchUserInfo()
    //     /** 此方法会跳转到 redirect 参数所在的位置 */
    //     if (!history) return
    //     const { query } = history.location
    //     const { redirect } = query as { redirect: string }
    //     history.push(redirect || '/')
    //     return
    //   }
    //   console.log(msg)
    //   // 如果失败去设置用户错误信息
    //   setUserLoginState(msg)
    // } catch (error) {
    //   const defaultLoginFailureMessage = intl.formatMessage({
    //     id: 'pages.login.failure',
    //     defaultMessage: '登录失败，请重试！'
    //   })
    //   message.error(defaultLoginFailureMessage)
    // }
  }
  const { code } = userLoginState

  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <Link to="/" className="flex justify-center">
              <img alt="logo" className={styles.logo} src="/logo.svg" />
              <span className={styles.title}>投资项目云平台</span>
            </Link>
          </div>
          <div className={styles.desc}>
            {intl.formatMessage({ id: 'pages.layouts.userLayout.title' })}
          </div>
        </div>
        <div className={styles.main}>
          <ProForm
            initialValues={{
              autoLogin: true
            }}
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({
                  id: 'pages.login.submit',
                  defaultMessage: '登录'
                })
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                loading,
                size: 'large',
                style: {
                  width: '100%'
                }
              }
            }}
            onFinish={async values => {
              handleSubmit(values as API.LoginParams)
            }}>
            <Tabs activeKey={type} onChange={setType}>
              <Tabs.TabPane
                key="account"
                tab={intl.formatMessage({
                  id: 'pages.login.accountLogin.tab',
                  defaultMessage: '账户密码登录'
                })}
              />
            </Tabs>

            {code === consts.RET_CODE.ERROR && <LoginMessage content={'账户或密码错误'} />}
            {type === 'account' && (
              <>
                <ProFormText
                  name="account"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className={styles.prefixIcon} />
                  }}
                  placeholder={intl.formatMessage({
                    id: 'pages.login.username.placeholder',
                    defaultMessage: '请输入用户名'
                  })}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.username.required"
                          defaultMessage="请输入用户名!"
                        />
                      )
                    }
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={styles.prefixIcon} />
                  }}
                  placeholder={intl.formatMessage({
                    id: 'pages.login.password.placeholder',
                    defaultMessage: '请输入密码！'
                  })}
                  rules={[
                    {
                      required: true,
                      message: (
                        <FormattedMessage
                          id="pages.login.password.required"
                          defaultMessage="请输入密码！"
                        />
                      )
                    }
                  ]}
                />
              </>
            )}

            {/* {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />} */}
            <div
              style={{
                marginBottom: 24
              }}>
              <ProFormCheckbox noStyle name="autoLogin">
                <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
              </ProFormCheckbox>
              <a
                style={{
                  float: 'right'
                }}>
                <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
              </a>
            </div>
          </ProForm>
        </div>
      </div>
    </div>
  )
}

export default Login
