<template>
    <div class="loginExe">
        
        <div class="main" >

            <div class="title" >排水管道智能检测评估</div>

            <div class="left" >
                <div class="title2" >虚拟仿真实验平台</div>
                <div class="title3" >系统登录</div>
                <div class="edit" >
                    <img class="editLeft" src="../assets/exeLogin/user.webp" />
                    <input class="editRight newInput" type="text" placeholder="请输入账号" v-model="form.username" />
                </div>
                <div class="edit" >
                    <img class="editLeft" src="../assets/exeLogin/pwd.webp" />
                    <input class="editRight newInput" type="password" placeholder="请输入密码" v-model="form.password" />
                </div>

                <div class="btnSubmit" >
                    <img class="btnImg" src="../assets/exeLogin/btn.webp" />
                    <div class="btnTxt" @click="loginEvent" >登陆</div>
                    
                </div>

            </div>
            
        </div>
        
    </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, nextTick } from 'vue';
import { ElForm, ElInput, ElNotification } from 'element-plus';
import { loginApi, getCurrentUser } from '@/api/userApi';
import { useUserInfo } from '@/stores/userInfo';
import router from '../router/index';
import { ElMessage } from 'element-plus';

const userInfo = useUserInfo();
const formRef = ref<InstanceType<typeof ElForm>>();
const usernameRef = ref<InstanceType<typeof ElInput>>();
const passwordRef = ref<InstanceType<typeof ElInput>>();

const form = reactive({
    username: '',
    password: '',
});

const rules = reactive({
    username: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'blur',
        },
        {
            validator: (rule: any, val: string, callback: Function) => {
                if (!val) {
                    return callback();
                }
                // if (!/^[a-zA-Z0-9_]{2,15}$/.test(val)) {
                //     return callback(new Error('请输入正确的账户'));
                // }

                if (typeof val != 'string') {
                    return callback(new Error('请输入正确的账户'));
                }
                
                return callback();
            },
            trigger: 'blur',
        },
    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
        },
        {
            validator: (rule: any, val: string, callback: Function) => {
                if (!val) {
                    return callback();
                }
                if (!regularPassword(val)) {
                    return callback(new Error('请输入正确的密码'));
                }
                return callback();
            },
            trigger: 'blur',
        },
    ],
});

const focusInput = () => {
    if (form.username === '') {
        usernameRef.value!.focus();
    } else if (form.password === '') {
        passwordRef.value!.focus();
    }
};

const onSubmit = (formEl: InstanceType<typeof ElForm> | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            loginApi(form).then((res) => {
                if (res.data.data.token) {
                    userInfo.setToken(res.data.data.token, 'auth');
                    const userType = res.data.data.userType;
                    getCurrentUser().then((res) => {
                        userInfo.dataFill(Object.assign({ userType: userType }, res.data.data));

                        // // 老接口的类型 - 学生
                        // if (userType == 0) router.push({ path: '/train' });
                        // // 老接口的类型 - 老师
                        // else if (userType == 1) router.push({ path: '/TaskMng' });

                        // 老师
                        if (userType == 0) router.push({ path: '/TaskMng' });
                        // 学生
                        else if (userType == 1) router.push({ path: '/studentMain' });
                        else {
                            ElNotification({
                                message: '无效用户',
                                type: 'info',
                            });
                        }
                    });
                }
            });
        } else {
            return false;
        }
    });
};

/**
 * 新的登陆逻辑
 */
const loginEvent = () => {
    
    // console.log("新的登陆逻辑 form", form);
    if (form.username == null || form.username == undefined || form.username == '') {
        ElMessage({ message: '账号必须填写', type: 'warning', });
        return;
    }

    if (form.password == null || form.password == undefined || form.password == '') {
        ElMessage({ message: '密码必须填写', type: 'warning', });
        return;
    }

    loginApi(form).then((res) => {
        if (res.data.data.token) {
            userInfo.setToken(res.data.data.token, 'auth');
            const userType = res.data.data.userType;
            getCurrentUser().then((res) => {
                userInfo.dataFill(Object.assign({ userType: userType }, res.data.data));

                // // 老师
                // if (userType == 0) router.push({ path: '/TaskMng' });
                // // 学生
                // else if (userType == 1) router.push({ path: '/studentMain' });
                // else {
                //     ElNotification({
                //         message: '无效用户',
                //         type: 'info',
                //     });
                // }

                mainToMaxEvent(function() {
                    
                    // 老师
                    if (userType == 0) router.push({ path: '/TaskMng' });
                    // 学生
                    else if (userType == 1) router.push({ path: '/studentMain' });
                    else {
                        ElNotification({
                            message: '无效用户',
                            type: 'info',
                        });
                    }

                });

            });
        }
    });
    
}


/**
 * 桌面应用窗口最大化
 * callback
 */
