<template>
    <section class="h-full flex items-center login-bg">
        <div class="login-container">
            <div class="pig-tit">
                <p>牛只运输跟踪系统</p>
            </div>
            <div class="pig-container">
                <el-form ref="formRef" :model="form" :rules="rules">
                    <div class="con-tab" @click="toggleLoginMode">
                        <span :class="{ cur: form.loginType === 0 }" @click="changeLoginType(0)">用户名密码登录</span>
                        <!-- <em style="font-style: normal;">|</em> -->
                        <span :class="{ cur: form.loginType === 1 }" @click="changeLoginType(1)">手机验证码登录</span>
                        <em :class="{ cur: form.loginType === 1 }"></em>
                    </div>
                    <template v-if="form.loginType === 0">
                        <p class="info-title">手机号</p>
                        <el-form-item prop="mobile">
                            <el-input v-model="form.mobile" class="no-border-input" placeholder="请输入手机号" @keyup.enter="onSubmit" />
                        </el-form-item>
                        <p class="info-title">密码</p>
                        <el-form-item prop="password">
                            <el-input
                                placeholder="请输入密码"
                                v-model="form.password"
                                show-password
                                type="password"
                                @keyup.enter="onSubmit"
                            ></el-input>
                        </el-form-item>
                    </template>
                    <template v-if="form.loginType === 1">
                        <p class="info-title">手机号</p>
                        <el-form-item prop="mobile">
                            <el-input v-model="form.mobile" class="no-border-input" placeholder="请输入手机号" @keyup.enter="onSubmit" />
                        </el-form-item>
                        <p class="info-title">验证码</p>
                        <el-form-item prop="password">
                            <p class="info-yan" v-loading="getSmsCodeLoading" @click="getSmsCode">{{ title }}</p>
                            <el-input v-model="form.password" class="no-border-input info-fa" placeholder="请输入验证码" @keyup.enter="onSubmit">
                            </el-input>
                        </el-form-item>
                    </template>

                    <el-form-item class="login_Submitbtn">
                        <el-button :loading="loading" class="login_btn" type="primary" @click="onSubmit">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </section>
