<template>
    <div class="login-wrapper">
        <ele-card shadow="always" class="login-card">
            <div class="login-cover">
                <img
                    :src="logoCover"
                    class="login-cover-img"
                    alt="cover"
                    style="width: 100px; height: 100px"
                />
                <div class="login-cover-right" style="margin-top: 10px">
                    <h1 class="login-title">书嗨</h1>
                    <h4 class="login-subtitle">不辜负每一个爱书的人</h4>
                </div>
            </div>
            <div class="login-body">
                <ele-text
                    type="heading"
                    style="font-size: 24px; margin-bottom: 18px"
                >
                    用户登录
                </ele-text>
                <ele-segmented
                    v-model="tabActive"
                    :items="[
                        { label: '密码登录', value: 1 },
                        { label: '扫码登录', value: 2 }
                    ]"
                    style="margin-bottom: 18px"
                    @change="handleTabChange"
                />
                <el-form
                    v-if="tabActive == 1"
                    ref="formRef"
                    size="large"
                    :model="form"
                    :rules="rules"
                    @keyup.enter="submit"
                    @submit.prevent=""
                >
                    <el-form-item prop="username">
                        <el-input
                            clearable
                            v-model="form.username"
                            placeholder="请输入登录账号"
                            :prefix-icon="UserOutlined"
                        />
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input
                            show-password
                            v-model="form.password"
                            placeholder="请输入登录密码"
                            :prefix-icon="LockOutlined"
                        />
                    </el-form-item>
                    <el-form-item prop="code">
                        <div class="login-captcha-group">
                            <el-input
                                clearable
                                v-model="form.code"
                                placeholder="请输入验证码"
                                :prefix-icon="ProtectOutlined"
                            />
                            <div class="login-captcha" @click="changeCaptcha">
                                <img
                                    v-if="captcha"
                                    :src="captcha"
                                    :style="captchaStyle"
                                />
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="phoneCode">
                        <div class="login-captcha-group">
                            <el-input
                                clearable
                                v-model="form.phoneCode"
                                placeholder="手机号验证码"
                                :prefix-icon="ProtectOutlined"
                            />
                            <div
                                class="login-captcha"
                                @click="handleSendMobileCode"
                                style="text-align: center; cursor: pointer"
                            >
                                <span v-if="countdown > 0"
                                    >{{ countdown }}s</span
                                >
                                <span v-else>发送验证码</span>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-checkbox v-model="form.remember"
                            >记住密码</el-checkbox
                        >
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            size="large"
                            type="primary"
                            :loading="loading"
                            style="width: 100%"
                            @click="submit"
                        >
                            登录
                        </el-button>
                    </el-form-item>
                </el-form>
                <div v-else class="login-qrcode-group">
                    <ele-qr-code-svg
                        :size="180"
                        :margin="2"
                        :value="qrcode"
                        class="login-qrcode"
                    />
                    <el-link
                        type="primary"
                        :underline="false"
                        style="margin-top: 16px; user-select: none"
                        @click="refreshQrCode"
                    >
                        <el-icon
                            :size="15"
                            style="
                                transform: translateY(-1px);
                                margin-right: 6px;
                            "
                        >
                            <ReloadOutlined />
                        </el-icon>
                        <span>刷新二维码</span>
                    </el-link>
                </div>
            </div>
        </ele-card>
    </div>
</template>

<script setup>
    import { ref, reactive, unref } from 'vue';
    import { useRouter } from 'vue-router';
    import { EleMessage } from 'ele-admin-plus/es';
    import {
        UserOutlined,
        LockOutlined,
        ProtectOutlined,
        ReloadOutlined
    } from '@/components/icons';
    import { getToken } from '@/utils/token-util';
    import { usePageTab } from '@/utils/use-page-tab';
    import { login, getCaptcha, sendMobileCode } from '@/api/login';
    import logoCover from '@/assets/logo-cover.png';

    const { currentRoute } = useRouter();
    const { goHomeRoute, cleanPageTabs } = usePageTab();

    /** 页签选中 */
    const tabActive = ref(1);

    /** 表单 */
    const formRef = ref(null);

    /** 加载状态 */
    const loading = ref(false);

    /** 手机验证码倒计时 */
    const countdown = ref(0);
    const countdownTimer = ref(null);

    /** 表单数据 */
    const form = reactive({
        username: '',
        password: '',
        code: '',
        uuid: '',
        remember: true,
        phoneCode: ''
    });

    /** 表单验证规则 */
    const rules = reactive({
        username: [
            {
                required: true,
                message: '请输入登录账号',
                type: 'string',
                trigger: 'blur'
            }
        ],
        password: [
            {
                required: true,
                message: '请输入登录密码',
                type: 'string',
                trigger: 'blur'
            }
        ],
        code: [
            {
                required: true,
                message: '请输入验证码',
                type: 'string',
                trigger: 'blur'
            }
        ],
        phoneCode: [
            {
                required: true,
                message: '请输入手机号验证码',
                type: 'string',
                trigger: 'blur'
            }
        ]
    });

    /** 图形验证码 */
    const captcha = ref('');

    /** 图形验证码样式 */
    const captchaStyle = ref({});

    /** 二维码 */
    const qrcode = ref('');

    /** 提交 */
    const submit = () => {
        formRef.value?.validate?.((valid) => {
            if (!valid) {
                return;
            }
            loading.value = true;
            login(form)
                .then((msg) => {
                    EleMessage.success(msg);
                    cleanPageTabs();
                    goHome();
                })
                .catch((e) => {
                    loading.value = false;
                    EleMessage.error(e.message);
                    changeCaptcha();
                });
        });
    };

    /** 获取图形验证码 */
    const changeCaptcha = () => {
        getCaptcha()
            .then((data) => {
                captcha.value = `data:image/gif;base64,${data.img}`;
                captchaStyle.value = {
                    transform: `scaleX(1.${Math.floor(Math.random() * (0 - 5) + 5)}) skewX(-${Math.floor(Math.random() * (0 - 30) + 30)}deg)`,
                    filter: `contrast(200%) hue-rotate(${Math.floor(Math.random() * (0 - 360) + 360)}deg)`
                };
                form.uuid = data.uuid;
                formRef.value?.clearValidate?.();
            })
            .catch((e) => {
                EleMessage.error(e.message);
            });
    };

    /** 刷新二维码 */
    const refreshQrCode = () => {
        qrcode.value = `https://api.eleadmin.com/v2/auth/login?code=${Date.now()}`;
    };

    /** 发送手机验证码 */
    const handleSendMobileCode = async () => {
        if (countdown.value > 0) {
            return;
        }

        try {
            await sendMobileCode({
                username: form.username,
                password: form.password
            });
            EleMessage.success('验证码发送成功');

            // 开始60秒倒计时
            countdown.value = 60;
            countdownTimer.value = setInterval(() => {
                countdown.value--;
                if (countdown.value <= 0) {
                    clearInterval(countdownTimer.value);
                    countdownTimer.value = null;
                }
            }, 1000);
        } catch (e) {
            EleMessage.error(e.message);
        }
    };

    /** 选项卡切换事件 */
    const handleTabChange = (active) => {
        if (active === 2) {
            refreshQrCode();
        }
    };

    /** 跳转到首页 */
    const goHome = () => {
        const { query } = unref(currentRoute);
        goHomeRoute(query.from);
    };

    // 如果已登录直接进入首页
    if (getToken()) {
        goHome();
    } else {
        changeCaptcha();
    }
