<template>
    <div class="login-wrap">
        <div class="logo" :class="{ logoleave: jumpAnimate }">
            <img src="@assets/img/icon_logo2.png" />
        </div>
        <div class="login-title">
            <h1 class="title-name">智慧社区管理平台</h1>
            <!-- <p class="title-lang">Smart community management platform</p> -->
            <p class="title-lang">SMART COMMUNITY MANAGEMENT PLATFORM</p>
        </div>
        <div class="ms-login ms-login1" :class="{ 'ms-login1leave': jumpAnimate }" v-show="!isSelectTenant">
            <div class="ms-main">
                <div class="login-topImg paTop10"><img src="@assets/img/loginPop/img1.png" alt="" /></div>
                <el-tabs v-model="activeName" @tab-click="handleClick" class="login-body">
                    <el-tab-pane label="账号登录" name="accountNumber" class="regist_class">
                        <el-form>
                            <div class="form-item">
                                <el-input
                                    type="text"
                                    placeholder="请输入账号"
                                    required="required"
                                    v-model="accountNumberData.mobile"
                                    maxlength="11"
                                    @focus="namefocus = true"
                                    @blur="onnamefocus"
                                    clearable
                                >
                                </el-input>
                            </div>
                            <div class="form-item">
                                <el-input
                                    type="password"
                                    placeholder="请输入密码"
                                    v-model="accountNumberData.password"
                                    @focus="phonefocus = true"
                                    @blur="onphonefocus"
                                    clearable
                                >
                                </el-input>
                            </div>
                            <div class="form-item">
                                <el-input
                                    type="text"
                                    placeholder="请输入手机验证码"
                                    v-model="accountNumberData.smsCode"
                                    @focus="smsCodefocus = true"
                                    @blur="onsmsCodefocus"
                                >
                                </el-input>
                                <el-button
                                    type="text"
                                    v-if="accountNumberData.time"
                                    class="el-fl-right codeImg sms-code sms-code-istime"
                                    :disabled="!!accountNumberData.time"
                                    @click="getCode"
                                >
                                    {{ `${accountNumberData.time}s后重新获取` }}</el-button
                                >
                                <el-button
                                    type="text"
                                    v-else
                                    class="el-fl-right codeImg sms-code sms-code-notime"
                                    :disabled="!!accountNumberData.time"
                                    @click="getCode"
                                >
                                    获取验证码</el-button
                                >
                            </div>
                            <div class="remember">
                                <el-checkbox v-model="rememberName">记住账号</el-checkbox>
                            </div>
                            <span class="tips" v-if="accountNumberData.errMsg">{{ accountNumberData.errMsg }}</span>
                            <el-button type="primary" class="btn" @click="accountNumberSubmit" v-preventReClick>登录</el-button>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="手机登录" name="login" class="login_class">
                        <el-form>
                            <div class="form-item">
                                <el-input
                                    type="text"
                                    placeholder="请输入手机号"
                                    required="required"
                                    v-model="loginData.mobile"
                                    maxlength="11"
                                    @focus="mobilefocus = true"
                                    @blur="onmobilefocus"
                                    clearable
                                >
                                </el-input>
                            </div>
                            <div class="form-item">
                                <el-input
                                    type="text"
                                    placeholder="请输入校验码"
                                    required="required"
                                    v-model="loginData.code"
                                    @focus="codefocus = true"
                                    @blur="oncodefocus"
                                >
                                </el-input>
                                <img class="el-fl-right codeImg codeImg-item" :src="loginData.codeUrl" @click="refreshCode" />
                            </div>

                            <div class="form-item">
                                <el-input
                                    type="text"
                                    placeholder="请输入手机验证码"
                                    v-model="loginData.smsCode"
                                    @focus="smsCodefocus = true"
                                    @blur="onsmsCodefocus"
                                >
                                </el-input>
                                <el-button
                                    type="text"
                                    v-if="loginData.time"
                                    class="el-fl-right codeImg sms-code sms-code-istime"
                                    :disabled="!!loginData.time"
                                    @click="getCode"
                                >
                                    {{ `${loginData.time}s后重新获取` }}</el-button
                                >
                                <el-button
                                    type="text"
                                    v-else
                                    class="el-fl-right codeImg sms-code sms-code-notime"
                                    :disabled="!!loginData.time"
                                    @click="getCode"
                                >
                                    获取验证码</el-button
                                >
                            </div>
                            <span class="tips" v-if="loginData.errMsg">{{ loginData.errMsg }}</span>
                            <el-button type="primary" class="btn mgTop16" @click="loginSubmit">登录</el-button>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
                <div class="login-buttonImg paTop10"><img src="@assets/img/loginPop/img2.png" alt="" /></div>
            </div>
        </div>
        <select-tenant :selectDta="loginInfoArr" :class="{ 'ms-login1leave': jumpAnimate }" v-show="isSelectTenant"></select-tenant>
    </div>
