<template>
    <div class="wrap">
        <div class="left">
            <img src="../../assets/img/logo.png" alt="">
            <div class="text">
                <p>欢迎进入商品期权交易</p>
                <p>虚拟仿真系统</p>
            </div>
        </div>
        <div class="right">
            <div class="back" v-show="isReg" @click="toReg(false)">
                <i class="el-icon-back"></i>
            </div>
            <div v-if="!isReg">
                <h2>密码登录</h2>
                <el-form :model="loginForm" :rules="loginRules" ref="login" label-width="0px">
                    <el-form-item prop="username">
                        <p class="label">用户名</p>
                        <el-input v-model="loginForm.username" placeholder="请输入账号/手机号" @keyup.enter.native="submitForm()"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <p class="label">密码</p>
                        <el-input
                            type="password"
                            placeholder="请输入密码"
                            v-model="loginForm.password"
                            @keyup.enter.native="getSchool()"
                        >
                        </el-input>
                    </el-form-item>
                    <el-button class="submit" type="primary" @click="getSchool">登录</el-button>
                    <div class="links flex-between">
                        <el-button type="text" class="ques" @click="toReg(true)">前往注册</el-button>
                        <el-button type="text" class="forget" @click="forget">忘记密码？</el-button>
                    </div>
                    <!-- <p class="login-tips">其他登陆方式</p>
                    <div class="thirdParty">
                        <div class="item">
                            <img src="../../assets/img/icon_wechat.png" alt="">
                            微信扫码登录
                        </div>
                        <div class="item">
                            <img src="../../assets/img/icon_qq.png" alt="">
                            QQ一键登录
                        </div>
                    </div> -->
                </el-form>
            </div>
            <register v-else :isReg.sync="isReg" @updateInfo="updateInfo"></register>
        </div>

        <!-- 选择角色 -->
        <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 type="primary" @click="roleSure">确 定</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="phoneVisible = 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="emailVisible = false">取 消</el-button>
                    <el-button type="primary" @click="updatePassword">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import register from './RegisterForm';
export default {
    data: function() {
        return {
            isReg: false,
            loginForm: {
                username: '15794146134',
                password: '111aaa',
            },
            loginRules: {
                username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
            },
            roleDialog: false,
            userId: '',
            schoolId: '',
            roleId: '',
            roleList: [],
            studentId: '',
            forgetVisible: false,
            phoneReset: true,
            email: '',
            emailBtnText: '发送验证码',
            emailCode: '',
            emailDisabled: false,
            emailTimer: null,
            phone: '',
            phoneBtnText: '发送验证码',
            phoneCode: '',
            phoneDisabled: false,
            phoneTimer: null,
            newPassword: '',
            emailOpener: '',
            phoneOpener: ''
        };
    },
    components: {
        register
    },
    mounted(){
        this.$once('hook:beforeDestroy', function () {
            clearInterval(this.phoneTimer)
            this.phoneTimer = null
            clearInterval(this.emailTimer)
            this.emailTimer = null
        })
    },
    methods: {
        getSchool() {
            this.$refs.login.validate(valid => {
                if (valid) {
                    let data = {
                        account: this.loginForm.username,
                        password: this.loginForm.password,
                        schoolId: 2105
                    };                       
                    this.$get(this.api.loginSchool, data)
                        .then(res => {
                            if(res.status == 200){
                                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()
                                    this.roleId = 4
                                    this.submitForm()
                                }else{
                                    this.$message.error('账号不存在')
                                }
                            }else{
                                this.$message.error(res.errmessage);
                            }
                        })
                        .catch(res => {});
                } else {
                    this.$message.error('请输入账号和密码');
                    return false;
                }
            });
        },
        getRole() {
            // this.userId = this.schoolList.find((n,k) => {
            //     return n.schoolId == this.schoolId
            // }).userId
            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()
                    }
                })
                .catch(res => {});
        },
        updateInfo(data){
            this.loginForm.username = data.username
            this.loginForm.password = data.password
        },
        roleSure(){
            if(this.roleId){
                this.submitForm()
            }else{
                this.$message.error('请选择角色！');
            }
        },
        submitForm() {
            this.$refs.login.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 => {});
                        this.$message.success('登录成功');
                        sessionStorage.setItem('kd_client_username', this.loginForm.username);
                        this.$store.commit("userLoginData", { userId : this.userId,accountRole: this.roleId,studentId : this.studentId,schoolId: this.schoolId,token: res.message.user.token}); 
                        res.message.user.userAvatars && this.$store.commit("userPhoto", { avatar : res.message.user.userAvatars});
                        this.$store.commit("userName", { userName : res.message.user.userName});
                        let redirect = decodeURIComponent(this.$route.query.redirect || '/dashboard')
                        this.$router.replace(redirect)
                    }).catch(res => {}); 
                } else {
                    // this.$message.error('请输入账号和密码');
                    return false;
                }
            });
        },
        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 this.$message.warning('请输入邮箱')
            if(!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(this.email)) return this.$message.warning('请输入正确的邮箱')
            let data = {
                email: this.email
            }
            this.$get(this.api.findPasswordByEmail,data).then(res => {
                if(res.errmessage == 'success'){
                    this.$message.success('发送成功')
                    this.emailCountdown()
                    this.userId = res.data.userId
                    this.emailOpener = res.data.opener
                }
            }).catch(res => {});
        },
        sendPhoneCode(){
            if(!this.phone) return this.$message.warning('请输入手机号')
            if(!/^1[3456789]\d{9}$/.test(this.phone)) return this.$message.warning('请输入正确的手机号')
            let data = {
                phone: this.phone
            }
            this.$get(this.api.findPasswordByPhone,data).then(res => {
                if(res.errmessage == 'success'){
                    this.$message.success('发送成功')
                    this.phoneCountdown()
                    this.userId = res.data.userId
                    this.phoneOpener = res.data.opener
                }
            }).catch(res => {});
        },
        async updatePassword(type){
            if(type == 1){
                if(!this.phone) return this.$message.warning('请输入手机号')
                if(!/^1[3456789]\d{9}$/.test(this.phone)) return this.$message.warning('请输入正确的手机号')
                if(!this.phoneCode) return this.$message.warning('请输入验证码')
            }else{
                if(!this.email) return this.$message.warning('请输入邮箱')
                if(!/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(this.email)) return this.$message.warning('请输入正确的邮箱')
                if(!this.emailCode) return this.$message.warning('请输入验证码')
            }
            if(!this.newPassword) return this.$message.warning('请输入新密码')

            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'){
                    this.$message.success('重置成功')
                    this.forgetVisible = false
                }
            }
        },
        switchType(type){
            this.phoneReset = type
        }
    },
};
</script>

