import { Footer } from '@/components';
import { login, validateCode } from '@/services/user/index';
import {
  LockOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormText,
} from '@ant-design/pro-components';
import { FormattedMessage, Helmet, useIntl, useModel } from '@umijs/max';
import { message, Row, Col, Image } from 'antd';
import { createStyles } from 'antd-style';
import React, { useState, useEffect } from 'react';
import { flushSync } from 'react-dom';
import Settings from '../../../../config/defaultSettings';
import "./index.css";

const useStyles = createStyles(({ token }) => {
  return {
    action: {
      marginLeft: '8px',
      color: 'rgba(0, 0, 0, 0.2)',
      fontSize: '24px',
      verticalAlign: 'middle',
      cursor: 'pointer',
      transition: 'color 0.3s',
      '&:hover': {
        color: token.colorPrimaryActive,
      },
    },
    lang: {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    },
    container: {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    },
  };
});


const Login: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const { styles } = useStyles();
  const intl = useIntl();
  const [captchaCode, setCaptchaCode] = useState<string>('');
  const [uuid, setUuid] = useState<string>('');

  const getCaptchaCode = async () => {
    const { data } = await validateCode();
    const imgdata = `data:image/png;base64,${data.img}`;
    setCaptchaCode(imgdata);
    setUuid(data.uuid);
  };





  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    console.log(userInfo, 'userInfo');

    if (userInfo) {
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
        }));
      });
    }
  };

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      const msg = await login({ ...values, uuid });
      if (msg.success || msg.status == 'ok') {
        localStorage.setItem('token', msg.data?.token)
        const defaultLoginSuccessMessage = '登录成功！';
        message.success(defaultLoginSuccessMessage);
        await fetchUserInfo();
        const urlParams = new URL(window.location.href).searchParams;
        window.location.href = urlParams.get('redirect') || '/';
        return;
      }
    } catch (error) {
      getCaptchaCode()
    }
  };


  useEffect(() => {
    getCaptchaCode();
  }, []);

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      {/* <Lang /> */}
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          // logo={<img alt="logo" src="/logo.svg" />}
          title="广东星动 管理后台"
          subTitle={'广东星动 管理后台'}
          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="password"
              fieldProps={{
                size: 'large',
                prefix: <LockOutlined />,
              }}
              placeholder={'请输入密码'}

              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
            <Row>
              <Col flex={3}>
                <ProFormText
                  fieldProps={{
                    size: 'large',
                  }}
                  style={{
                    float: 'right',
                  }}
                  name="code"
                  placeholder={'请输入验证码'}
                  rules={[
                    {
                      required: true,
                      message: '请输入验证码',
                    },
                  ]}
                />
              </Col>
              <Col flex={2}>
                <Image
                  src={captchaCode}
                  alt="验证码"
                  style={{
                    display: 'inline-block',
                    verticalAlign: 'top',
                    cursor: 'pointer',
                    paddingLeft: '10px',
                    width: '100px',
                    height:'40px'
                  }}
                  preview={false}
                  onClick={() => getCaptchaCode()}
                />
              </Col>
            </Row>
          </>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
