<template>
    <div class="wrap">
        <div class="header" v-if="!isHh">
            <img class="logo" src="@/assets/img/logo.png" />
        </div>

        <div class="bg">
            <div class="left">
                <div class="text" v-if="isHh">
                    <p>欢迎使用</p>
                    <p style="margin-bottom: 15px">商学院金融工程</p>
                    <p>与大数据实验平台</p>
                </div>
                <div class="text" v-else>
                    <p>欢迎使用</p>
                    <p>Occupation Lab</p>
                </div>
            </div>
            <div class="right"></div>
        </div>

        <div class="right-form">
            <img v-if="isHh" class="logo" src="@/assets/img/logo-hh1.png" />

            <div class="form">
                <div class="back" v-show="isReg" @click="toReg(false)">
                    <i class="el-icon-back"></i>
                </div>
                <div v-if="!isReg">
                    <el-tabs v-model="activeName">
                        <el-tab-pane label="账号登录" name="1">
                            <el-form v-if="activeName === '1'" :model="loginForm" :rules="loginRules" ref="loginForm" style="margin-top: 20px">
                                <el-form-item label="用户名" prop="username">
                                    <el-input v-model.trim="loginForm.account" placeholder="请输入账号"></el-input>
                                </el-form-item>
                                <el-form-item label="密码" prop="password">
                                    <el-input
                                        type="password"
                                        placeholder="请输入密码"
                                        v-model.trim="loginForm.password"
                                    >
                                    </el-input>
                                </el-form-item>
                                <el-form-item label="验证码" prop="code">
                                    <el-input
                                        placeholder="请输入验证码"
                                        v-model.trim="loginForm.code"
                                        @keyup.enter.native="submitFormLogin('loginForm')"
                                    >
                                    </el-input>
                                    <img @click="blur" :src="verificationIMG" class="verification" alt="">
                                </el-form-item>
                                <el-button class="submit" type="primary" @click="submitFormLogin('loginForm')">登录</el-button>
                            </el-form>
                        </el-tab-pane>

                        <el-tab-pane label="手机号/邮箱登录" name="2">
                            <el-form v-if="activeName === '2'" :model="phoneParam" :rules="phoneRules" ref="phoneParam" style="margin-top: 20px">
                                <el-form-item label="手机号/邮箱" prop="userphone">
                                    <el-input v-model="phoneParam.userphone" placeholder="请输入手机号/邮箱"></el-input>
                                </el-form-item>
                                <el-form-item label="密码" prop="phonePassword">
                                    <el-input
                                        type="password"
                                        placeholder="请输入密码"
                                        v-model="phoneParam.phonePassword"
                                        @keyup.enter.native="getSchool('phoneParam')"
                                    >
                                    </el-input>
                                </el-form-item>
                                <el-button class="submit" type="primary" @click="getSchool('phoneParam')">登录</el-button>
                            </el-form>
                        </el-tab-pane>
                    </el-tabs>
                    <div class="links">
                        <!-- <el-button type="text" class="ques" @click="toReg(true)">前往注册</el-button> -->
                        <el-button type="text" class="forget" @click="forget">忘记密码？</el-button>
                    </div>
                </div>
                <register v-else :isReg.sync="isReg" @updateInfo="updateInfo"></register>
            </div>
        </div>

        <v-footer ref="footer"></v-footer>

        <el-dialog title="选择角色" :visible.sync="roleDialog" width="24%" center :close-on-click-modal="false">
            <div>
                <el-select v-model="roleId" placeholder="请选择角色">
                    <el-option v-for="(item,index) in roleList" :key="index" :label="item.roleName"
                               :value="item.roleId"></el-option>
                </el-select>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancleRoleDia">取 消</el-button>
                <el-button v-if="activeName == '0'" type="primary" @click="roleSure('loginForm')">确 定</el-button>
                <el-button v-else type="primary" @click="roleSure('phoneParam')">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="phoneReset ? '手机重置密码' : '邮箱重置密码'" :visible.sync="forgetVisible" :close-on-click-modal="false"
                   @close="closeForget" width="30%">
            <template v-if="phoneReset">
                <el-form ref="form" label-width="60px">
                    <el-form-item label="手机号">
                        <el-input placeholder="请输入手机号" v-model.number="phone" maxlength="11"></el-input>
                    </el-form-item>
                    <el-form-item label="验证码">
                        <div class="flex-between">
                            <el-input v-model.number="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-item label="新密码">
                        <el-input type="password" placeholder="请输入新密码" v-model="newPassword"></el-input>
                    </el-form-item>
                </el-form>
                <div class="switch" @click="switchType(false)"><span>邮箱重置密码</span></div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="forgetVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updatePassword(1)">确 定</el-button>
                </span>
            </template>
            <template v-else>
                <el-form ref="form" label-width="60px">
                    <el-form-item label="邮箱">
                        <el-input placeholder="请输入邮箱" v-model="email"></el-input>
                    </el-form-item>
                    <el-form-item label="验证码">
                        <div class="flex-between">
                            <el-input v-model.number="emailCode" placeholder="请输入验证码" maxlength="6"></el-input>
                            <el-button style="margin-left: 10px" type="text" @click="sendEmailCode"
                                       :disabled="emailDisabled">{{ emailBtnText }}
                            </el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="新密码">
                        <el-input type="password" placeholder="请输入新密码" v-model="newPassword"></el-input>
                    </el-form-item>
                </el-form>
                <div class="switch" @click="switchType(true)"><span>手机重置密码</span></div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="forgetVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updatePassword">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

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

