import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { Helmet, history, useModel } from '@umijs/max';
import { Alert, message } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';

import Footer from '@/components/footer';
import { login } from '@/services/user';
import { setToken } from '@/utils/login';

import Settings from '../../../../config/defaultSettings';

const useStyles = createStyles(() => {
  return {
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
    },
  };
});

const Login: React.FC = () => {
  const [loginError, setLoginError] = useState<boolean>(false);
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      flushSync(() => {
        setInitialState(s => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };
  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      console.log('login params', values);
      const result = await login({ ...values });
      if (result.token) {
        setToken(result.token);
        message.success('登录成功！');
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/');
        return;
      }
      console.log(result);
      // 如果失败去设置用户错误信息
      setLoginError(true);
    } catch (error) {
      console.log(error);
      message.error('登录失败，请重试！');
    }
  };
  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'登录'}- {Settings.title}
        </title>
      </Helmet>
      <div style={{ flex: '1', padding: '32px 0' }}>
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src={Settings.logo} />}
          subTitle=" "
          title="播络管理后台"
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async values => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <ProFormText
            name="userName"
            fieldProps={{ size: 'large', prefix: <UserOutlined /> }}
            placeholder="请输入账号"
            rules={[{ required: true, message: '账号不能为空!' }]}
          />
          <ProFormText.Password
            name="pwd"
            fieldProps={{ size: 'large', prefix: <LockOutlined /> }}
            placeholder="请输入密码"
            rules={[{ required: true, message: '密码不能为空!' }]}
          />
          {loginError && <Alert style={{ marginBottom: 24 }} message="用户名或密码错误" type="error" showIcon />}
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};
export default Login;
