<template>
    <div>
        <div class="ajm-login-containier login-bg" ref="loginBg" :style="{backgroundImage: 'url('+loginBg+')'}" v-if="!pageLoading">
            <div class="login-top">
                <div>
                    <a class="logo" href="javascript:void(0);" v-if="systemUrl == null || systemUrl == ''">
                        <img :src="logoImg" alt="">
                        <h1 v-if="systemName">{{systemName}}</h1>
                        <h1 v-else>{{$t('message.Oauth.basePlatform')}}</h1>
                    </a>
                    <a class="logo" target="_blank" :href="systemUrl" v-else>
                        <img :src="logoImg" alt="">
                        <h1 v-if="systemName">{{systemName}}</h1>
                        <h1 v-else>{{$t('message.Oauth.basePlatform')}}</h1>
                    </a>
                </div>
            </div>
            <div class="ajm-login-form" v-if="!authOvertime">
                <el-form id="loginFormId" :model="loginForm" ref="loginForm" class="login-container" :show-message="false" @keyup.enter.native="enterLogin">
                    <h1>{{$t('message.Oauth.login')}}</h1>
                    <div class="form-item-tittle error-tip ellipsis" v-if="errorMessage">
                        <i></i>
                        {{errorMessage}}
                    </div>
                    <div class="form-item-tittle">{{$t('message.Oauth.id')}}</div>
                    <el-form-item prop="userName">
                        <el-input ref="userNameinput" :autofocus="true" type="text" v-model="loginForm.userName" auto-complete="off" :placeholder="$t('message.Oauth.confirmId')" size="medium" :maxlength="50"></el-input>
                    </el-form-item>
                    <div class="form-item-tittle">{{$t('message.Oauth.pwd')}}</div>
                    <el-form-item prop="password">
                        <el-input type="password" v-model="loginForm.password" auto-complete="off" :placeholder="$t('message.Oauth.confirmPwd')" size="medium" :maxlength="50"></el-input>
                    </el-form-item>
                    <div class="form-item-tittle">{{$t('message.Oauth.code')}}</div>
                    <el-form-item prop="validCode">
                        <el-col :span="16">
                            <el-input type="text" v-model="loginForm.validCode" auto-complete="off" :placeholder="$t('message.Oauth.confirmCode')" size="medium" :maxlength="50"></el-input>
                        </el-col>
                        <el-col :span="8" class="validcode-contaniner">
                            <i class="el-icon-loading" v-show="validcodeLoading"></i>
                            <img :src="validCodeUrl" v-show="!validcodeLoading" class="validcode" @click="loadValidCode">
                        </el-col>
                    </el-form-item>
                    <el-form-item class="ajm-login-submit">
                        <el-button type="primary" @click.native.prevent="login" :loading="logining" size="medium" :autofocus="true">{{$t('message.Oauth.login')}}
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="ajm-login-form ajm-auth-form" v-show="authOvertime">
                <el-form ref="authForm" class="login-container auth-container" :label-position="labelPosition">
                    <h1 class="margin-bottom10">{{$t('message.Oauth.oauth')}}</h1>
                    <el-form-item :label="$t('message.Oauth.facilityId')">
                        <el-input type="text" v-model="authForm.deviceId" auto-complete="off" :maxlength="50" :disabled="true"></el-input>
                    </el-form-item>
                    <el-input type="textarea" v-model="authForm.authorizationCode"  auto-complete="off" :placeholder="$t('message.Oauth.confirmOauth')" :autosize="{ minRows: 10, maxRows: 10}"></el-input>
                    <div class="ajm-auth-submit">
                        <el-button type="primary" @click.native.prevent="doAuth" :loading="authing" :autofocus="true">{{$t('message.Oauth.activate')}}</el-button>
                    </div>
                </el-form>
            </div>
        </div>
        <div v-else>
            <div class="loadding">
                <img src="static/images/loadding.gif"/>
            </div>
        </div>
    </div>
</template>

