<!--
 * @Author: Kane
 * @Date: 2023-02-28 00:57:21
 * @LastEditors: Kane
 * @FilePath: /task_schedule/src/views/Login.vue
 * @Description:
 * 登录页面，路由默认指向这个页面
 * 1、判断url中的参数，取得用户信息，根据用户的部门改变路由
 *
 * Copyright (c) ${2022} by Kane, All Rights Reserved.
-->
<template>
    <div class="page-wrapper">
        <div class="login-wrapper">
            <h1>登&nbsp;录</h1>
            <ul class="menu-tab">
                <li
                    v-for="item in ui.tabMenu"
                    :key="item.type"
                    :class="{ 'current': ui.currentMenu === item.type }"
                    @click="onToggleMenu(item.type)"
                >
                    {{ item.label }}
                </li>
            </ul>
            <el-form ref="loginForm">
                <el-form-item>
                    <label class="form-label">用户名</label>
                    <el-input
                        v-if="ui.currentMenu === ui.tabMenu[0].type"
                        v-model.trim.lazy="ui.account"
                        type="text"
                        placeholder="请输入P13账号或P09工号"
                    />
                    <el-input
                        v-else
                        v-model.trim.lazy="ui.account"
                        type="text"
                        placeholder="请输入坐席工号"
                    />
                </el-form-item>
                <el-form-item v-show="ui.currentMenu === ui.tabMenu[0].type">
                    <label class="form-label">密码</label>
                    <el-input
                        v-model.trim.lazy="ui.password"
                        type="password"
                        placeholder="请输入P13密码"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="primary"
                        class="el-button-block"
                        @click="onLogin"
                    >
                        登录
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <!-- <div>
            <span>{{ ui.tips }}</span>
        </div> -->
    </div>
</template>

<script lang="ts">
import { reactive, onBeforeMount } from "vue";
import { useRouter } from "vue-router";
import { saveStaffInfo, getUserType, saveUserType, getCallerInfo, saveCallerInfo } from "@/utils/api/localStorage";
import { login, loginCaller, type LoginCallerInfo, type LoginCallerResult } from "@/utils/account";
import { ElMessage } from "element-plus";
import { StaffInfo } from "@/types/cpicxim/StaffInfo";
import { type TelSaler } from "@/types/cpicxim/TelSaler";