const mainToMaxEvent = (callback : any) => {

    fetch('http://127.0.0.1:' + window["mainToMaxPort"] + '/mainToMax')
    .then(response => {
        if (!response.ok) {
            throw new Error(`请求失败：${response.status} ${response.statusText}`);
        }
        return response.json(); // 若返回文本，用 response.text()
    })
    .then(data => {
        // console.log('获取到的数据：', data);
        // 这里写业务逻辑（如渲染页面）
        callback('yes');
    })
    .catch(error => {
        // console.error('请求出错：', error.message);
        callback('yes');
    });
}


const regularPassword = (val: string) => {
    if (/^[a-zA-Z0-9_@]{6,32}$/.test(val)) return true;
    return false;
};

onMounted(() => {
    nextTick(() => focusInput());
});
</script>
<style lang="scss" scoped>

// $proportion : 0.7;
$proportion : 1;

.newInput {
    /* 移除默认外观 */
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    
    /* 移除边框和轮廓 */
    border: none;
    outline: none;
    
    /* 移除默认内边距 */
    padding: 0;
    
    /* 继承字体样式 */
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
    
    /* 背景透明 */
    background: transparent;
}

.newInput::placeholder {
    color: #49608C;
}

.loginExe {

    box-sizing:border-box;
    -moz-box-sizing:border-box; /* Firefox */
    -webkit-box-sizing:border-box; /* Safari */

    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;

}

.loginExe {

    position: fixed;
    width: 100%;
    height: 100%;
    top: 0px;
    left: 0px;
    background-color: #092661;

    .main {
        position: fixed;
        width: 137.14rem * $proportion;
        height: 81.14rem * $proportion;
        top: 50%;
        left: 50%;
        margin: -40.57rem * $proportion 0px 0px -68.57rem * $proportion;

        background-image: url("../assets/exeLogin/bg.webp");
        -webkit-background-size: 100% 100%;
        -moz-background-size: 100% 100%;
        -o-background-size: 100% 100%;
        background-size: 100% 100%;
        background-position: center center;

        .title {
            position: absolute;
            top: 2.25rem * $proportion;
            left: 0px;
            width: 100%;
            text-align: center;
            font-size: 4rem * $proportion;
            font-weight: 700;
            color: #f0fffe;
        }

        .left {
            position: absolute;
            width: 46;
            top: 15.85rem * $proportion;
            left: 19.85rem * $proportion;

            .title2 {
                width: 100%;
                text-align: center;
                font-weight: 500;
                font-size: 5.35rem * $proportion;
                color: #F0F5FD;
            }

            .title3 {
                width: 100%;
                text-align: center;
                font-weight: 400;
                font-size: 3.57rem * $proportion;
                color: #F0F5FD;
                margin: 2.64rem * $proportion 0px 2.64rem * $proportion 0px;

                /* 设置渐变背景，从左到右 */
                background: linear-gradient(to right, #6A9EFF, #4ecdc4, #7DDBFA);
                
                /* 将背景裁剪到文字区域 */
                -webkit-background-clip: text;
                background-clip: text;
                
                /* 使文字颜色透明，显示背景渐变 */
                -webkit-text-fill-color: transparent;
                text-fill-color: transparent;

            }

            .edit {
                position: relative;
                width: 100%;
                height: 5.71rem * $proportion;
                border: 1px solid #71CBF2;
                margin: 3.92rem * $proportion 0px 3.92rem * $proportion 0px;
                background-color: #ffffff;

                .editLeft, .editRight {
                    position: absolute;
                }

                .editLeft {
                    width: 2.78rem * $proportion;
                    left: 2.14rem * $proportion;
                    top: 1.57rem * $proportion;
                }

                .editRight {
                    left: 6.71rem * $proportion;
                    top: 0px;
                    bottom: 0px;
                    right: 0px;
                    font-weight: 400;
                    font-size: 2.5rem * $proportion;
                    color: #49608C;
                    
                }
                
            }

            .btnSubmit {
                position: relative;
                width: 100%;
                height: 6.21rem * $proportion;
                cursor:pointer;
                
                .btnImg {
                    position: absolute;
                    top: -166%;
                    left: -40%;
                    width: 180%;
                    // 穿透点击
                    pointer-events: none;
                }

                .btnTxt {
                    position: absolute;
                    width: 100%;
                    height: 100%;
                    top: 0px;
                    left: 0px;
                    z-index: 1;

                    text-align: center;
                    font-weight: 500;
                    font-size: 3.14rem * $proportion;
                    color: #FFFFFF;
                    letter-spacing: 7px;
                    text-shadow: 0px 3px 7px rgba(39,63,121,0.25);

                    line-height: 6.21rem * $proportion;
                    
                }

            }
            
        }

    }

}

</style>