<script>
    import logoImg from "@/assets/image/logo.png";
    import loginBg from "@/assets/image/login-banner.png";
    // 登录服务
    import loginService from "../services/loginService";
    import AjmConfig from 'ajm-framework/core/utils/ajm-config';
    import aesUtils from "../services/aesUtils";
    import rsaUtils from "../services/rsaUtils";
    import SessionContextHodler from 'ajm-framework/core/utils/ajm-session'

    export default {
        name: "login",
        data() {
            return {
                pageLoading : true,
                labelPosition:'left',
                systemUrl: '',
                systemName: '',
                //登录背景图
                loginBg: loginBg,
                // 登录logo
                logoImg: logoImg,
                logoLoading: true,
                // 系统信息
                systemInfo: this.$store.getters.platformInfo.configureVO,
                //登录提示
                logining: false,
                //验证码加载中
                validcodeLoading: true,
                //验证码KEY
                validCodeKey: "",
                //验证码路径
                validCodeUrl: "",
                //错误消息
                errorMessage: "",
                //登录表单
                loginForm: {
                    //用户名
                    userName: "",
                    //密码
                    password: "",
                    //验证码
                    validCode: ""
                },
                //授权提示
                authing: false,
                // 授权表单
                authForm: {
                    // 授权码
                    authorizationCode: "",
                    // 设备ID
                    deviceId: this.$store.getters.deviceId
                },
                // 授权状态
                authOvertime: this.$store.getters.authOvertime,
                // 是否远程登录授权
                isRemoteOauth : this.$context.isRemoteOauth
            };
        },
        methods: {
            init() {
                // 加载系统信息
                if (this.systemInfo) {
                    let systemIcon = this.systemInfo.systemIcon;
                    let loginBg = this.systemInfo.loginBg;
                    // 系统图标
                    if (systemIcon) {
                        this.logoImg = this.getImgUrl(systemIcon);
                    }
                    // 系统背景
                    if (loginBg) {
                        this.loginBg = this.getImgUrl(loginBg);
                    }
                    // 系统名称
                    this.systemName = this.systemInfo.systemName;
                    // 系统地址
                    this.systemUrl = this.systemInfo.systemUrl;
                }
                
                let token = this.getQueryVariable("access_token");
                if(!this.authOvertime){
                    if (token) {
                        token = {"access_token": token};
                        this.$store.commit("user/saveTokenInfo", token);
                        this.goHome();
                    }else if(this.$context.isRemoteOauth){
                        this.forwardRemoteAuth();
                    } else {
                        //加载验证码
                        this.loadValidCode();
                        this.pageLoading = false;
                    }
                }else{
                    this.pageLoading = false;
                }
            },
            enterLogin(){
                this.login();
            },
            // 跳转远程授权
            forwardRemoteAuth(){
                let oauthUrl = this.$context.oauthUrl;
                let clientInfo = this.$context.clientInfo;
                let url = window.location.href;
                url = url.split("#")[0] +"#"+ this.$context.homePath;
                url = encodeURIComponent(url);
                let href = AjmConfig.getOAuthUrl() + AjmConfig.get("OAUTH_CONTEXT_PATH") + "/login?client_id=" + clientInfo.clientId + "&redirect_uri=" + url + "&response_type=code";
                window.location.href = href;
            },
            getImgUrl(filekey) {
                return AjmConfig.getApiUrl() + AjmConfig.get("BASE_CONTEXT_PATH") + '/common/file/viewFile/' + filekey;
            },
            //加载验证码
            loadValidCode() {
                this.validcodeLoading = true;
                loginService.generateKey().then(resp => {
                    var key = (this.validCodeKey = resp.data);
                    var _r = "1";
                    this.validCodeUrl = AjmConfig.getApiUrl() + AjmConfig.get("MANAGER_CONTEXT_PATH") + "/common/verifyCode/generateImage?key=" + key + "&_r=" + _r;
                    this.validcodeLoading = false;
                });
            },
            // 去除空格
            trim(val) {
                return val.replace(/^\s+|\s+$/gm, "");
            },
            // 检查表单信息
            check() {
                if (!this.trim(this.loginForm.userName)) {
                    this.errorMessage = this.$t('message.Oauth.confirmId');
                    return false;
                } else if (!this.trim(this.loginForm.password)) {
                    this.errorMessage = this.$t('message.Oauth.confirmPwd');
                    return false;
                } else if (!this.trim(this.loginForm.validCode)) {
                    this.errorMessage = this.$t('message.Oauth.confirmCode');
                    return false;
                } else {
                    return true;
                }
            },
            //登录
            login(ev) {
                // 检查表单信息
                if (!this.check()) {
                    return false;
                }
                let _this = this;
                this.logining = true;
                //isRSA 读取配置 是否采用RSA AES混合加密传输
                if(AjmConfig.get("ISENCBYRSA")){
                    //javaPublicKey 后端公钥  后期优化成获取javaPublicKey
                    let javaPublicKey = AjmConfig.get("javaPublicKey") ||
                        "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF70j6EHuN16zSfcRLhoB/XOoScUmaHgXra7PehP5Lryy+sYdkqroOO8lnmybAY1ss/i2QDWXTQw0LGK07BzX4x/bonYv5ROqlARq0xO2nQnJdtPUx7fUfGrUeS+3ryRw8yzbeW3Nx1lQjV3oM4I+GHoduAvMP05zd8EtY8xZlKwIDAQAB";
                    let genKeyPair = rsaUtils.genKeyPair();
                    let aesKey = aesUtils.genKey();
                    let password = aesUtils.encrypt(
                        this.$md5(this.loginForm.password),
                        aesKey
                    );
                    let resKey = rsaUtils.encryptLong(aesKey, javaPublicKey);
                    //rsa对aesKey使用后端公钥加密后数据					
                    var loginParams = {
                        username: this.loginForm.userName,
                        password: window.encodeURIComponent(resKey+"|||"+password),
                        _validCode: window.encodeURIComponent(this.loginForm.validCode),
                        // password: resKey+"|||"+password,
                        // _validCode: this.loginForm.validCode,
                        _t: this.validCodeKey
                    };
                }else if(AjmConfig.get("ISADAUTHENTICATION")){ // 是否开启AD域认证
                    var jsencrypt= new this.$jsEncrypt.JSEncrypt();
                    var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF70j6EHuN16zSfcRLhoB/XOoScUmaHgXra7PehP5Lryy+sYdkqroOO8lnmybAY1ss/i2QDWXTQw0LGK07BzX4x/bonYv5ROqlARq0xO2nQnJdtPUx7fUfGrUeS+3ryRw8yzbeW3Nx1lQjV3oM4I+GHoduAvMP05zd8EtY8xZlKwIDAQAB";
                    jsencrypt.setPublicKey(publicKey);
                    var loginParams = {
                        username: this.loginForm.userName,
                        password: window.encodeURIComponent(jsencrypt.encrypt(this.loginForm.password)),
                        _validCode: window.encodeURIComponent(this.loginForm.validCode),
                        // _validCode: this.loginForm.validCode,
                        _t: this.validCodeKey
                    };
                }else{
                    var loginParams = {
                        username: this.loginForm.userName,
                        password: this.$md5(this.loginForm.password),
                        _validCode: window.encodeURIComponent(this.loginForm.validCode),
                        // _validCode: this.loginForm.validCode,
                        _t: this.validCodeKey
                    };
                }
                //执行登录
                this.$loginApi.login(loginParams, function () {
                    loginService.checkIsDefaultPassword().then(resp =>{
                       if(resp){
                           _this.goEdit();
                       }else{
                           _this.goHome();
                       }
                    });
                }).catch(err => {
                    if(err.response&&err.response.status != 200){
                        this.loadValidCode();
                    }
                    var data = err.message;
                    this.errorMessage = data;
                    this.logining = false;
                });
            },
            // 执行授权
            doAuth(){
                this.authing = true;
                let authParams = {
                    authorizationCode: this.authForm.authorizationCode
                };
                //执行登录
                this.$authApi.activateAuth(authParams).then(resp => {
                    this.authing = false;
                    if(resp.status == 500){
                        this.$alert(resp.message+"," + this.$t('message.Oauth.oauthError'), this.$t('message.Oauth.OauthClue'), {
                            confirmButtonText: this.$t('message.confirm')
                        });
                    }else{
                        this.$alert(this.$t('message.Oauth.activateSuccess'), this.$t('message.Oauth.OauthClue'));
                        this.$store.dispatch("auth/setAuthorizationVO",resp);
                        this.authOvertime = resp.authOvertime;
                        this.init();
                    }
                }).catch(err => {
                    this.authing = false;
                });
            },
            //进入首页
            goHome() {
                this.$router.push({
                    path: this.$context.homePath
                });
            },
            //进入修改密码
            goEdit(){
                this.$router.push('/PasswordEditMain/');
            },
            //获取token
            getQueryVariable(variable) {
                var query = window.location.hash.split("?")[1];
                if (query) {
                    var vars = query.split("&");
                    for (var i = 0; i < vars.length; i++) {
                        var pair = vars[i].split("=");
                        if (pair[0] == variable) {
                            return pair[1];
                        } else {
                            return null;
                        }
                    }
                } else {
                    return null;
                }

            }
        },
        //初始化
        mounted() {
            this.init();
            this.$nextTick(()=>{
                if(!this.authOvertime){
                    this.$refs.userNameinput.focus()
                }
            })
        }
    };