<style scoped lang="scss">
    .wrap {
        position: relative;
        width: 100%;
        height: 100%;
        background: url(../../assets/img/login_bg.png) 0 0/100% 100% no-repeat;
        overflow: hidden;

        .logo{
            position: absolute;
            top: 20px;
            left: 72px;
            width: 240px;
        }
        .left{
            position: absolute;
            top: 50%;
            left: 221px;
            transform: translateY(-60%);
            
            img{
                width: 447px;;
                margin-bottom: 30px;
            }
            .text{
                font-size: 47px;
                color: #fff;
                p:first-child{
                    margin-bottom: 30px;
                }
            }
        }
        .right{
            position: absolute;
            top: 50%;
            right: 100px;
            transform: translateY(-50%);
            width: 700px;
            padding: 50px 90px 20px;
            background-color: #fff;
            box-sizing: border-box;
            box-shadow: 0 1px 20px rgba(0,0,0,0.16);

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

                &:hover{
                    opacity: .8;
                }
            }

            h2{
                padding-bottom: 10px;
                font-size: 24px;
                font-weight: 400;
                color: #303d4c;
                text-align: center;
                border-bottom: 1px solid #E5E5E5;
            }
            /deep/.el-form{
                margin-top: 30px;
                
                .label{
                    margin-bottom: 10px;
                    color: #105CB2;
                }
                /deep/.el-input__inner{
                    height: 46px;
                    padding: 0 23px;
                    line-height: 46px;
                    border: 1px solid #AFB5BB;
                    border-radius: 23px !important;
                }
                /deep/.el-form-item__error{
                    top: 105%;
                    left: auto;
                    right: 0;
                    color: #FFA94E;
                }
                .submit{
                    width: 100%;
                    height: 48px;
                    margin-top: 60px;
                    line-height: 48px;
                    padding: 0;
                    font-size: 20px;
                    background-color: #105cb2;
                    border-radius: 23px;
                    border: 0;
                }
                .links{
                    margin: 20px 0 20px;
                }
                .ques{
                    color: #105cb2;
                    font-size: 14px;
                }
                .forget{
                    color: #ffa94e;
                    font-size: 14px;
                }
                .login-tips{
                    margin-bottom: 20px;
                    font-size: 16px;
                    color: #105CB2;
                    text-align: center;
                }
                .thirdParty{
                    .item{
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        margin-bottom: 20px;
                        padding: 10px 0;
                        color: #AFB5BB;
                        font-size: 16px;
                        background-color: #eff0f1;
                        border-radius: 36px;
                        cursor: pointer;
                        img{
                            width: 40px;
                            margin-right: 10px;
                        }
                    }
                }
            }
        }
    }
    .switch{
        span{
            cursor: pointer;
            color: #9076FF;
        }
    }
</style>