<template>
    <div class="page">
        <img src="@/assets/images/agent/logo3.png" class="logo">
        <div class="login">
            <div class="l_tabs adfac">
                <div class="t_pre" :class="{'active':tidx===1}" @click="handleChangeTab(1)">账号密码登录</div>
                <div class="t_pre" :class="{'active':tidx===2}" @click="handleChangeTab(2)">验证码登录</div>
            </div>
            <div class="l_form">
                <template v-if="tidx===1">
                    <el-form ref="accountRef" :model="accountForm" :rules="accountRules" label-width="0px">
                        <el-form-item label="" prop="username">
                            <el-input v-model="accountForm.username" placeholder="请输入账号" />
                        </el-form-item>
                        <el-form-item label="" prop="password">
                            <el-input show-password v-model="accountForm.password" placeholder="请输入密码" />
                        </el-form-item>
                    </el-form>
                </template>
                <template v-else-if="tidx===2">
                    <el-form ref="codeRef" :model="codeForm" :rules="codeRules" label-width="0px">
                        <el-form-item label="" prop="phone">
                            <el-input type="number" v-model="codeForm.phone" placeholder="请输入手机号码" />
                        </el-form-item>
                        <el-form-item label="" prop="code">
                            <div class="c_pre">
                                <div class="left">
                                    <el-input v-model="codeForm.code" placeholder="请输入验证码"></el-input>
                                </div>
                                <div class="cp_right" @click="handleCode">
                                    <span>{{ codeBtnText }}</span>
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </template>
            </div>
            <div class="l_check">
                <el-checkbox v-model="checked">记住密码</el-checkbox>
            </div>
            <div class="l_btn" :class="{'active':((tidx===1&&accountForm.username&&accountForm.password)||(tidx===2&&codeForm.phone&&codeForm.code))}" @click="handleLogin">立即登录</div>
            <div class="l_check">
                <el-checkbox v-model="agree">已阅读并同意 <span class="lcs">隐私协议</span> 和 <span class="lcs">服务条款</span></el-checkbox>
            </div>
        </div>
    </div>
</template>

<script setup name="">
    var timer = null;
    import Cookies from "js-cookie";
    import { getUUID } from "@/utils";
    import { ref, getCurrentInstance } from 'vue'
    const { proxy } = getCurrentInstance();
    
    const time = ref(60);
    const codeBtn = ref(true);
    const codeBtnText = ref('获取验证码');
    const tidx = ref(1);
    const accountRef = ref(null);
    const codeRef = ref(null);
    const accountForm = ref({
        username: '',
        password: '',
        uuid: getUUID()
    });
    const accountRules = ref({
        username: [
            { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
        ]
    });
    const codeForm = ref({
        phone: '',
        code: ''
    });
    const codeRules = ref({
        phone: [
            { required: true, message: '请输入手机号码', trigger: 'blur' },
            { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        code: [
            { required: true, message: '请输入验证码', trigger: 'blur' }
        ]
    })
    const checked = ref(false);
    const agree = ref(false);

    
    const handleChangeTab = (idx) => {
        tidx.value = idx;
    }

    const handleCode = () => {
        if(!codeBtn.value) return;
        codeBtn.value = false;
        codeBtnText.value = '重新发送('+time.value+'s)';
        timer = setInterval(()=>{
            time.value--;
            if(time.value<=0){
                clearInterval(timer);
                codeBtnText.value = '获取验证码';
                codeBtn.value = true;
                time.value = 60;
            }else{
                codeBtnText.value = '重新发送('+time.value+'s)';
            }
        },1000)
    }

    const handleLogin = () => {
        if(tidx.value===1){
            proxy.$refs.accountRef.validate((valid) => {
                if (valid) {
                    if(!agree.value) return proxy.$message({type: 'warning', message: '请阅读并同意隐私协议和服务条款'})
                    toLogin();
                } else {
                    return false;
                }
            });
        }else if(tidx.value===2){
            proxy.$refs.codeRef.validate((valid) => {
                if (valid) {
                    if(!agree.value) return proxy.$message({type: 'warning', message: '请阅读并同意隐私协议和服务条款'})
                    console.log("验证码登录");
                } else {
                    return false;
                }
            });
        }
    }

    const toLogin = () => {
        proxy.$http.post("/login", accountForm.value).then(({ data: res }) => {
            if (res.code !== 0) return proxy.$message.error(res.msg);
            sessionStorage.removeItem("tags");
            Cookies.set("token", res.data.token);

            if (checked.value) {
                setCookie(accountForm.value.username, accountForm.value.password, 7);
            } else {
                setCookie("", "", -1);
            }

            // 获取菜单列表, 添加并全局变量保存
            proxy.$http.get("/sys/menu/nav", {
                params: {
                    menuClassify: 1
                }
            }).then(({ data: res }) => {
                if (res.code !== 0) proxy.$message.error(res.msg);
                var menuList = res.data;
                for (var i = 0; i < menuList.length; i++) {
                    var menu = {};
                    if (menuList[i].url != "") {
                        menu = menuList[i];
                    } else if (menuList[i].children.length > 0) {
                        menu = menuList[i].children[0];
                    }

                    // 组装路由
                    var route = {
                        path: "",
                        component: null,
                        name: "index",
                        meta: {
                            ...window.SITE_CONFIG["contentTabDefault"],
                            menuId: menu.id,
                            title: menu.name,
                        },
                    };
                    let URL = (menu.url || "").replace(/{{([^}}]+)?}}/g,(s1, s2) => eval(s2));
                    URL = URL.replace(/^\//, "").replace(/_/g, "-");
                    route["path"] = route["name"] = URL.replace(/\//g, "-");
                    route["component"] = () => import(`@/views/modules/${URL}`);
                    // proxy.$router.push(route);
                    proxy.$router.push('home');
                    proxy.$store.state.sidebarMenuActiveName = [];

                    var proute = menuList.filter(
                        (item) =>
                        item.children.filter((child) => child.id == menu.id).length > 0
                    );

                    proxy.$store.state.sidebarMenuActiveName.push(
                        proute.length > 0 ? proute[0].name : ""
                    );
                    proxy.$store.state.sidebarMenuActiveName.push(
                        route.meta.title
                    );
                    break;
                }
                localStorage.setItem("currentMenuIndex", 0);
                proxy.$store.state.currentMenuIndex = 0;
            });
        })
    }

    const setCookie = (name, pwd, exdays) => {
      var exdate = new Date();
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); 
      window.document.cookie =
        "userName" + "=" + name + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "userPwd" + "=" + pwd + ";path=/;expires=" + exdate.toGMTString();
    }
    const getCookie = () => {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); 
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); 
          if (arr2[0] === "userName") {
            accountForm.value.username = arr2[1]; 
          } else if (arr2[0] === "userPwd") {
            accountForm.value.password = arr2[1];
          }
        }
        checked.value = true;
      }
    }
    
    getCookie();