</template>
<script setup>
import { ElMessage } from 'element-plus';
import { reactive, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { login, getSmsCodeByPhone } from '~/api/sys.js';
import { useUserStore } from '~/store/user';
import usePermissionStore from '~/store/permission.js';
import { setToken } from '@/utils/auth';
import { checkMobile } from '@/utils/validateFuns.js';
import { getUserMenu } from '@/api/sys.js';

const router = useRouter();
const route = useRoute();
const userStore = useUserStore();
const title = ref('获取验证码');
const time = ref(0);
const getSmsCodeLoading = ref(false);

const form = reactive({
    mobile: '',
    password: '',
    loginType: 0,
});
const loading = ref(false);
const formRef = ref();
// 表单校验
const rules = {
    mobile: [
        {
            required: true,
            validator: (rule, value, callback) => {
                if (form.loginType === 0) {
                    if (!value) {
                        callback(new Error('登录用户名不能为空'));
                    }
                    callback();
                } else {
                    if (!checkMobile(form.mobile)) {
                        callback(new Error('请输入正确的手机号码'));
                    }
                    callback();
                }
                callback();
            },
            trigger: 'blur',
        },
    ],
    password: [
        {
            required: true,
            validator(rule, value, callback) {
                if (form.loginType === 0) {
                    if (!value) {
                        callback(new Error('登录密码不能为空'));
                    }
                    callback();
                } else {
                    if (!value || value.length !== 6) {
                        callback(new Error('短信验证码输入有误'));
                    }
                    callback();
                }
                callback();
            },
            trigger: 'blur',
        },
    ],
};
const resetForm = () => {
    form.mobile = '';
    form.password = '';
    form.loginType = 0;
    formRef.value.clearValidate();
};
const changeLoginType = (type) => {
    resetForm();
    form.loginType = type;
};

// eslint-disable-next-line consistent-return
const getSmsCode = () => {
    if (getSmsCodeLoading.value) return false;
    if (time.value > 0) return false;
    if (!checkMobile(form.mobile)) {
        ElMessage.error('请输入正确的手机号码');
        formRef.value.clearValidate();
        return false;
    }
    getSmsCodeLoading.value = true;
    title.value = '';
    getSmsCodeByPhone(form.mobile)
        .then(() => {
            title.value = `60s`;
            getSmsCodeLoading.value = false;
            time.value = 59;
            const timer = setInterval(() => {
                if (time.value > 0) {
                    title.value = `${time.value}s`;
                    // eslint-disable-next-line no-plusplus
                    time.value--;
                } else {
                    clearInterval(timer);
                    title.value = '获取验证码';
                }
            }, 1000);
        })
        .catch(() => {
            getSmsCodeLoading.value = false;
            title.value = '获取验证码';
        });
};
const onSubmit = async (val) => {
    formRef.value.validate((valid) => {
        if (valid) {
            loading.value = true;
            const params = { ...form };
            login(params)
                .then((ret) => {
                    // 写入用户登录信息
                    userStore.updateToken(ret.data.token);
                    userStore.updateUserName(ret.data.mobile);
                    userStore.updateLoginUser(ret.data.username);
                    userStore.updateLoginUserType(ret.data.userType);
                    userStore.updateRoleId(ret.data.roleId);
                    userStore.updatePermissions(ret.data.permissions || []);  // 保存权限列表
                    userStore.updateRoles(ret.data.roles || []);              // 保存角色列表
                    setToken(ret.data.token);
                    let redirect = route.query.redirect || '/';
                    if (redirect.indexOf('login') > -1) {
                        redirect = '/';
                    }
                    // router.push({ path: redirect });   此方法弃用，因为企业端和海关端没有相同系统模块，这样会导致页面空白
                    ElMessage.success('登录成功!');
                    // 更新为以下跳转方法 userType=1为监管端，userType=2为企业端，根据不同端来跳转不同页面
                    // if (ret.data.userType == 1) {
                    //     router.push({ path: '/system/post' });
                    // } else {
                    //     router.push({ path: '/personnel/role' });
                    // }
                    loading.value = false;
                    generateRoutes();
                })
                .catch((error) => {
                    loading.value = false;
                });
        }
    });
};
const generateRoutes = async () => {
    try {
        const ret = await getUserMenu();

        // 检查用户权限
        const userStore = useUserStore();
        const isSuperAdmin = userStore.permissions.includes('*:*:*') || userStore.roles.includes('admin');

        // 查找第一个有pageUrl的菜单项（type=1表示菜单）
        const findFirstMenuWithUrl = (menus) => {
            // 按sort排序，确保按顺序查找
            const sortedMenus = menus.sort((a, b) => (a.sort || 0) - (b.sort || 0));
            
            for (const menu of sortedMenus) {
                // 查找type=1（菜单）且有pageUrl的项目
                if (menu.type === 1 && menu.pageUrl) {

                    return menu;
                }
            }
            return null;
        };
        
        const firstMenu = findFirstMenuWithUrl(ret.data);
        
        // 根据用户类型和权限决定跳转页面
        let targetPath = '/';
        
        if (isSuperAdmin) {
            // 超级管理员优先跳转到系统管理页面
            targetPath = '/system/post';

        } else if (firstMenu && firstMenu.pageUrl) {
            // 普通用户跳转到第一个有权限的菜单页面
            targetPath = firstMenu.pageUrl;

        } else {
            // 默认跳转到装车订单页面
            targetPath = '/shipping/loadingOrder';

        }
        
        // 等待路由完全生成后再执行跳转
        await nextTick();
        
        // 确保权限store的路由生成完成
        const permissionStore = usePermissionStore();
        if (!permissionStore.routeFlag) {

            await permissionStore.generateRoutes();
        }
        
        // 确保路径以斜杠开头
        if (!targetPath.startsWith('/')) {
            targetPath = '/' + targetPath;
        }
        
        // 使用replace而不是push，避免路由警告
        try {
            await router.replace({ path: targetPath });

        } catch (error) {
            console.warn('Failed to navigate to', targetPath, 'error:', error);
            // 如果跳转失败，尝试跳转到首页
            try {
                await router.replace({ path: '/' });

            } catch (homeError) {
                console.error('Failed to navigate to home:', homeError);
            }
        }
        
    } catch (error) {
        console.error('Failed to get user menu:', error);
        // 获取菜单失败时跳转到首页
        try {
            await router.push({ path: '/' });

        } catch (navError) {
            console.error('Failed to navigate to home:', navError);
        }
    }
};
</script>
<style scoped lang="scss">
.login-bg {
    background: url(../assets/login-bg.png) center no-repeat;
    background-size: cover;
    height: 100vh;
    width: 100%;
    position: relative;
}
.login-container {
    position: absolute;
    top: 50%;
    transform: translate(0%, -50%);
    right: 15%;
    width: 550px;
    // height: 400px;
}

.pig-container {
    padding: 40px 56px 40px;
    border-radius: 9px;
    background-color: rgb(255, 255, 255);
    opacity: 0.98;
    box-shadow: 0px 8px 24px 0px rgba(104, 114, 124, 0.35);
}
.pig-tit {
    font-weight: bolder;
    font-size: 45px;
    text-align: center;
    color: #3b74ff;
    margin-bottom: 30px;
}
.con-tab {
    // font-weight: 600;
    font-size: 24px;
    color: #999;
    line-height: 20px;
    padding: 10px 0;
    margin-bottom: 40px;
    span {
        display: inline-block;
        cursor: pointer;
        &:first-child {
            padding-right: 20px;
            margin-right: 20px;
            // border-right: #ccc 2px solid;
        }
    }
    span.cur {
        color: #000;
    }

    .info {
        font-weight: 300;
        font-size: 25px;
        margin-top: 20px;
    }
}
.info-title {
    font-size: 18px;
    color: #000;
    line-height: 28px;
    margin-bottom: 4px;
}

.login-container .el-input {
    width: 500px;
    height: 60px;
    line-height: 60px;
    border-radius: 12px;
    margin-bottom: 8px;
}

.info-fa {
    position: relative;
}
.info-yan {
    position: absolute;
    z-index: 9;
    top: 9px;
    right: 10px;
    width: 120px;
    height: 42px;
    text-align: center;
    background: #3b74ff;
    border: 1px solid #dbf1ec;
    border-radius: 11px;
    font-size: 16px;
    color: #fff;
    cursor: pointer;
}
.login_Submitbtn {
    margin-top: 36px;
}

.login-container .login_btn {
    width: 500px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    font-size: 18px;
    color: #fff;
    border-radius: 5px;
    background: #3b74ff;
}
:deep(.el-input .el-input__icon) {
    color: #fff;
}
</style>
