import Footer from '@/components/Footer';
import { login } from '@/services/auth/api';
import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormCaptcha, ProFormCheckbox, ProFormText } from '@ant-design/pro-form';
import { Alert, message, Tabs } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import { history, SelectLang, useIntl } from 'umi';
import { getAccount,} from '@/services/auth/user';

import styles from './index.less';

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

const Login: React.FC = () => {
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');
  const formRef = useRef<any>();

  useEffect(() => {

    let password = sessionStorage.getItem('password')
    let username = sessionStorage.getItem('username')

    if (password && username) {
      formRef?.current?.setFieldsValue({
        password: password,
        username: username,
      });
    }


  }, [])

  const intl = useIntl();

  const handleSubmit = async (values: any) => {
    try {
      // 登录
      const msg = (await login({ ...values, type })) as any;

      let { id_token } = msg
      let { password, username, autoLogin } = values
      if (autoLogin) {
        sessionStorage.setItem('password', password)
        sessionStorage.setItem('username', username)
      } else {
        sessionStorage.removeItem('username')
        sessionStorage.removeItem('password')
      }
      sessionStorage.setItem('Authorization', id_token)

      if (id_token) {
        // history.push('/user/welcome');
        setTimeout(() => {
          getAccount().then((res: any) => {
            sessionStorage.setItem('User', JSON.stringify(res))
            message.success('登陆成功');
            // getRolesUser(res?.login).then((res: any) => {
            //   getPermissionsUser().then((res: any) => {
            //   });
            //   getResourcesUser(res[0]?.name).then((res: any) => {
            //   });
            // });
            history.push('/user/welcome');
            window.location.reload()
          });
        }, 1000);
      } else {
        message.error(JSON.parse(msg).message);
      }
    } catch (error) {
      message.error('用户名或密码错误');
    }
  };
  const { status, type: loginType } = userLoginState;

  return (
    <div className={styles.container}>
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src={require("./images/logo.png")} />}
          title="座舱教师端管理"
          subTitle="  "
          formRef={formRef}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          {status === 'error' && loginType === 'account' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误(admin/ant.design)',
              })}
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入用户名'}
                rules={[
                  {
                    required: true,
                    message: ('请输入用户名'),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: ('请输入密码'),
                  },
                ]}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              记住用户名密码
            </ProFormCheckbox>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