export default {
    data: function() {
        return {
            verificationIMG: "",
            isHh: Setting.isHh,
            schoolId: Setting.schoolId,
            activeName: "1",
            isReg: false,
            loginForm: {
                account: "xiaoliu",
                password: "111aaa",
                code: "", // 验证码
                random: "", // 随机数
                distinguish: null, // 区分手机号账号登录,1为账号登录,2为手机号或邮箱登录
                platform: 1 // 平台标识，1职站，2数据平台，3中台
            },
            loginRules: {
                account: [{ required: true, message: "请输入用户名", trigger: "blur" }],
                password: [{ required: true, message: "请输入密码", trigger: "blur" }],
                code: [{ required: true, message: "请输入验证码", trigger: "blur" }]
            },
            phoneParam: {
                userphone: "",
                phonePassword: ""
            },
            phoneRules: {
                userphone: [{ required: true, message: "请输入手机号/邮箱", trigger: "blur" }],
                phonePassword: [{ required: true, message: "请输入密码", trigger: "blur" }]
            },
            roleDialog: false,
            userId: "",
            roleId: "",
            roleList: [],
            forgetVisible: false,
            phoneReset: true,
            email: "",
            emailBtnText: "发送验证码",
            emailCode: "",
            emailDisabled: false,
            emailTimer: null,
            phone: "",
            phoneBtnText: "发送验证码",
            phoneCode: "",
            phoneDisabled: false,
            phoneTimer: null,
            newPassword: "",
            emailOpener: "",
            phoneOpener: ""
        };
    },
    components: {
        register,
        vFooter
    },
    mounted() {
        // 页面离开的时候销毁手机和邮箱验证码定时器
        this.$once("hook:beforeDestroy", function() {
            clearInterval(this.phoneTimer);
            this.phoneTimer = null;
            clearInterval(this.emailTimer);
            this.emailTimer = null;
        });
    },
    methods: {
        ...mapActions("user", [
            "login", "setInfo"
        ]),
        // 获取输入的账号的学校
        getSchool(form) {
            this.$refs[form].validate(valid => {
                if (valid) {
                    let data = {
                        account: this.activeName == "0" ? this.loginForm.username : this.phoneParam.userphone,
                        password: this.activeName == "0" ? this.loginForm.password : this.phoneParam.phonePassword,
                        schoolId: this.schoolId,
                        source: this.activeName
                    };
                    this.$get(this.api.loginSchool, data)
                        .then(res => {
                            this.schoolList = [...res.message.staffList, ...res.message.studentList];
                            let indexs = {};
                            this.schoolList = this.schoolList.reduce((cur, next) => {
                                indexs[next.schoolId] ? "" : indexs[next.schoolId] = true && cur.push(next);
                                return cur;
                            }, []);
                            if (this.schoolList.length >= 1) {
                                this.schoolId = this.schoolList[0].schoolId;
                                this.userId = this.schoolList[0].userId;
                                this.studentId = this.schoolList[0].studentId;
                                this.getRole(form);
                            } else {
                                util.errorMsg("账号不存在");
                            }
                        })
                        .catch(res => {
                        });
                } else {
                    util.errorMsg("请输入账号和密码");
                    return false;
                }
            });
        },
        // 之前是一个账号可能属于多个角色的，因此要选择角色，后来把这个功能改了，目前是学生度只能学生登录
        getRole(form) {
            let data = {
                userId: this.userId,
                schoolId: this.schoolId
            };
            this.$get(this.api.loginRole, data)
                .then(res => {
                    this.roleList = [...res.message.staffList, ...res.message.studentList];
                    let indexs = {};
                    this.roleList = this.roleList.reduce((cur, next) => {
                        indexs[next.roleId] ? "" : indexs[next.roleId] = true && cur.push(next);
                        return cur;
                    }, []);
                    this.roleList.forEach((n, k) => {
                        switch (n.roleId) {
                            case 2:
                                n.roleName = "管理员";
                                break;
                            case 3:
                                n.roleName = "老师";
                                break;
                            case 4:
                                n.roleName = "学生";
                                break;
                        }
                    });
                    if (this.roleList.length > 1) {
                        this.roleDialog = true;
                    } else {
                        this.roleId = this.roleList[0].roleId;
                        this.submitForm(form);
                    }
                })
                .catch(res => {
                });
        },
        updateInfo(data) {
            this.loginForm.account = data.username;
            this.loginForm.password = data.password;
        },
        roleSure(form) {
            if (this.roleId) {
                this.submitForm(form);
            } else {
                util.errorMsg("请选择角色！");
            }
        },
        submitForm(form) {
            this.$refs[form].validate(valid => {
                if (valid) {
                    let data = {
                        roleId: this.roleId,
                        userId: this.userId,
                        schoolId: this.schoolId
                    };
                    this.$get(this.api.logins, data).then(res => {
                        this.$post(this.api.updateLogInNumber, { userId: this.userId }).then(res => {
                        }).catch(res => {
                        }); // 更新登录次数和上次登录时间
                        let data = res.message.user;
                        util.local.set(Setting.tokenKey, data.token, Setting.tokenExpires);
                        this.setInfo({
                            userId: this.userId,
                            roleId: this.roleId,
                            studentId: this.studentId,
                            schoolId: this.schoolId,
                            avatar: data.userAvatars,
                            userName: data.userName,
                            dataTime: data.dataTime
                        });
                        util.successMsg("登录成功");
                        let redirect = decodeURIComponent(this.$route.query.redirect || "/index");
                        this.$router.replace(redirect);
                    }).catch(res => {
                    });
                }
            });
        },
        cancleRoleDia() {
            this.roleId = "";
            this.roleDialog = false;
        },
        toReg(status) {
            this.isReg = status;
        },
        forget() {
            this.forgetVisible = true;
        },
        emailCountdown() {
            let count = 60;
            if (!this.emailTimer) {
                this.emailDisabled = true;
                this.emailTimer = setInterval(() => {
                    if (count > 0) {
                        count--;
                        this.emailBtnText = `${count}秒后重试`;
                    } else {
                        this.emailDisabled = false;
                        clearInterval(this.emailTimer);
                        this.emailTimer = null;
                        this.emailBtnText = `发送验证码`;
                    }
                }, 1000);
            }
        },
        phoneCountdown() {
            let count = 60;
            if (!this.phoneTimer) {
                this.phoneDisabled = true;
                this.phoneTimer = setInterval(() => {
                    if (count > 0) {
                        count--;
                        this.phoneBtnText = `${count}秒后重试`;
                    } else {
                        this.phoneDisabled = false;
                        clearInterval(this.phoneTimer);
                        this.phoneTimer = null;
                        this.phoneBtnText = `发送验证码`;
                    }
                }, 1000);
            }
        },
        closeForget() {
            this.phoneCode = "";
            this.emailCode = "";
            this.userId = "";
            this.newPassword = "";
        },
        sendEmailCode() {
            if (!this.email) return util.warningMsg("请输入邮箱");
            if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(this.email)) return util.warningMsg("请输入正确的邮箱");
            let data = {
                email: this.email
            };
            this.$get(this.api.findPasswordByEmail, data).then(res => {
                if (res.errmessage == "success") {
                    util.successMsg("发送成功");
                    this.emailCountdown();
                    this.userId = res.data.userId;
                    this.emailOpener = res.data.opener;
                }
            }).catch(res => {
            });
        },
        sendPhoneCode() {
            if (!this.phone) return util.warningMsg("请输入手机号");
            if (!/^1[3456789]\d{9}$/.test(this.phone)) return util.warningMsg("请输入正确的手机号");
            let data = {
                phone: this.phone
            };
            this.$get(this.api.findPasswordByPhone, data).then(res => {
                if (res.errmessage == "success") {
                    util.successMsg("发送成功");
                    this.phoneCountdown();
                    this.userId = res.data.userId;
                    this.phoneOpener = res.data.opener;
                }
            }).catch(res => {
            });
        },
        async updatePassword(type) {
            if (type == 1) {
                if (!this.phone) return util.warningMsg("请输入手机号");
                if (!/^1[3456789]\d{9}$/.test(this.phone)) return util.warningMsg("请输入正确的手机号");
                if (!this.phoneCode) return util.warningMsg("请输入验证码");
            } else {
                if (!this.email) return util.warningMsg("请输入邮箱");
                if (!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(this.email)) return util.warningMsg("请输入正确的邮箱");
                if (!this.emailCode) return util.warningMsg("请输入验证码");
            }
            if (!this.newPassword) return util.warningMsg("请输入新密码");

            let checkData = {
                code: type == 1 ? this.phoneCode : this.emailCode,
                opener: type == 1 ? this.phoneOpener : this.emailOpener
            };
            let checkRes = await this.$post(this.api.checkCode, checkData);
            if (checkRes.errmessage == "success") {
                let resetData = {
                    userId: this.userId,
                    password: this.newPassword
                };
                let resetRes = await this.$post(this.api.resetPassword, resetData);
                if (resetRes.errmessage == "success") {
                    util.successMsg("重置成功");
                    this.forgetVisible = false;
                }
            }
        },
        switchType(type) {
            this.phoneReset = type;
        },
        submitFormLogin(form) {
            this.$refs[form].validate(valid => {
                if (valid) {
                    this.loginForm.distinguish = this.activeName === "1" ? 1 : 2;
                    this.login(this.loginForm).then(() => {
                        let redirect = this.$route.query.redirect ? decodeURIComponent(this.$route.query.redirect) : "/index";
                        this.$router.replace(redirect);
                    }).catch(res => {
                    });
                } else {
                    return util.errorMsg("请检查表单数据");
                }
            });
        },
        blur() {
            this.loginForm.random = Math.floor(Math.random() * 999999999);
            this.verificationIMG = this.api.verification + "?random=" + `${this.loginForm.random}`;
        }
    },
    created() {
        this.blur();
    }
};
</script>