</script>

<style lang="less" scoped>
    @keyframes shadow {
        0% {
            opacity: 0;
        }
        100% {
            opacity: 1
        }
    }

    .login-bg {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 0;
        height: 100%;
        background: url(../image/login-banner.png) no-repeat center center;
        background-size: cover;
        min-height: 600px;
        transform-origin: 50% 50%;
        .login-top {
            width: 100%;
            height: 50px;
            box-shadow: 0 1px #080b10;
            background: -webkit-linear-gradient(#273342, #293647); /* Safari 5.1 - 6.0 */
            background: -o-linear-gradient(#273342, #293647); /* Opera 11.1 - 12.0 */
            background: -moz-linear-gradient(#273342, #293647); /* Firefox 3.6 - 15 */
            background: linear-gradient(#273342, #293647); /* 标准的语法 */
            h1 {
                display: inline-block;
                font-size: 18px;
                font-weight: bold;
                color: #fff;
                vertical-align: middle;
                padding-left: 2px;
            }
            img {
                width: 48px;
                height: 48px;
                vertical-align: middle;
                margin-top: 4px;
                margin-left: 20px;
            }
        }
        .ajm-login-form {
            box-sizing: border-box;
            position: fixed;
            top: 0;
            bottom: 0;
            right: 10%;
            height: 460px;
            width: 380px;
            margin: auto;
            box-sizing: border-box;
            animation: shadow 0.5s 1 linear forwards;
            .login-container {
                width: 380px;
                height: 430px;
                margin: 0 auto;
                background: #fff;
                h1 {
                    margin-left: 40px;
                    padding-top: 25px;
                    margin-bottom: 15px;
                    font-size: 24px;
                    font-weight: bold;
                    color: #333538;
                }
                .form-item-tittle {
                    font-size: 12px;
                    color: #333538;
                    margin: 0px 0 10px 40px;
                }
                .error-tip {
                    width: 300px;
                    height: 32px;
                    line-height: 32px;
                    color: #E3342B;
                    border: 1px solid #FF4F4F;
                    background: #FFEBEB;
                    //margin-top: 18px;
                    margin-bottom: 18px;
                    i {
                        display: inline-block;
                        width: 18px;
                        height: 18px;
                        vertical-align: middle;
                        background: url("../image/error-tip.png") no-repeat;
                        background-size: 100% 100%;
                        margin-left: 10px;
                        margin: -2px 6px 0 10px;
                    }
                }
                .el-form-item {
                    width: 300px;
                    margin: 0 auto;
                    height: 36px;
                    margin-bottom: 18px;
                    .el-form-item__content {
                        height: 36px!important;
                        line-height: 36px!important;
                        button {
                            width: 300px;
                            margin: 0 auto;
                            //background: #19c5e3;
                            border: none;
                            height: 36px;
                            font-size: 14px;
                            color: #ffffff;
                        }
                        .el-input__inner {
                            height: 36px;
                            line-height: 36px;
                            font-size: 12px;
                            color: #45494C;
                        }
                        .validcode-contaniner {
                            text-align: center;
                            margin-top: 2px;
                            .validcode {
                                width: 100%;
                                height: 36px;
                                display: block;
                                cursor: pointer;
                                position: relative;
                                top: 0;
                                right: 0;
                            }
                        }
                    }
                }
                .el-form-item.ajm-login-submit {
                    margin-top: 30px;
                }
            }
        }
        .ajm-auth-form{
            width: 380px;
            height: 460px;
            background: #fff;
            .auth-container{
                 width: 300px;
                .margin-bottom10{
                     margin-left: 0;
                }
                .el-form-item{
                    height: auto;
                    margin-bottom: 15px;
                }
                .el-textarea{
                    margin-bottom: 15px;
                }
                .ajm-auth-submit{
                    .el-button--primary{
                        width: 100%;
                        padding: 12px;
                    }
                }
            }
        }
    }
    
</style>



