<template>
    <div class="bg">
        <el-form :rules="rules" ref="loginForm" :model="loginForm" class="loginContainer">
            <h3 class="loginTitle">
                Emdoor可视化平台
            </h3>
            <el-form-item prop="sob">
                <el-select v-model="loginForm.sob"  placeholder="请选择账套" style="width:100%">
                    <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="workshop">
                <el-select v-model="loginForm.type"  placeholder="请选择看板类型" style="width:100%">
                    <el-option
                            v-for="item in typeoptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
          <el-form-item prop="factory">
            <el-select v-model="loginForm.factory"  placeholder="请选择厂区" style="width:100%">
              <el-option
                  v-for="item in factoryoptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
            <el-form-item prop="username">
                <el-input type="text" v-model="loginForm.username" placeholder="请输入用户名" >
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" >
                </el-input>
            </el-form-item>
            <el-checkbox v-model="checked" class="loginRemember">记住我</el-checkbox>
            <el-button type="primary" style="width:100%" @click="submitLogin">登录</el-button>
        </el-form>
    </div>
</template>

<script>
    import CryptoJS from "crypto-js";

    export default {
        name: "Login",
        data(){
            return{
                captchaUrl: "",
                loginForm:{
                    sob:"",
                    username:"",
                    password:"",
                    type:"产线看板",
                    factory:""
                },
                checked: true,
                rules:{
                    sob :[{required:true,message:"请选择账套",trigger:"blur"}],
                    username:[{required:true,message:"请输入用户名",trigger:"blur"}/*,{ min: 5, max: 14, message: '长度在 5 到 14 个字符', trigger: 'blur' }*/],
                    password:[{required:true,message:"请输入密码",trigger:"blur"} /*,{ min: 6,  message: '密码长度要大于6', trigger: 'blur' }*/],
                    type:[{required:true,message:"请选择看板类型",trigger:"blur"}]
                },
                options: [],
                typeoptions:[
                    //车间看板、产线看板、品质看板、设备看板
                    {label: '车间看板', value: '车间看板'},
                    {label: '产线看板', value: '产线看板'},
                    {label: '品质看板', value: '品质看板'},
                    {label: '仓库看板', value: '仓库看板'},
                   /* {label: '设备看板', value: '设备看板'}*/
                ],
                factoryoptions:[],  //产区
            }
        },
        created() {
            //默认数据
            this.getCookies();
            //获取账套信息
            this.getMasters();
            //获取厂区信息
            this.getFactory();
        },
        mounted() {
            //监听enter键
            this.$refs.loginForm.$el.addEventListener('keydown',this.handleEnter);
        },
        beforeDestroy(){
            this.$refs.loginForm.$el.removeEventListener('keydown',this.handleEnter);
        },
        methods:{
            //获取账套
            getMasters(){
                this.$http.get("kanban/getAllMasters.action").then(
                    (result)=>{
                        var res = JSON.parse(JSON.stringify(result.data.masters));
                        for (let i = 0; i < res.length; i++) {
                            this.options.push({label: res[i].ma_function, value: res[i].ma_user});
                        }
                        //设置默认值
                        if("" == this.loginForm.sob || !result.data.masters.some(item => item.ma_function === this.loginForm.sob) ){
                            this.loginForm.sob = res[0].ma_user;
                        }
                    },(result)=>{
                        console.error(result)
                    });
            },
            getFactory(){
              this.$http.get("kanban/getFactory.action").then(
                  (result)=>{
                    var res = JSON.parse(JSON.stringify(result.data.factories));
                    for (let i = 0; i < res.length; i++) {
                      this.factoryoptions.push({label: res[i].FA_NAME, value: res[i].FA_NAME});
                    }
                    //设置默认值
                    if("" == this.loginForm.factory || !result.data.factories.some(item => item.FA_NAME === this.loginForm.factory) ){
                      this.loginForm.factory = res[0].FA_NAME;
                    }
                  },(result)=>{
                    console.error(result)
                  });
              },
            //登录操作
            submitLogin(){
                this.$refs.loginForm.validate((valid) => {
                    if (valid) {
                       // console.log('登录',this.loginForm);
                        //?username=zhongyl&password=asd&sob=N_MES_TEST
                        this.$http.get("kanban/login.action",{
                                params:{
                                    username:this.loginForm.username,
                                    password:CryptoJS.AES.encrypt(this.loginForm.password, "123456"), //密码加密传递
                                    sob:this.loginForm.sob,
                                    type:this.loginForm.type,
                                    factory:this.loginForm.factory
                                }}).then(
                            (result)=>{
                                var res = result.data;
                                if(res.success || "检测到您已登录本系统,请不要重复登录、打开空白页!" == res.reason) {
                                    this.setStoreSession(res);
                                    this.setCookieData();
                                    if(this.loginForm.type =='产线看板'){
                                        this.$router.push({path: this.redirect || '/prodline'});
                                    }else if(this.loginForm.type =='车间看板'){
                                        this.$router.push({path: this.redirect || '/shop'});
                                    }else if(this.loginForm.type =='品质看板'){
                                        this.$router.push({path: this.redirect || '/quality'});
                                    }else if(this.loginForm.type =='仓库看板'){
                                      this.$router.push({path: this.redirect || '/warehouse'});
                                    }
                                }else{
                                    this.$message.error(res.reason);
                                }
                            },(result)=>{
                                console.error(result)
                            });

                        /*this.$store.dispatch('kanban/login.action',this.form).then(() => {
                            this.$router.push({ path: this.redirect || '/' })
                        }).catch(() => {
                            this.loading = false;
                        })*/
                    } else {
                        this.$message.error('登录出错请重新输入');
                        return false;
                    }
                });


            },
            handleEnter(event){
                if(event.key === 'Enter'){
                    //处理回车键按下时间
                    this.submitLogin();
                }
            },
           setStoreSession(res){
             //登录成功返回session
             sessionStorage.setItem('x-access-token', res.token);
             sessionStorage.setItem('username',this.loginForm.username);
             sessionStorage.setItem('password',CryptoJS.AES.encrypt(this.loginForm.password, "123456"));
             sessionStorage.setItem('sob',this.loginForm.sob);
             this.$store.commit('setUser',this.loginForm);
             this.$store.commit('setFactoryOptions',this.factoryoptions);
             this.$store.commit('setFactory',this.loginForm.factory);
           },
            setCookieData(){
                if (this.checked) {
                    this.$cookie.set(
                        "password",
                        CryptoJS.AES.encrypt(this.loginForm.password, "123456"),
                        {
                            expires: 30
                        }
                    );
                } else {
                    this.$cookie.remove("password");
                }
                this.$cookie.set("username", this.loginForm.username, {
                    expires: 30,
                });
                this.$cookie.set("sob", this.loginForm.sob, {
                    expires: 30,
                });
                this.$cookie.set("type", this.loginForm.type, {
                    expires: 30,
                });
                this.$cookie.set("checked", this.checked, {
                    expires: 30,
                });
                this.$cookie.set("factory", this.loginForm.factory, {
                  expires: 30,
                });
            },
            getCookies(){
                if(this.$cookie.get("sob")) {
                    this.loginForm.sob = this.$cookie.get("sob");
                }
                this.loginForm.username = this.$cookie.get("username");
                if (this.$cookie.get("password")) {
                    this.loginForm.password = CryptoJS.AES.decrypt(
                        this.$cookie.get("password"),
                        "123456"
                    ).toString(CryptoJS.enc.Utf8);
                }
                if(this.$cookie.get("type")) {
                    this.loginForm.type = this.$cookie.get("type");
                }
                if(this.$cookie.get("checked")) {
                    if(this.$cookie.get("checked") == 'false') {
                        this.checked = false;
                    }
                }
                if(this.$cookie.get("factory")) {
                  this.loginForm.factory = this.$cookie.get("factory");
                }
            }
        },
    };
</script>

<style lang="less" scoped>
    .loginContainer{
        border-radius: 15px;
        background-clip: padding-box;
        margin: 120px auto;
        width: 350px;
        padding: 15px 35px 15px 35px;
        background: aliceblue;
        border:1px solid blueviolet;
        box-shadow: 0 0 25px #f885ff;
    }
    .loginTitle{
        margin: 0px auto 35px auto;
        text-align: center;
        font-size: 24px;
    }
    .loginRemember{
        text-align: left;
        margin: 0px 0px 15px 0px;
    }
    .bg {
        width: 100%;
        height: 100%;
        background-image: url("../assets/pageBg.png");
        background-size: cover;
        background-position: center center;
    }
    /*body{
        background-image: url("../assets/pageBg.png");
        background-size:100%;
    }*/
</style>

