import { login } from '@/services/ant-design-pro/api';
import { getCaptchaId } from '@/services/ant-design-pro/login';
import { DefaultFooter } from '@ant-design/pro-components';
import { Button, Form, Input, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { history, useModel } from 'umi';
import styles from './index.less';
import md5 from 'js-md5';
import { SafetyCertificateOutlined, UnlockOutlined, UserOutlined } from '@ant-design/icons';

const FormItem = Form.Item;

/**
 *
 * @returns footer
 */
const Footer: React.FC = () => {
  const currentYear = new Date().getFullYear();
  const defaultMessage = '永续绿建运营管理平台';
  return <DefaultFooter className={styles.footer} copyright={`${currentYear} ${defaultMessage}`} />;
};

const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [captcha_id, setCaptcha_id] = useState('');

  /**
   * 获取验证码id
   */
  const fetchCaptcha = () => {
    getCaptchaId().then(async (res) => {
      if (res.code === 0) {
        setCaptcha_id(res.data.captcha_id);
      }
    });
  };

  /**
   * 初始化
   */
  useEffect(() => {
    fetchCaptcha();
  }, []);

  /**
   * 获取账号用户信息
   */
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s: any) => ({ ...s, currentUser: userInfo }));
    }
  };

  /**
   * 登录
   * @param values
   * @returns
   */
  const handleSubmit = async (values: API.LoginParams) => {
    try {
      const body = {
        ...values,
        password: md5(values.password),
        captcha_id,
      };
      const msg: any = await login(body);

      if (msg.code === 0) {
        if (localStorage.getItem('token') == null || localStorage.getItem('token') == undefined) {
          localStorage.setItem('token', '');
        }
        localStorage.setItem('token', `${msg.data.token_type} ${msg.data.access_token}`);
        message.success(`欢迎登录系统`);
        await fetchUserInfo();
        history.push('/');
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query as { redirect: string };
        history.push(redirect || '/');
      } else {
        message.error(msg?.message || '登录失败');
        fetchCaptcha();
      }
    } catch (error) {
      message.success(`登录失败`);
      fetchCaptcha();
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.loginBox}>
        <img src="/assets/logo.png" className={styles.logo_style} alt="" />
        {/*<img alt="请登录" src="/assets/login_left.png" className={styles.login_bg} />*/}
        <div className={styles.main}>
          <div className={styles.title}>
            <div
              style={{
                fontSize: '28px',
                fontWeight: 'bold',
                marginLeft: '10px',
                marginBottom: '5px',
              }}
            >
              永续绿建运营管理平台
            </div>
            <div
              style={{ marginLeft: '10px', fontSize: '16px', color: '#999', marginBottom: '60px' }}
            >
              欢迎登录
            </div>
          </div>
          <Form layout="vertical" onFinish={handleSubmit}>
            <FormItem
              rules={[{ required: true, message: '请输入手机号!' }]}
              className={styles.formItem}
              name="phone"
            >
              <Input
                className={styles.formItemInput}
                size="large"
                placeholder="请输入手机号"
                prefix={<UserOutlined />}
                allowClear
              />
            </FormItem>
            <FormItem
              className={styles.formItem}
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input
                className={styles.formItemInput}
                size="large"
                type="password"
                placeholder="请输入密码"
                prefix={<UnlockOutlined />}
                allowClear
              />
            </FormItem>
            <FormItem
              className={styles.formItem}
              name="captcha_code"
              rules={[{ required: true, message: '请输入验证码!' }]}
            >
              <Input
                className={styles.formItemInput}
                size="large"
                prefix={<SafetyCertificateOutlined />}
                suffix={
                  <img
                    className={styles.captcha}
                    onClick={() => {
                      fetchCaptcha();
                    }}
                    src={`/web/v1/login/captcha?id=${captcha_id}`}
                    alt="验证码"
                  />
                }
                placeholder="请输入验证码"
              />
            </FormItem>
            <div>
              <Button className={styles.submit} htmlType="submit">
                登录
              </Button>
            </div>
          </Form>
        </div>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