</template>

<script>
import SelectTenant from '@/components/ToggleTenant';
let timer;
const phoneRegExp = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|147)\d{8}$/,
    codeRegExp = /^\d{4}$/;
export default {
    components: {
        SelectTenant
    },
    data() {
        return {
            isSelectTenant: false,
            loginInfoArr: [],
            // 获取url地址后面的参数
            activeName: 'accountNumber',
            urlQuery: '',
            activeIndex: '1',
            loginData: {
                mobile: '17800000001', //手机号
                code: '', //校验码
                codeUrl: '',
                smsCode: '2020', //手机校验码
                time: 0,
                random: '', //用于重新获取数字校验码的随机数
                errMsg: ''
            },
            accountNumberData: {
                mobile: '',
                password: '',
                smsCode: '2020', //手机校验码
                time: 0,
                random: '', //用于重新获取数字校验码的随机数
                errMsg: ''
            },
            rememberName: false,
            registerData: {
                registered: false,
                name: '',
                mobile: '',
                errMsg: '',
                roleType: '',
                roleTypeOptions: [
                    {
                        id: 1,
                        label: '水表厂家用户'
                    },
                    {
                        id: 2,
                        label: '自来水公司用户'
                    },
                    {
                        id: 3,
                        label: '城市合伙人'
                    }
                ]
            },
            mobilefocus: false,
            codefocus: false,
            smsCodefocus: false,
            namefocus: false,
            phonefocus: false,
            tanasfocus: false,
            jumpAnimate: false
        };
    },
    methods: {
        onmobilefocus() {
            if (this.loginData.mobile.length === 0) {
                this.mobilefocus = false;
            }
        },
        oncodefocus() {
            if (this.loginData.code.length === 0) {
                this.codefocus = false;
            }
        },
        onsmsCodefocus() {
            if (this.loginData.smsCode.length === 0) {
                this.smsCodefocus = false;
            }
        },
        onnamefocus() {
            if (this.registerData.name.length === 0) {
                this.namefocus = false;
            }
        },
        onphonefocus() {
            if (this.registerData.mobile.length === 0) {
                this.phonefocus = false;
            }
        },
        ontanasfocus() {
            if (this.registerData.roleType.length === 0) {
                this.tanasfocus = false;
            }
        },
        ontanaschange(val) {
            if (val.length === 0) {
                this.tanasfocus = false;
            }
        },
        //获取随机数
        getRandom() {
            const CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            for (var r, chars = CHARS, uuid = new Array(36), rnd = 0, i = 0; 36 > i; i++) {
                8 == i || 13 == i || 18 == i || 23 == i
                    ? (uuid[i] = '-')
                    : 14 == i
                    ? (uuid[i] = '4')
                    : (2 >= rnd && (rnd = (33554432 + 16777216 * Math.random()) | 0),
                      (r = 15 & rnd),
                      (rnd >>= 4),
                      (uuid[i] = chars[19 == i ? (3 & r) | 8 : r]));
            }
            return uuid.join('');
        },
        refreshCode() {
            this.loginData.random = this.getRandom();
            this.loginData.codeUrl = `/sc-user-auth/validateCode/image?random=${this.loginData.random}`;
        },
        //获取手机验证码
        getCode() {
            const { mobile, code, random } = this.loginData;
            let errorMsg = '';
            if (!codeRegExp.test(code)) {
                errorMsg = '您输入的图形验证码有误，请重新输入';
            }
            if (!code) {
                errorMsg = '请输入图形验证码';
            }
            if (!phoneRegExp.test(mobile)) {
                errorMsg = '您输入的手机号码格式有误，请重新输入';
            }
            if (!mobile) {
                errorMsg = '请输入手机号码';
            }
            if (errorMsg) {
                this.loginData.errMsg = errorMsg;
                return;
            }
            this.loginData.errMsg = '';
            this.$http
                .postForm('/sms/v2/send', {
                    mobile,
                    code,
                    random
                })
                .then(({ status, msg }) => {
                    this.$message({
                        type: status === 0 ? 'success' : 'error',
                        message: msg
                    });
                    if (status === 0) {
                        this.loginData.time = 60;
                        timer = setInterval(() => {
                            this.loginData.time -= 1;
                            if (this.loginData.time == 0) {
                                clearInterval(timer);
                            }
                        }, 1000);
                    }
                });
        },
        registerSubmit() {
            const params = { ...this.registerData };
            if (!params.name) {
                this.registerData.errMsg = '· 请输入姓名';
                return;
            }
            if (!params.mobile) {
                this.registerData.errMsg = '· 请输入手机号';
                return;
            }
            if (!phoneRegExp.test(params.mobile)) {
                this.registerData.errMsg = '· 请输入正确的手机号';
                return;
            }
            if (!params.roleType) {
                this.registerData.errMsg = '· 请输入用户类型';
                return;
            }
            let registparams = {
                username: params.name,
                phone: params.mobile,
                userType: params.roleType
            };
            this.$http.post('/user/insertRegister', registparams).then(({ status, data, msg }) => {
                if (status === 0) {
                    this.registerData.errMsg = '';
                    this.$message({
                        type: 'success',
                        message: '注册成功，请登录'
                    });
                    this.activeName = 'accountNumber';
                } else {
                    this.$message({
                        type: 'err',
                        message: '注册失败'
                    });
                }
            });
        },
        accountNumberSubmit() {
            let errorMsg = '';
            const params = { ...this.accountNumberData };
            if (!codeRegExp.test(params.smsCode)) {
                errorMsg = '· 您输入的手机验证码有误，请重新输入';
            }
            if (!params.smsCode) {
                errorMsg = '· 请输入手机检验码';
            }

            if (!params.password) {
                errorMsg = '· 请输入密码';
            }
            if (!params.mobile) {
                errorMsg = '· 请输入账号';
            }
            if (errorMsg) {
                this.accountNumberData.errMsg = errorMsg;
                return;
            }
            if (this.rememberName) {
                localStorage.setItem('accountNumberName', params.mobile);
            } else {
                localStorage.removeItem('accountNumberName');
            }
            this.$http.postForm('/user/mobileLogin', params).then(({ status, data, msg }) => {
                if (status === 0 && data) {
                    localStorage.setItem('SC_token', data.token.access_token);
                    this.loginInfoArr = data.loginInfo;
                    if (data.loginInfo.length > 1) {
                        this.isSelectTenant = true;
                    } else {
                        console.log('this.loginInfoArr', this.loginInfoArr);
                        this.$store.commit('setloginInfo', data.loginInfo[0]);
                        this.jumpAnimate = true;
                        window.sessionStorage.setItem('loginJson', JSON.stringify(this.loginInfoArr));
                        window.sessionStorage.setItem('loginJsonActive', JSON.stringify(this.loginInfoArr[0]));
                        setTimeout(() => {
                            this.$router.push({
                                path: '/nav'
                            });
                        }, 1500);
                    }
                } else {
                    this.$message.error(msg);
                    if (msg === '您输入的手机验证码已过期，请重新输入') {
                        self.refreshCode();
                        self.loginData.code = '';
                    }
                }
            });
        },
        loginSubmit() {
            let errorMsg = '';
            const params = { ...this.loginData };
            if (!codeRegExp.test(params.smsCode)) {
                errorMsg = '· 您输入的手机验证码有误，请重新输入';
            }
            if (!params.smsCode) {
                errorMsg = '· 请输入手机检验码';
            }
            if (!codeRegExp.test(params.code)) {
                errorMsg = '· 您输入的图形验证码有误，请重新输入';
            }
            if (!params.code) {
                errorMsg = '· 请输入图形验证码';
            }
            if (!phoneRegExp.test(params.mobile)) {
                errorMsg = '· 请输入正确的手机号';
            }
            if (!params.mobile) {
                errorMsg = '· 请输入手机号';
            }
            if (errorMsg) {
                this.loginData.errMsg = errorMsg;
                return;
            }
            this.$http.postForm('/user/smsCodeLogin', params).then(({ status, data, msg }) => {
                if (status === 0 && data) {
                    localStorage.setItem('SC_token', data.token.access_token);
                    this.loginInfoArr = data.loginInfo;
                    if (data.loginInfo.length > 1) {
                        this.isSelectTenant = true;
                    } else {
                        console.log('this.loginInfoArr', this.loginInfoArr);
                        this.$store.commit('setloginInfo', data.loginInfo[0]);
                        this.jumpAnimate = true;
                        window.sessionStorage.setItem('loginJson', JSON.stringify(this.loginInfoArr));
                        window.sessionStorage.setItem('loginJsonActive', JSON.stringify(this.loginInfoArr[0]));
                        setTimeout(() => {
                            this.$router.push({
                                path: '/nav'
                            });
                        }, 1500);
                    }
                } else {
                    this.$message.error(msg);
                    if (msg === '您输入的手机验证码已过期，请重新输入') {
                        self.refreshCode();
                        self.loginData.code = '';
                    }
                }
            });
        }
    },
    created() {
        let that = this;
        document.onkeydown = function (e) {
            e = window.event || e;
            if (that.$route.path == '/login' && (e.code == 'Enter' || e.code == 'enter') && that.activeName == 'accountNumber') {
                that.loginSubmit(); //登录函数
            }
        };
        this.refreshCode();
        localStorage.removeItem('menupath');
        localStorage.removeItem('ms_username');
        localStorage.removeItem('SC_token');
        // sessionStorage.removeItem('tabs');
        sessionStorage.clear();
        const accountNumberName = localStorage.getItem('accountNumberName') || '';
        this.accountNumberData.mobile = accountNumberName;
        this.rememberName = !!accountNumberName;
    }
};
</script>