export default {
    name: "LoginPage",
    setup()
    {
        const router = useRouter();

        const ui = reactive({
            account: "",
            password: "",
            tips: "",
            showNeedAccountTip: false,
            showAccountErrorTip: false,
            tabMenu: [
                { type: "cpicxim_staff", label: "内勤", },
                { type: "tele_saler", label: "坐席", },
            ],
            currentMenu: "",
        });

        /**
         * 保存p13账号
         */
        const savedP13uid = (): void =>
        {
            window.localStorage.setItem( "stuff_account", ui.account );
        };

        /**
         * 登录函数，根据ui.currentMenu判断登录的是坐席还是员工。
         */
        const onLogin = (): void =>
        {
            // 保存用户类型
            saveUserType( ui.currentMenu );

            // 判断是坐席还是内勤
            if ( ui.currentMenu === "cpicxim_staff" )
            {
                // 是内勤员工
                const info = {
                    p13account: ui.account,
                    password: ui.password,
                };

                login( info )
                    // 调用成功
                    .then(( response ) =>
                    {
                        const data = response.data ?? { success: false, };

                        if ( data.success === true )
                        {
                            // 提示登录成功，并保存到localStorage，然后路由跳转
                            ElMessage({
                                message: data.message,
                                type: "success",
                                center: true,
                            });

                            const staffInfo = new StaffInfo(
                                data.staff_info.p13uid ?? "",
                                data.staff_info.code ?? "",
                                data.staff_info.name ?? "",
                                data.staff_info.department_code ?? "",
                                data.staff_info.department_name ?? "",
                                data.staff_info.section_office_code ?? "",
                                data.staff_info.p13section_office_nameuid ?? ""
                            );

                            saveStaffInfo( staffInfo );

                            // 跳转路由
                            router.push( "/desktop" ).then(() => {}).catch(() => {});
                        }
                        else
                        {
                            ElMessage({
                                message: data.message,
                                type: "error",
                                center: true,
                            });
                        }

                        console.log( data );
                    })
                    // 调用失败
                    .catch(( error ) =>
                    {
                        // debugger;
                        console.log( `登录失败，返回信息：${error}` );
                    });
            }
            else if ( ui.currentMenu === "tele_saler" )
            {
                // 是坐席
                const loginInfo: LoginCallerInfo = {
                    telsaler: ui.account,
                };

                // 登录
                loginCaller( loginInfo )
                    // 调用接口成功
                    .then(( response ) =>
                    {
                        const data: LoginCallerResult = response.data ?? { success: false, };

                        // debugger;

                        // 查看標志位
                        if ( data.success )
                        {
                            // 查询成功，显示一个提示，保存工号，并跳转路由
                            ElMessage({
                                message: `验证成功，登录用户 ${data.tel_saler_name}`,
                                type: "success",
                            });

                            const telsaler: TelSaler = {
                                telSalerCode: data.tel_saler_code,
                                telSalerName: data.tel_saler_name,
                                teamCode: data.team_code,
                                teamName: data.team_name,
                                departmentCode: data.department_code,
                                departmentName: data.department_name,
                            };

                            saveCallerInfo( telsaler );

                            router.push( "/desktop_archievement" ).then(() => {}).catch(() => {});
                        }
                        else
                        {
                            // 查詢失敗
                            ElMessage({
                                message: "验证失败，请检查输入的工号。",
                                type: "error",
                            });
                        }
                    })
                    // 调用接口失败
                    .catch(( error ) =>
                    {
                        const message = `登录失败，返回信息：${error}`;

                        console.log( message );

                        ElMessage({
                            message,
                            type: "error",
                        });
                    });
            }
        };

        onBeforeMount(() =>
        {
            // 判断已登录的信息是坐席还是内勤
            // 坐席就直接跳转桌面霸屏
            // 员工就暂且什么都不做
            const staffType = getUserType();

            if ( staffType === "tele_saler" )
            {
                // 是坐席，尝试获取存储的坐席工号
                const callInfo = getCallerInfo();

                // 判断是否已经记录了坐席工号，有则提示已登录，然后跳转路由
                if ( callInfo.telSalerCode.length !== 0 )
                {
                    ElMessage({
                        message: `已登录账号:${callInfo.telSalerName}`,
                        type: "success",
                        center: true,
                    });

                    // 跳转路由
                    router.push( "/desktop_archievement" ).then(() => {}).catch(() => {});
                }
            }
            else if ( staffType === "cpicxim_staff" )
            {
                // 是员工，暂且不管；
            }
        });

        const onToggleMenu = ( type: string ): void =>
        {
            ui.currentMenu = type;
        };

        // 初始化界面
        ui.currentMenu = ui.tabMenu[1].type;

        return { ui, savedP13uid, onLogin, onToggleMenu, };
    },
};
</script>

<style scoped lang="scss">
.page-wrapper {
    box-sizing: border-box;
    // height: calc(100vh - 10mm);
    // width: calc(100vw - 10mm);
    height: 100vh;
    width: 100vw;
    // border: 1px solid red;
    display: flex;
    flex-direction: column;
    justify-content: start;
    align-items: center;

    background-image: url("@/assets/img/bg/bg_01.jpg");
    background-attachment: fixed;
    background-size: contain;

    span {
        font-size: 30px;
        color: red;
    }
}

.login-wrapper {
    box-sizing: border-box;
    width: 320px;
    // margin-top: 5cm auto auto auto;
    margin-top: calc(100vh * 0.075);
    padding: 10mm;
    background-color: #cac2c27f;
    backdrop-filter: blur(10px);
    border-radius: 5px;
    // backdrop-filter: ;

    h1 {
        font-family: "FZ-ZHUOHEI";
        font-size: 70px;
        font-weight: 100;
        color: #fff;
        margin: 5mm 0;
        display: block;
        text-align: center;
        text-shadow: #1d6ddc 2px 10px 2px,
            #1d6ddc 2px 0px 2px,
            #1d6ddc -2px -0px 2px,
            #1d6ddc -0px -2px 2px,
            #1d6ddc -1.4px -1.4px 2px,
            #1d6ddc 1.4px 1.4px 2px,
            #1d6ddc 1.4px -1.4px 2px,
            #1d6ddc -1.4px 1.4px 2px;

    }
}

.menu-tab {
    text-align: center;
    margin-bottom: 15px;
    margin-top: 25px;

    li {
        display: inline-block;
        padding: 10px 24px;
        margin: 0 10px;
        // background-color: #fff;
        color: #1d6ddc;
        font-size: 16px;
        border-radius: 5px;
        cursor: pointer;

        &.current {
            background-color: #1d6ddc;
            color: #fff;
        }
    }
}

.form-label {
    display: block;
    /* color: #fff; */
    color: #344a5fef;
    font-size: 14px;
    // border: 1px solid red;
}

.el-input {
    color: #344a5fef;
}

.el-button-block {
    width: 100%;
    margin-top: 20px;
}
</style>
