import styles from './index.less';
import React, { useState } from 'react';
import { Alert, message } from 'antd';
import { Link, useIntl, FormattedMessage, useModel, history } from 'umi';
import ProForm, { ProFormText, ProFormCheckbox } from '@ant-design/pro-form';
import { UserOutlined, LockOutlined, CloseCircleOutlined } from '@ant-design/icons';
import Footer from '@/components/Footer';
import { login } from '@/services/mgr/api';
import { setLocale } from 'umi';


const LoginMessage: React.FC = ({ children }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={children}
    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 intl = useIntl();

  const [submitting, setSubmitting] = useState(false);
  const [loginResult, setLoginResult] = useState({ message: '' });
  const { initialState, setInitialState } = useModel('@@initialState');

  const fetchUserInfo = async () => {
    const resp = await initialState?.fetchUserInfo?.();
    if (resp) {
      if (resp.user.locale) {
        console.log('locale', resp.user.locale)
        setLocale(resp.user.locale, false)
      }
      
      await setInitialState((s) => ({
        ...s,
        currentUser: resp,
      }));
    }
  };

  const handleSubmit = async (values: Api.LoginPubParams) => {
    setSubmitting(true);
    try {
      const res = await login({ ...values });
      if (res.code !== 200) {
        const msg1 = intl.formatMessage({
          id: 'pages.login.failure',
          defaultMessage: '登录失败，请重试！',
        });
        setLoginResult({ message: res.msg || msg1 });
        setSubmitting(false);
        return
      }
      const msg = intl.formatMessage({
        id: 'pages.login.success',
        defaultMessage: '登录成功！',
      });
      message.success({
        content: (
          <>
            <span>{msg}</span>
            <CloseCircleOutlined onClick={() => message.destroy()} />
          </>
        ),
      });
      await fetchUserInfo();
      goto();
      return;
    } catch (error) {
      const msg = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      setLoginResult({ message: msg });
    }
    setSubmitting(false);
  };

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={styles.header}>
            <img alt="logo" className={styles.logo} src="logo.png" />
            <span className={styles.title}>
              <FormattedMessage id="看板系统" defaultMessage="看板系统" />
            </span>
          </div>
        </div>
        <div className={styles.main}>
          <ProForm
            submitter={{
              searchConfig: {
                submitText: intl.formatMessage({
                  id: 'pages.login.submit',
                  defaultMessage: '登录',
                }),
              },
              render: (_, dom) => dom.pop(),
              submitButtonProps: {
                loading: submitting,
                size: 'large',
                style: {
                  width: '100%',
                },
              },
            }}
            onFinish={async (values) => {
              handleSubmit(values as Api.LoginPubParams);
            }}
            isKeyPressSubmit
          >
            {loginResult.message.length > 0 && <LoginMessage>{loginResult.message}</LoginMessage>}
            {
              <>
                <ProFormText
                  name="username"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className={styles.prefixIcon} />,
                    placeholder: intl.formatMessage({
                      id: 'pages.login.username.placeholder',
                      defaultMessage: '用户名',
                    }),
                  }}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        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: intl.formatMessage({
                        id: 'pages.login.password.required',
                        defaultMessage: '请输入密码',
                      }),
                    },
                  ]}
                />
              </>
            }
            {false && (
              <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>
      <Footer />
    </div>
  );
};

export default Login;