<style lang="scss" scoped>
/deep/.el-input__inner {
    font-family: Microsoft YaHei;
    height: 48px;
    line-height: 10px;
    border-radius: 6px;
    background: #1d212a;
    border: 1px solid rgba(255, 255, 255, 0.3);
    color: #ffffff;
    font-size: 16px;
    font-weight: 400;
    &:focus {
        border: 1px solid #0eaeff;
        border-radius: 6px;
    }
    // opacity: 0.3;
}
/deep/.el-form-item {
    margin-bottom: 30px;
}

/deep/.el-tabs {
    // position: relative;
    // position: absolute;
    // top: 10px;
    width: 100%;
    // padding: 0px 30px 30px 30px;
    // height: 360px;
    .el-tabs__header {
        margin: 0;
    }
    .el-tabs__content {
        .el-form .form-item {
        }
    }
    .el-tabs__nav-wrap::after {
        display: none;
    }
    .el-tabs__nav {
        width: 100%;
        .el-tabs__bar {
            height: 0;
        }
        .el-tabs__active-bar {
            background-color: transparent;
            // background: url(../../assets/img/line_selected.png) no-repeat;
            // height: 2px;
            // background: #0EAEFF;
            // width: 48px !important;
            // left: 25%;
            // transform: translateX(-50%) !important;
            // background-position: center;
        }
        .el-tabs__item {
            width: 50%;
            color: #ffffff33;
            text-align: center;
            padding: 0;
        }
        .el-tabs__item.is-active {
            color: #ffffff;
            &::after {
                display: block;
                content: '';
                position: absolute;
                width: 48px;
                left: 50%;
                transform: translateX(-50%);
                height: 2px;
                background: #0eaeff;
                bottom: 0;
            }
        }
    }
}