<style scoped lang="scss">
.wrap {
    position: relative;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .header {
        width: 100%;
        height: 60px;
        background-color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 18px;
        box-shadow: 1px 1px 3px 2px #ececec;

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

    .bg {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: calc(100% - 116px);

        .left {
            position: relative;
            width: 40%;
            height: 100%;
            background: url(../../../assets/img/bg_2.png) 0 0/100% 100% no-repeat;

            .text {
                position: absolute;
                top: 35%;
                left: 15%;
                color: #fff;
                font-size: 46px;
                font-weight: bold;

                p:first-child {
                    margin-bottom: 20px;
                }
            }
        }

        .right {
            width: 50%;
            height: 100%;
            background: url(../../../assets/img/bg_1.png) center center/80% auto no-repeat;
        }
    }


    /deep/ .right-form {
        position: absolute;
        top: 47%;
        right: 12%;
        transform: translateY(-50%);
        width: 30%;

        .logo {
            width: 100%;
            margin-bottom: 40px;
        }

        .form {
            padding: 50px 20px 20px;
            background-color: #fff;
            border-radius: 16px;
            box-sizing: border-box;
            box-shadow: 0 1px 20px rgba(146, 120, 255, 0.3);
        }

        .back {
            position: absolute;
            top: 20px;
            left: 20px;
            font-size: 24px;
            color: #9278ff;
            cursor: pointer;

            &:hover {
                opacity: .8;
            }
        }

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

        h2 {
            padding-bottom: 10px;
            font-size: 20px;
            font-weight: 400;
            color: #8F73FF;
            text-align: center;
            border-bottom: 1px solid #f3f3f3;
        }

        .el-form {
            width: 70%;
            margin: 30px auto 0;

            .label {
                line-height: 1.8;
                color: #929292;
            }

            /deep/ .el-input__inner {
                height: 46px;
                padding: 0 23px;
                line-height: 46px;
                border: 1px solid #E5E5E5;
                border-radius: 8px !important;
            }

            /deep/ .el-form-item__error {
                top: 105%;
                left: auto;
                right: 0;
                color: #FFA94E;
            }

            .verification {
                position: absolute;
                right: 0px;
                width: 100px;
                height: 40px;
                border: 1px solid #DCDFE6;
                cursor: pointer;
            }

            .submit {
                width: 100%;
                height: 48px;
                margin-top: 40px;
                line-height: 48px;
                padding: 0;
                font-size: 18px;
                background-color: #9278ff;
                border-radius: 6px;
                border: 0;
            }
        }
    }
}

.switch {
    span {
        cursor: pointer;
        color: #9076FF;
    }
}

.links {
    width: 70%;
    margin: 20px auto 0;
    text-align: right;
}

.ques {
    color: #9278ff;
    font-size: 14px;
}

.forget {
    color: #ffa94e;
    font-size: 14px;
}
</style>