import {
  AlipayOutlined, KeyOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoOutlined,
  UserOutlined,
  WeiboOutlined,
} from '@ant-design/icons';
import {
  LoginFormPage,
  ProConfigProvider,
  ProFormCaptcha,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {Alert, Button, Divider, Image, message, Space, Tabs, theme} from 'antd';
import type { CSSProperties } from 'react';
import React, {useEffect, useState} from 'react';
import {FormattedMessage, history, useIntl, useModel} from "@@/exports";
type LoginType = 'phone' | 'account';

const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};
import { getFakeCaptcha } from '@/services/ant-design-pro/login';
import {postMenuGetMenu} from "@/services/system/Menu";
import {flushSync} from "react-dom";
import {postBaseCaptcha, postBaseLogin} from "@/services/system/Base";

const Page = () => {
  // const [loginType, setLoginType] = useState<LoginType>('account');
  const { token } = theme.useToken();

  const [captcha, setCaptcha] = useState<string>('');
  const [captchaId, setCaptchaId] = useState<string>('');
  const intl = useIntl();
  const { initialState, setInitialState } = useModel('@@initialState');
  const [userLoginState, setUserLoginState] = useState<API.LoginResult>({});
  const [type, setType] = useState<string>('account');

  const [loginLoading, setLoginLoading] = useState<boolean>(false);
  const refreshCaptcha = () => {
    postBaseCaptcha().then((r: API.Response) => {
      let resp_data: API.SysCaptchaResponse = r.data
      setCaptcha(resp_data?.picPath ||'')
      setCaptchaId(resp_data?.captchaId || '')
    })
  }

  useEffect(()=>{
    refreshCaptcha()
  }, [])

  const LoginMessage: React.FC<{
    content: string;
  }> = ({ content }) => {
    return (
      <Alert
        style={{
          marginBottom: 24,
        }}
        message={content}
        type="error"
        showIcon
      />
    );
  };
  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    const menus = await postMenuGetMenu();
    if (userInfo) {
      console.log(22, userInfo)
      flushSync(() => {
        setInitialState((s) => ({
          ...s,
          currentUser: userInfo,
          menuData: menus.data.routes
        }));
      });
    }
  };

  const handleSubmit = async (values: API.Login) => {
    try {
      // 登录
      //{username: "admin", password: "123456", captcha: "5531", captchaId: "GMeC0be8js61jFfbBaXz"}
      const msg = await postBaseLogin({...values, captchaId: captchaId})

      // const msg = await login({ ...values, type });
      if (msg.success === true) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });
        message.success(defaultLoginSuccessMessage);
        localStorage.setItem('access', msg.data?.token || '');
        fetchUserInfo().then(()=>{
          const urlParams = new URL(window.location.href).searchParams;
          history.push(urlParams.get('redirect') || '/');
        });
        return;
        // GetUserProfile().then(r=>{
        //   console.log(223, r)
        // })
      }
      // 如果失败去设置用户错误信息
      setUserLoginState({ status: msg.success ? 'ok': 'error', type: type, currentAuthority: msg.data?.token || ''});
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      message.error(defaultLoginFailureMessage);
      refreshCaptcha()
    } finally {
      setLoginLoading(false)
    }
  };
  const { status, type: loginType } = userLoginState;

  return (
    <div
      style={{
        backgroundColor: 'white',
        height: '100vh',
      }}
    >
      <LoginFormPage
        // backgroundImageUrl="/bg.png"
        backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
        title="苏胜天智能AI系统"
        containerStyle={{
          backgroundColor: 'rgba(0, 0, 0,0.65)',
          backdropFilter: 'blur(4px)',
          color: 'rgba(255, 255, 255, 0.85)',
        }}
        subTitle="欢迎登录，苏胜天智能ai系统"
        onFinish={async (values) => {
          setLoginLoading(true)
          await handleSubmit(values as API.Login);
        }}
        loading={loginLoading}
        initialValues={{
          autoLogin: true,
        }}
        // actions={
        //   <div
        //     style={{
        //       display: 'flex',
        //       justifyContent: 'center',
        //       alignItems: 'center',
        //       flexDirection: 'column',
        //     }}
        //   >
        //     <Divider plain>
        //       <span
        //         style={{
        //           color: token.colorTextPlaceholder,
        //           fontWeight: 'normal',
        //           fontSize: 14,
        //         }}
        //       >
        //         其他登录方式
        //       </span>
        //     </Divider>
        //     <Space align="center" size={24}>
        //       <div
        //         style={{
        //           display: 'flex',
        //           justifyContent: 'center',
        //           alignItems: 'center',
        //           flexDirection: 'column',
        //           height: 40,
        //           width: 40,
        //           border: '1px solid ' + token.colorPrimaryBorder,
        //           borderRadius: '50%',
        //         }}
        //       >
        //         <AlipayOutlined style={{ ...iconStyles, color: '#1677FF' }} />
        //       </div>
        //       <div
        //         style={{
        //           display: 'flex',
        //           justifyContent: 'center',
        //           alignItems: 'center',
        //           flexDirection: 'column',
        //           height: 40,
        //           width: 40,
        //           border: '1px solid ' + token.colorPrimaryBorder,
        //           borderRadius: '50%',
        //         }}
        //       >
        //         <TaobaoOutlined style={{ ...iconStyles, color: '#FF6A10' }} />
        //       </div>
        //       <div
        //         style={{
        //           display: 'flex',
        //           justifyContent: 'center',
        //           alignItems: 'center',
        //           flexDirection: 'column',
        //           height: 40,
        //           width: 40,
        //           border: '1px solid ' + token.colorPrimaryBorder,
        //           borderRadius: '50%',
        //         }}
        //       >
        //         <WeiboOutlined style={{ ...iconStyles, color: '#1890ff' }} />
        //       </div>
        //     </Space>
        //   </div>
        //}
      >
        <Tabs
          centered
          activeKey={type}
          onChange={(activeKey) => setType(activeKey as LoginType)}
          items={[
            {
              key: 'account',
              label: intl.formatMessage({
                id: 'pages.login.accountLogin.tab',
                defaultMessage: '账户密码登录',
              }),
            },
            // {
            //   key: 'mobile',
            //   label: intl.formatMessage({
            //     id: 'pages.login.phoneLogin.tab',
            //     defaultMessage: '手机号登录',
            //   }),
            // },
          ]}

        >
          {/*<Tabs.TabPane key={'account'} tab={'账号密码登录'} />*/}
          {/*<Tabs.TabPane key={'phone'} tab={'手机号登录'} />*/}
        </Tabs>
        {status === 'error' && loginType === 'account' && (
          <LoginMessage
            content={intl.formatMessage({
              id: 'pages.login.accountLogin.errorMessage',
              defaultMessage: '账户或密码错误',
            })}
          />
        )}
        {type === 'account' && (
          <>
            <ProFormText
              name="username"
              fieldProps={{
                size: 'large',
                prefix: (
                  <UserOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'用户名:'}
              rules={[
                {
                  required: true,
                  message: '请输入用户名!',
                },
              ]}
            />
            <ProFormText.Password
              name="password"
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              placeholder={'密码:'}
              rules={[
                {
                  required: true,
                  message: '请输入密码！',
                },
              ]}
            />
            <ProFormText
              name="captcha"
              fieldProps={{
                size: 'large',
                prefix: <KeyOutlined />,
              }}
              placeholder={intl.formatMessage({
                id: 'pages.login.captcha.placeholder',
                defaultMessage: '验证码:',
              })}
              rules={[
                {
                  required: true,
                  message: (
                    <FormattedMessage
                      id="pages.login.captcha.required"
                      defaultMessage="请输入验证码！"
                    />
                  ),
                },
              ]}
              addonAfter={<Image style={{backgroundColor:'white'}} width={120} preview={false} src={captcha} onClick={refreshCaptcha}></Image>}
            />
          </>
        )}
        {loginType === 'phone' && (
          <>
            <ProFormText
              fieldProps={{
                size: 'large',
                prefix: (
                  <MobileOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              name="mobile"
              placeholder={'手机号'}
              rules={[
                {
                  required: true,
                  message: '请输入手机号！',
                },
                {
                  pattern: /^1\d{10}$/,
                  message: '手机号格式错误！',
                },
              ]}
            />
            <ProFormCaptcha
              fieldProps={{
                size: 'large',
                prefix: (
                  <LockOutlined
                    style={{
                      color: token.colorText,
                    }}
                    className={'prefixIcon'}
                  />
                ),
              }}
              captchaProps={{
                size: 'large',
              }}
              placeholder={'请输入验证码'}
              captchaTextRender={(timing, count) => {
                if (timing) {
                  return `${count} ${'获取验证码'}`;
                }
                return '获取验证码';
              }}
              name="captcha"
              rules={[
                {
                  required: true,
                  message: '请输入验证码！',
                },
              ]}
              onGetCaptcha={async () => {
                message.success('获取验证码成功！验证码为：1234');
              }}
            />
          </>
        )}
        <div
          style={{
            marginBlockEnd: 24,
          }}
        >
          <ProFormCheckbox noStyle name="autoLogin">
            自动登录
          </ProFormCheckbox>
          <a
            style={{
              float: 'right',
            }}
          >
            忘记密码
          </a>
        </div>
      </LoginFormPage>
    </div>
  );
};

export default () => {

  return (
    <ProConfigProvider dark>
      <Page />
    </ProConfigProvider>
  );
};