/deep/ .right-tabbox-newnotice /deep/.el-tabs__nav-wrap::after {
    position: static !important;
}

// 改版
// 动画

@-webkit-keyframes lightfadeout {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}
@keyframes lightfadeout {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}
@-webkit-keyframes lightfadeoutleave {
    0% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}
@keyframes lightfadeoutleave {
    0% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}

.login-wrap .logo {
    position: absolute;
    top: 120px;
    left: 130px;
    margin: 0;
    opacity: 0;
    animation-name: lightfadeout;
    animation-duration: 0.267s;
    animation-timing-function: linear;
    animation-delay: 1.267s;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}
.login-wrap .logo > img {
    width: 150px;
    height: 40px;
}
.login-wrap .logoleave {
    opacity: 1;
    animation-name: lightfadeoutleave;
    animation-duration: 0.267s;
    animation-timing-function: linear;
    animation-delay: 0.3s;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}
.ms-login1 {
    opacity: 0;
    animation-name: lightfadeout;
    animation-duration: 0.5s;
    animation-timing-function: linear;
    animation-delay: 0.5s;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}
.ms-login1leave {
    opacity: 1;
    animation-name: lightfadeoutleave;
    animation-duration: 0.5s;
    animation-timing-function: linear;
    animation-delay: 0.5s;
    animation-iteration-count: 1;
    animation-fill-mode: forwards;
}