</script>

<style lang="scss" scoped>
    .login-wrapper {
        min-height: 100vh;
        min-height: 100dvh;
        box-sizing: border-box;
        padding: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-image: url('@/assets/login-bg.png');
        background-repeat: no-repeat;
        background-size: 100% 100%;

        .login-card {
            width: 920px;
            max-width: 100%;
            overflow: hidden;

            :deep(.ele-card-body) {
                display: flex;
                padding: 0;
                height: 520px;
            }
        }
    }

    .login-cover {
        flex: 1;
        padding: 32px 8px;
        box-sizing: border-box;
        background-color: #1681fd;
        background-image: url('@/assets/login-img.png');
        background-repeat: no-repeat;
        background-position: bottom;
        background-size: contain;
        display: flex;
        justify-content: center;
        padding-top: 20px;
    }

    .login-body {
        width: 400px;
        flex-shrink: 0;
        padding: 32px 48px 0 48px;
        box-sizing: border-box;

        :deep(.el-checkbox) {
            height: auto;

            .el-checkbox__label {
                color: inherit;
            }
        }

        :deep(.el-input__prefix-inner > .el-icon) {
            margin-right: 12px;
            transform: scale(1.16);
        }
    }

    /* 验证码 */
    .login-captcha-group {
        width: 100%;
        display: flex;
        align-items: center;

        :deep(.el-input) {
            flex: 1;
        }

        .login-captcha {
            flex-shrink: 0;
            width: 108px;
            height: 40px;
            margin-left: 8px;
            border-radius: var(--el-border-radius-base);
            border: 1px solid var(--el-border-color);
            transition: border 0.2s;
            box-sizing: border-box;
            background: #fff;
            overflow: hidden;
            cursor: pointer;

            img {
                width: calc(100% + 4px);
                height: calc(100% + 4px);
                margin: -2px 0 0 -2px;
                display: block;
            }

            &:hover {
                border-color: var(--el-color-primary);
            }
        }
    }

    /* 标题 */
    .login-title {
        color: rgba(255, 255, 255, 0.98);
        font-size: 28px;
        margin: 0 0 6px 0;
        font-weight: normal;
        letter-spacing: 1.2px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto,
            'Helvetica Neue', Arial, 'Noto Sans', sans-serif,
            'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol',
            'Noto Color Emoji';
    }

    .login-subtitle {
        color: rgba(255, 255, 255, 0.8);
        font-size: 16px;
        margin: 0;
        font-weight: normal;
        letter-spacing: 4px;
    }

    /* 二维码 */
    .login-qrcode-group {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 24px 0;
    }

    .login-qrcode {
        font-size: 0;
        display: inline-block;
        border: 1px solid #ddd;
        border-radius: var(--el-border-radius-base);
        overflow: hidden;
    }

    /* 小屏幕适应 */
    @media screen and (max-width: 680px) {
        .login-wrapper {
            padding: 0;
            display: block;
            background: #fff;

            .login-card {
                width: 100%;
                background: none;
                box-shadow: none;
                border-radius: 0;

                :deep(.ele-card-body) {
                    display: block;
                    height: auto;
                }
            }
        }

        .login-cover {
            padding: 20px 12px 100px 12px;
            background-size: auto 100px;
        }

        .login-body {
            width: 100%;
        }
    }
</style>

<style lang="scss">
    html.dark .login-wrapper {
        background: #000;
    }
</style>