</script>

<style scoped lang="scss">
    .page{
        width: 100%;
        height: 100vh;
        background: url(@/assets/images/agent/login_bg.png) no-repeat;
        background-size: 100% 100%;
        position: relative;

        .logo{
            width: 167px;
            height: 48px;
            position: absolute;
            top: 40px;
            left: 48px;
            z-index: 2;
        }

        .login{
            width: 514px;
            height: 614px;
            background: #FFFFFF;
            border-radius: 16px;
            padding: 64px 48px;
            box-sizing: border-box;
            position: absolute;
            top: 50%;
            margin-top: -307px;
            right: 262px;

            .l_tabs{
                .t_pre{
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 20px;
                    color: #646464;
                    line-height: 28px;
                    padding-bottom: 4px;
                    cursor: pointer;
                    &.active{
                        font-weight: bold;
                        color: #761E6A;
                        position: relative;
                        &::after{
                            content:'';
                            width: 100%;
                            height: 2px;
                            background: #761E6A;
                            position: absolute;
                            left: 0;
                            bottom: 0;
                        }
                    }
                    &:last-child{
                        margin-left: 64px;
                    }
                }
            }

            .l_check{
                margin-top: 48px;
                .lcs{
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 400;
                    font-size: 16px;
                    color: #761E6A;
                    line-height: 22px;
                }
            }

            .l_btn{
                margin-top: 48px;
                height: 60px;
                background: rgba(131, 52, 120, .4);
                border-radius: 6px;
                font-family: PingFang-SC, PingFang-SC;
                font-weight: bold;
                font-size: 20px;
                color: #FFFFFF;
                line-height: 60px;
                text-align: center;
                cursor: pointer;
                letter-spacing: 1px;
                cursor: not-allowed;
                &.active{
                    background: rgba(131, 52, 120, 1);
                    cursor: pointer;
                }
            }

            .c_pre{
                height: 54px;
                background: #FFFFFF;
                border-radius: 6px;
                border: 1px solid #ECEEF5;
                display: flex;
                align-items: center;
                .left{
                    width: 304px;
                }
                .cp_right{
                    width: calc(100% - 304px);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    position: relative;
                    cursor: pointer;
                    &::before{
                        content: '';
                        width: 1px;
                        height: 21px;
                        background: #ECEEF5;
                        position: absolute;
                        top: 50%;
                        margin-top: -10.5px;
                        left: 0;
                    }
                    &>span{
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 400;
                        font-size: 14px;
                        color: #761E6A;
                        line-height: 20px;
                    }
                }
            }
        }
    }

    ::v-deep .el-form-item{
        margin-bottom: 0 !important;
        margin-top: 48px;
    }
    ::v-deep .el-input__inner{
        height: 54px !important;
        line-height: 54px !important;
    }
    ::v-deep .el-checkbox__label{
        font-size: 16px !important;
        color: #393939;
    }
    ::v-deep .c_pre .el-input__inner{
        border: none !important;
        height: 48px !important;
        line-height: 48px !important;
        width: calc(100% - 2px);
        margin-left: 2px;
    }
</style>