/deep/.el-input__inner {
    &::placeholder {
        font-size: 16px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #ffffff33;
    }
}

.prefix-img {
    height: 18px;
    position: absolute;
    top: 15px;
    padding: 0 10px 0 14px;
}
.center-middle {
    width: 1660px;
    height: 430px;
    position: absolute;
    top: 23%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.suffix-img {
    position: absolute;
    top: 15px;
    right: 0;
    padding: 0 10px 0 14px;
}
/deep/.el-input--prefix .el-input__inner {
    padding-left: 44px;
}
.login-wrap .ms-main .form-item .codeImg-item {
    width: 110px;
    height: 34px;
    background: #97a3c1;
    opacity: 0.8;
    border-radius: 4px;
}
.login-wrap .ms-main .form-item .sms-code {
    border-left: 1px solid rgba(38, 133, 242, 0.3);
    padding-left: 26px;
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: rgba(14, 174, 255, 1);
}
.login-wrap .ms-main .form-item .sms-code-notime {
    width: 110px;
    padding-left: 10px;
}
.login-wrap .ms-main .form-item .sms-code-istime {
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: rgba(255, 255, 255, 0.4);
}
.login-wrap .ms-main .btn {
    border: none;
}

.define-el-select {
    /deep/ .el-input__suffix {
        display: none;
    }
}
.login-wrap .ms-main .form-item .btn-select {
    padding: 0 10px 0 20px;
    pointer-events: none;
    img {
        width: 18px;
        height: 18px;
    }
}
</style>
<style lang="scss" scoped >
.login-wrap {
    min-width: 1280px;
    width: 100%;
    height: 100%;
    background: url(../../assets/img/loginPop/bg.png) center no-repeat;
    background-size: cover;
    overflow: hidden;
    position: relative;
    .ms-login {
        position: absolute;
        top: 50%;
        right: 215px;
        transform: translateY(-50%);
    }
    .login-title {
        position: absolute;
        top: 226px;
        left: 130px;
        color: white;
        font-family: PingFangSC-Semibold;
        .title-name {
            font-size: 60px;
        }
        .title-lang {
            font-size: 17.5px;
            display: inline-block;
            // margin-left: 60px;
            // transform: scale(1.35, 0.9);
            // -ms-transform: scale(1.35, 0.9);
            // -webkit-transform: scale(1.35, 0.9);
            // -moz-transform: scale(1.35, 0.9);
            // -o-transform: scale(1.35, 0.9);
            margin-left: 30px;
            transform: scale(1.15, 0.8);
            -ms-transform: scale(1.15, 0.8);
            -webkit-transform: scale(1.15, 0.8);
            -moz-transform: scale(1.15, 0.8);
            -o-transform: scale(1.15, 0.8);
        }
    }
    .ms-main {
        width: 400px;
        border: 1px solid rgba(240, 238, 241, 0.2);
        border-radius: 10px;
        opacity: 0.8;
        height: 468px;
        background: linear-gradient(0deg, #101327 0%, #29314c 100%);
        box-shadow: 0px 10px 80px 0px rgba(0, 0, 0, 0.15);
        .login-topImg,
        .login-buttonImg {
            width: 100%;
            text-align: center;
        }
        .login-buttonImg {
            position: absolute;
            bottom: 0;
        }
        .login-body {
            padding: 15px 30px 0 30px;
            .tips {
                color: #f25050;
                font-size: 14px;
                display: inline-block;
                margin-bottom: 10px;
            }
            .btn {
                width: 100%;
                background: linear-gradient(-90deg, #0098ef 0%, #0eaeff 100%);
                border-radius: 6px;
                height: 48px;
                font-size: 20px;
                font-family: Microsoft YaHei;
                font-weight: 400;
                color: #ffffff;
            }
            .remember {
                margin-bottom: 30px;
            }
        }
        .form-item {
            margin: 24px 0;
            height: 48px;
            display: flex;
            align-items: center;
            position: relative;
            .codeImg {
                position: absolute;
                right: 10px;
            }
            .code {
                border-left: 1px solid #2887f2;
                height: 20px;
                line-height: 0px;
                padding-left: 10px;
            }
            .el-select {
                width: 100%;
            }
            .icon {
                position: absolute;
                top: 18px;
                left: 6px;
            }
        }
    }
}
.paTop10 {
    padding-top: 10px;
}
.mgTop16 {
    margin-top: 16px;
}
</style>