<template>
    <div class="wrap">
        <div class="main">
            <div class="box">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                    <el-tab-pane label="账号登录" name="1"></el-tab-pane>
                    <el-tab-pane label="手机号/邮箱登录" name="2"></el-tab-pane>
                    <el-form :model="loginForm" :rules="loginRules" ref="loginForm" style="margin-top: 20px">
                        <el-form-item v-if="activeName === '1'" prop="account">
                            <el-input v-model.trim="loginForm.account" placeholder="请输入账号"></el-input>
                        </el-form-item>
                        <el-form-item v-if="activeName === '2'" prop="account">
                            <el-input v-model.trim="loginForm.account" placeholder="请输入手机号/邮箱"></el-input>
                        </el-form-item>
                        <el-form-item prop="password">
                            <el-input
                                type="password"
                                placeholder="请输入密码"
                                v-model.trim="loginForm.password"
                            >
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="code">
                            <el-input
                                placeholder="请输入验证码"
                                v-model.trim="loginForm.code"
                                @keyup.enter.native="submitFormLogin"
                            >
                            </el-input>
                            <img @click="getVerImg" :src="verificationIMG" class="verification" alt="">
                        </el-form-item>
                        <el-button class="submit" type="primary" @click="submitFormLogin">马上登录</el-button>
                    </el-form>
                </el-tabs>
            </div>
        </div>

        <el-dialog title="绑定手机号" :visible.sync="phoneVisible" :close-on-click-modal="false" width="30%">
            <div style='padding: 0 13px 20px 13px;'>
                依据国家政策法规，需绑定手机号进行实网络实名才可登录使用本平台
            </div>
            <el-form ref="form" label-width="60px">
                <el-form-item label="手机号">
                    <el-input style="width: 100%;" placeholder="请输入手机号" v-model="phone" maxlength="11"></el-input>
                </el-form-item>
                <el-form-item label="验证码">
                    <div style="display: flex;">
                        <el-input v-model="phoneCode" placeholder="请输入验证码" maxlength="6"></el-input>
                        <el-button style="margin-left: 10px" type="text" @click="sendPhoneCode"
                                   :disabled="phoneDisabled">{{ phoneBtnText }}
                        </el-button>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="phoneVisible = false">取 消</el-button>
                <el-button type="primary" @click="phoneSubmit">确 定</el-button>
            </span>
        </el-dialog>
        <v-footer class="footer"></v-footer>
    </div>
</template>

<script>
import { mapActions } from "vuex";
import vFooter from "@/layouts/footer";
import util from "@/libs/util";
import Setting from "@/setting";

