'use client'
import {
    LockOutlined, MailOutlined,
    UserOutlined,
} from '@ant-design/icons';
import {
    LoginFormPage,
    ProFormCaptcha,
    ProFormCheckbox,
    ProFormText,
} from '@ant-design/pro-components';

import {Divider, Space, Tabs, message, theme, Modal, Button, Skeleton} from 'antd';
import React, {CSSProperties, Suspense, useCallback, useEffect, useLayoutEffect} from 'react';
import {useState} from 'react';
import {CaptchaLoginSuccess, LoginObject} from "@/lib/login/definitions";
import {httpReq} from "@/utils/axiosReq";
import {useRouter} from 'next/navigation'
import { isMobile } from 'react-device-detect';
import Cookies from "js-cookie";

type LoginType = 'email' | 'account';

const iconStyles: CSSProperties = {
    color: 'rgba(0, 0, 0, 0.2)',
    fontSize: '18px',
    verticalAlign: 'middle',
    cursor: 'pointer',
};

export default function Page() {
    const [loaded, setLoaded] = useState(false);
    useLayoutEffect(() => {
        if (isMobile){
            console.log("手机端")
        }else {
            console.log("PC端")
        }
        console.log('页面所有资源加载完毕');
        setLoaded(true);
    })
    const [loginType, setLoginType] = useState<LoginType>('account');
    const {token} = theme.useToken();
    const router = useRouter()
    const [messageApi, contextHolder] = message.useMessage();
    const [loading, setLoading] = useState(false);
    const [open, setOpen] = useState(false);
    const [captchaLoginSuccessList, setCaptchaLoginSuccessList] = useState([]);
    const captchaUserNameConfirm = (captchaLoginSuccess: CaptchaLoginSuccess) => {
        messageApi.open({
            type: 'info',
            content: "使用帐号" + captchaLoginSuccess.username + "登录成功"
        })
        localStorage.setItem('platform-security', captchaLoginSuccess.token)
        if (isMobile){
            router.push('/mobile/listTask')
        }else {
            router.push('/task/project')
        }
        setOpen(false)
        setLoading(false)
    }
    return (
        <div
            style={{
                backgroundColor: 'white',
                height: '100vh',
            }}
        >
            {contextHolder}
            <Modal
                open={open}
                title="发现您注册有多个帐号，请选择需要登录的账号"
                footer={
                    captchaLoginSuccessList.map((label: CaptchaLoginSuccess, index) => (
                        <Button key={label.username} onClick={() => captchaUserNameConfirm(label)}>
                            {label.username}
                        </Button>
                    ))
                }
            >
            </Modal>
            {loaded?<LoginFormPage
                backgroundImageUrl="/20-1733751222585.jpg"
                // logo="https://github.githubassets.com/favicons/favicon.png"
                // backgroundVideoUrl="https://gw.alipayobjects.com/v/huamei_gcee1x/afts/video/jXRBRK_VAwoAAAAAAAAAAAAAK4eUAQBr"
                title="任务管理"
                containerStyle={{
                    backgroundColor: 'rgba(0, 0, 0,0.65)',
                    backdropFilter: 'blur(4px)',
                }}
                // subTitle="任务管理"
                // activityConfig={{
                //     style: {
                //         boxShadow: '0px 0px 8px rgba(0, 0, 0, 0.2)',
                //         color: token.colorTextHeading,
                //         borderRadius: 8,
                //         backgroundColor: 'rgba(255,255,255,0.25)',
                //         backdropFilter: 'blur(4px)',
                //     },
                // }}
                onFinish={(formData: LoginObject) => {
                    console.log("登录信息：" + formData.username + ";" + formData.password)
                    if (loginType === "account") {
                        httpReq.post(process.env.NEXT_PUBLIC_SECURITY_REQUEST_URL + "/stateless/login/username", {
                            username: formData.username,
                            password: formData.password
                        }).then(response => {
                            console.log(response);
                            if (response.data.status.code === 200) {
                                // localStorage.removeItem("platform-security")
                                localStorage.setItem('platform-security', response.data.data)
                                // 删除名为 'platform-security' 的Cookie
                                // Cookies.remove('platform-security');
                                // 设置一个有效期为7天的Cookie
                                Cookies.set('platform-security', response.data.data, { expires: 7 });
                                // 登录成功，跳转到首页或者回调
                                if (isMobile){
                                    router.push('/mobile/listTask')
                                }else {
                                    router.push('/task/project')
                                }
                            } else {
                                messageApi.open({
                                    type: 'error',
                                    content: response.data.status.message,
                                })
                            }
                            ;
                        })
                    } else if (loginType === "email") {
                        httpReq.post(process.env.NEXT_PUBLIC_SECURITY_REQUEST_URL + "/stateless/login/email", {
                            email: formData.email,
                            captcha: formData.captcha
                        }).then(response => {
                            console.log(response);
                            if (response.data.status.code === 200) {
                                // localStorage.removeItem("platform-security")
                                if (response.data.data.length > 1) {
                                    setCaptchaLoginSuccessList(response.data.data)
                                    setOpen(true)
                                } else {
                                    localStorage.setItem('platform-security', response.data.data)
                                    // 删除名为 'platform-security' 的Cookie
                                    // Cookies.remove('platform-security');
                                    // 设置一个有效期为7天的Cookie
                                    Cookies.set('platform-security', response.data.data, { expires: 7 });
                                    // 登录成功，跳转到首页或者回调
                                    if (isMobile){
                                        router.push('/mobile/listTask')
                                    }else {
                                        router.push('/task/project')
                                    }
                                }
                            } else {
                                messageApi.open({
                                    type: 'error',
                                    content: response.data.status.message,
                                })
                            }
                            ;
                        })
                    }

                }}
                // 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={loginType}
                    onChange={(activeKey) => setLoginType(activeKey as LoginType)}
                >
                    <Tabs.TabPane key={'account'} tab={'账号密码登录'}/>
                    <Tabs.TabPane key={'email'} tab={'邮箱登录'}/>
                </Tabs>
                {loginType === 'account' && (
                    <>
                        <ProFormText
                            name="username"
                            fieldProps={{
                                size: 'large',
                                prefix: (
                                    <UserOutlined
                                        style={{
                                            color: token.colorText,
                                        }}
                                        className={'prefixIcon'}
                                    />
                                ),
                            }}
                            placeholder={'用户名: test'}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入用户名!',
                                },
                            ]}
                        />
                        <ProFormText.Password
                            name="password"
                            fieldProps={{
                                size: 'large',
                                prefix: (
                                    <LockOutlined
                                        style={{
                                            color: token.colorText,
                                        }}
                                        className={'prefixIcon'}
                                    />
                                ),
                            }}
                            placeholder={'密码: 123456'}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入密码！',
                                },
                            ]}
                        />
                    </>
                )}
                {loginType === 'email' && (
                    <>
                        <ProFormText
                            fieldProps={{
                                type: "email",
                                size: 'large',
                                prefix: (
                                    <MailOutlined
                                        style={{
                                            color: token.colorText,
                                        }}
                                        className={'prefixIcon'}
                                    />
                                ),
                            }}
                            name="email"
                            placeholder={'邮箱帐号'}
                            rules={[
                                {
                                    required: true,
                                    message: '请输入邮箱帐号！',
                                },
                                {
                                    pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
                                    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 '获取验证码';
                            }}
                            phoneName="email"
                            name="captcha"
                            rules={[
                                {
                                    required: true,
                                    message: '请输入验证码！',
                                },
                            ]}
                            onGetCaptcha={async (email) => {
                                // 请求后端服务器发送密码
                                httpReq.get(process.env.NEXT_PUBLIC_SECURITY_REQUEST_URL + "/common/email/captcha/" + email)
                                    .then(response => {
                                        if (response.data.status.code === 200) {
                                            message.success(`${email},获取验证码成功,请及时查看！`);
                                        } else {
                                            messageApi.open({
                                                type: 'error',
                                                content: response.data.status.message,
                                            })
                                        }
                                    })
                            }}
                        />
                    </>
                )}
                <div
                    style={{
                        marginBlockEnd: 24,
                    }}
                >
                    <ProFormCheckbox noStyle name="autoLogin">
                        自动登录
                    </ProFormCheckbox>
                    <a
                        style={{
                            float: 'right',
                        }}
                    >
                        忘记密码
                    </a>
                </div>
            </LoginFormPage>:<Skeleton />}
        </div>
    );
};