export default {
    data: function() {
        return {
            activeName: "1",
            loginForm: {
                account: "",
                password: "",
                code: "", // 验证码
                random: "", // 随机数
                distinguish: 1, // 区分手机号账号登录,1为账号登录,2为手机号或邮箱登录
                type: 0, // 平台端区分：0->教师端 1->学生端 2->无端
                platform: Setting.platformId
            },
            loginRules: {
                account: [{ required: true, message: "请输入账号", trigger: "blur" }],
                password: [{ required: true, message: "请输入密码", trigger: "blur" }],
                code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
            },
            verificationIMG: "",
            phoneVisible: false, // 绑定手机号对话框
            phone: "",
            phoneCode: "",
            phoneDisabled: false,
            phoneTimer: null,
            phoneBtnText: "发送验证码"
        };
    },
    components: {
        vFooter
    },
    created() {
        this.getVerImg();
    },
    mounted() {
        // 页面离开的时候销毁手机和邮箱验证码定时器
        this.$once("hook:beforeDestroy", function() {
            clearInterval(this.phoneTimer);
            this.phoneTimer = null;
        });
    },
    methods: {
        ...mapActions("user", [
            "setCustomer", "setCustomerName"
        ]),
        getVerImg() { // 获取验证码图片
            this.loginForm.random = Math.floor(Math.random() * 999999999);
            this.verificationIMG = this.api.verification + "?random=" + `${this.loginForm.random}`;
        },
        handleClick(tab, event) { // 切换标签
            this.loginForm.account = "";
            this.$refs.loginForm.clearValidate();
            this.loginRules.account[0].message = tab.index === "1" ? "请输入账号" : "请输入手机号/邮箱";
        },
        submitFormLogin() { // 提交登录
            this.$refs.loginForm.validate(valid => {
                if (valid) {
                    this.loginForm.distinguish = Number(this.activeName);
                    this.$post(this.api.logins, this.loginForm).then(res => {
                        if (res && res.status == 30001) {
                            this.phoneVisible = true;
                        }
                        this.getVerImg();
                        this.loginForm.code = "";
                        util.local.set(Setting.tokenKey, res.data.token, Setting.tokenExpires);
                        this.queryCustomer();
                    }).catch(res => {

                    });
                } else {
                    return util.errorMsg("请检查表单数据");
                }
            });
        },
        queryCustomer() { // 查询是否是客户
            this.$get(this.api.isClient).then(res => {
                util.successMsg("登录成功");
                this.setCustomer(res.customer);
                this.setCustomerName(res.customerName);
                let redirect = this.$route.query.redirect ? decodeURIComponent(this.$route.query.redirect) : "/index";
                this.$router.replace(redirect);
            }).catch(res => {});
        },
        phoneCountdown() {
            let count = 60;
            if (!this.phoneTimer) {
                this.phoneDisabled = true;
                this.phoneTimer = setInterval(() => {
                    console.log("倒计时中");
                    if (count > 0) {
                        count--;
                        this.phoneBtnText = `${count}秒后重试`;
                    } else {
                        this.phoneDisabled = false;
                        clearInterval(this.phoneTimer);
                        this.phoneTimer = null;
                        this.phoneBtnText = `发送验证码`;
                    }
                }, 1000);
            }
        },
        sendPhoneCode() {
            if (!this.phone) return util.warningMsg("请输入手机号");
            if (!/^1[3456789]\d{9}$/.test(this.phone)) return util.warningMsg("请输入正确的手机号");
            let data = {
                platform: Setting.platformId,
                phone: this.phone,
                types: 2
            };
            this.$post(this.api.sendPhoneOrEmailCode, data).then(res => {
                if (res.message.opener) {
                    this.phoneCountdown();
                    this.phoneOpener = res.message.opener;
                } else {
                    util.errorMsg(res.message);
                }
            }).catch(res => {});
        },
        phoneSubmit() {
            if (!this.phone) return util.warningMsg("请输入手机号");
            if (!/^1[3456789]\d{9}$/.test(this.phone)) return util.warningMsg("请输入正确的手机号");
            if (!this.phoneCode) return util.warningMsg("请输入验证码");
            let data = {
                phone: this.phone,
                types: 2,
                code: this.phoneCode,
                opener: this.phoneOpener,
                platform: Setting.platformId,
                account: this.loginForm.account
            };
            this.$post(this.api.bindPhoneOrEmail, data).then(res => {
                util.successMsg("绑定成功");
                this.loginForm.phone = this.phone;
                this.phoneVisible = false;

                util.local.set(Setting.tokenKey, res.token, Setting.tokenExpires);
                let redirect = this.$route.query.redirect ? decodeURIComponent(this.$route.query.redirect) : "/index";
                this.$router.replace(redirect);
                util.successMsg("登录成功");
                this.queryCustomer();
            }).catch(res => {
            });
        }
    }
};
</script>

<style lang="scss" scoped>
.wrap {
    position: relative;
    width: 100%;
    height: 100%;
    background-image: url(../../../assets/img/login-bg.png);
    background-size: 100%;

    .header {
        width: 100%;
        height: 60px;
        position: absolute;
        top: 0;
        left: 0;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 18px;

        .logo {
            width: 150px;
            margin-left: 20px;

            &.hh {
                width: 220px;
            }
        }
    }

    /deep/ .main {
        position: absolute;
        left: 50%;
        top: 42px;
        transform: translate(-50%, 0);
        width: 1200px;
        height: 82%;
        margin-top: 60px;
        background-image: url(../../../assets/img/login-input.png);
        box-shadow: 0px 0px 79px 0px rgba(11, 15, 65, 0.36);
        overflow: hidden;

        .box {
            width: 548px;
            position: absolute;
            left: 50%;
            top: 50px;
            transform: translate(-50%, 0);

            .el-tabs__nav-scroll {
                display: flex;
                justify-content: center;
            }

            .el-tabs__nav-wrap::after {
                background-color: #fff;
                opacity: 0;

                .el-tabs__active-bar {
                    background-color: #000;
                    border-radius: 2px;
                }

                .el-tabs__item {
                    padding: 0 90px;
                    color: #999;

                    &:hover {
                        color: #000;
                    }

                    &.is-active {
                        color: #333;
                        font-weight: bold;
                    }
                }
            }

            .el-input__inner {
                height: 80px;
                line-height: 80px;
                border: 1px solid rgba(220, 220, 220, 1);
                border-radius: 2px;
            }

            .verification {
                position: absolute;
                top: 1px;
                right: 1px;
                width: 160px;
                height: 78px;
                cursor: pointer;
            }

            .submit {
                width: 100%;
                height: 88px;
                margin-bottom: 50px;
                font-weight: bold;
                background: linear-gradient(90deg, rgba(94, 206, 253, 1), rgba(91, 67, 231, 1));
                box-shadow: 0px 7px 27px 0px rgba(50, 129, 255, 0.51);
                border-radius: 10px;
            }
        }
    }

    .footer {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
    }
}
</style>