<template>
    <div class="login">
        <div class="login-par">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-position="left" label-width="0px" class="demo-ruleForm login-container">
                <div class="login-logo">
                    <img src="../assets/image/login_logo.png" style="width:80px;height:80px;"/>
                </div>
                <h3 class="title">工时管家</h3>
                <el-form-item class="login-input" prop="username">
                    <el-input type="text" v-model="ruleForm.username" autocomplete="off" placeholder="账号/手机号" clearable prefix-icon="el-icon-user-solid"></el-input>
                </el-form-item>
                <el-form-item class="login-input" prop="password">
                    <el-input type="password" v-model="ruleForm.password" @keyup.enter.native="handleSubmit" autocomplete="off" placeholder="密码" show-password prefix-icon="el-icon-lock"></el-input>
                </el-form-item>
                <el-form-item class="login-button" style="width:100%;">
                    <el-button type="primary" style="width:100%;" @click.native.prevent="handleSubmit" :loading="logining">登录</el-button>
                </el-form-item>
                <div class="toRegister">
                    <el-link type="primary" class="btn" style="float:left;" :underline="false">联系客服
                        <div class="service">
                            <p style="color: #333">扫码加客服微信</p>
                            <img src="../assets/image/code.jpg">
                            <p><span style="color: #333">QQ：</span><span id="QQ">3052894409</span></p>
                        </div>
                    </el-link>
                    <el-link type="primary" style="margin-right:5px;" @click="dialogVisible=true" :underline="false">
                        使用说明
                    </el-link>
                    <el-link type="primary" v-if="!isCorpWX" @click="jumpTo" :underline="false">企业注册</el-link>
                </div>
            </el-form>
        </div>
        <el-dialog title="使用说明" :visible.sync="dialogVisible" width="500px">
            <p><a style="color:#409EFF;text-decoration:none" href="upload/工时管家使用说明_基础版.docx" download="工时管家使用说明_基础版.docx" 
                        target="_blank">工时管家使用说明_基础版.docx</a></p>
            <p><a style="color:#409EFF;text-decoration:none" href="upload/工时管家使用说明_项目管理专业版.docx" download="工时管家使用说明_项目管理专业版.docx" 
                        target="_blank">工时管家使用说明_项目管理专业版.docx</a></p>
            <p><a style="color:#409EFF;text-decoration:none" href="upload/工时管家使用说明_建筑工程专业版.docx" download="工时管家使用说明_建筑工程专业版.docx" 
                        target="_blank">工时管家使用说明_建筑工程专业版.docx</a></p>
            <!-- <p><a style="color:#409EFF;text-decoration:none" href="upload/工时管家使用说明_项目经理.docx" download="工时管家使用说明_项目经理.docx" 
                        target="_blank">工时管家使用说明_项目经理.docx</a></p>
            <p><a style="color:#409EFF;text-decoration:none" href="upload/工时管家使用说明_普通员工.docx" download="工时管家使用说明_普通员工.docx" 
                        target="_blank">工时管家使用说明_普通员工.docx</a></p> -->
            
        </el-dialog>
    </div>
</template>

<script>
    import * as dd from 'dingtalk-jsapi';
    import "../permissions.js"
    export default {
        data() {
            return {
                isCorpWX: false,
                dialogVisible: false,
                logining: false,
                // 登录信息
                ruleForm: {
                    username: '',
                    password: ''
                },
                rules: {
                    username: [{ required: true, message: '请输入账号/手机号', trigger: 'blur' },],
                    password: [{ required: true, message: '请输入密码', trigger: 'blur' },]
                }
            };
        },
        created() {
            if (localStorage.userInfo != null) {
                var user = JSON.parse(localStorage.userInfo);
                if(user.moduleList.length > 0) {
                    this.$router.push({ path: user.moduleList[0].path })
                }
            }
            let windowHerf = window.location.href
            if(windowHerf.indexOf('?jobNumber') != '-1') {
                let jobNumber = windowHerf.split('jobNumber=')[1].split('&token=')[0]
                let token = windowHerf.split('&token=')[1]
                this.automaticLogin(jobNumber, token)
            }
        },
        mounted() {
            var ua = navigator.userAgent.toLowerCase();
            if (ua.indexOf("wxwork") > 0) {
                this.isCorpWX = true;
            } 
            if (localStorage.userInfo != null) {
                var user = JSON.parse(localStorage.userInfo);
                if (user.company.packageSimple == 1) {
                    //简易模式，直接进入工时统计表
                    this.$router.push({ path: '/simple' });
                } else {
                    if(user.moduleList.length > 0) {
                        this.$router.push({ path: user.moduleList[0].path })
                    }
                }
            } else {
                if (this.isCorpWX) {
                    //企业微信环境下，尝试自动登录
                    let href = window.location.href;
                    //判断企业微信，是否存在授权
                    //尝试自动登录
                    if (href.indexOf('hasTriedAutoLogin') == -1) {
                        this.tryAutoLogin();
                    } else if (href.indexOf("userId") > 0) {
                        //后台经过验证后，重定向过来带上了userId
                        var loginUserId = href.substring(href.indexOf("userId=")+"userId=".length);
                        if (loginUserId.includes('#/')) {
                            loginUserId = loginUserId.substring(0, loginUserId.indexOf('#/'));
                        }
                        this.loginByUserId(loginUserId);
                    }
                } else {
                    //检查环境，如果是钉钉有$CORPID$
                    var key = '?corpid=';
                    var jumpkey = '&jumpto=';
                    var url = location.href;
                    console.log('jumpto',location);
                    // var url = "https://worktime.ttkuaiban.com/?corpid=$CORPID$&jumpto=/info/21#/index"
                    var that = this;
                    if (url.indexOf(key) > 0) {
                        var corpId = ''
                        var jumpurl = ''
                        if(url.indexOf(jumpkey) > 0){
                            corpId = url.substring(url.indexOf(key)+key.length,url.indexOf(jumpkey));
                            jumpurl = url.substring(url.indexOf(jumpkey)+jumpkey.length,url.indexOf('#'));
                        }else{
                            corpId = url.substring(url.indexOf(key)+key.length,url.indexOf('#'));
                        }
                        dd.ready(function() {
                            that.isDingchg()
                            dd.runtime.permission.requestAuthCode({
                                corpId: corpId, // 企业id
                                onSuccess: function (info) {
                                    var code = info.code // 通过该免登授权码可以获取用户身份
                                    that.loginByCode(code, corpId, jumpurl);
                                }});
                        });
                    } 
                }
            }
        },
        methods: {
            isDingchg() {
                this.$store.commit('isDingFun')
            },
             bindIfNessary() {
                let href = window.location.href;
                
                if (this.isCorpWX) {
                    // localStorage.openId = 'o1L3L5lOrOl3_UEJjONaoT2Rne1I';
                    //会自动跳转到首页
                    // let href = 'http://hq.tangusoft.com/?code=011Ptjgc2rx1eI09Irgc2Rvsgc2PtjgF&state=1#/index';
                    
                    if (href.includes("com/?code")) {  //url包括 com/?code 证明为从微信跳转回来的
                        var url = href; //vue自动在末尾加了 #/ 符号，截取去掉
                        var jingPosit = url.indexOf("com/") + 4; //获取域名结束的位置

                        // var urlLeft = url.substring(0, jingPosit);//url左侧部分
                        var urlRight = url.substring(jingPosit, url.length); //url右侧部分
                        console.log('urlRight=' + urlRight);
                        urlRight = urlRight.substring(0, urlRight.indexOf('#/'));
                        // window.location = urlLeft + "#/home" + urlRight;//拼接跳转
                        //获取code
                        var code = urlRight.substring('?code='.length,urlRight.indexOf('&state='));
                        var passUserId = urlRight.substring(urlRight.indexOf('&state=')+'&state='.length);
                        if (passUserId == '1') {
                            //自动登录的回调
                            this.$axios.get('/wxcorp/corpWeiXinLogin', {params:{code:code}})
                            .then(res => {
                                if (res == null) {
                                    
                                } else if(res.errcode != null) {
                                    //报错了
                                    console.log(res.errmsg);
                                } else {
                                    //获取openId
                                    if (res.data != null && ((this.isWX && res.data.wxOpenid != undefined)
                                                || (this.isCorpWX && res.data.corpwxUserid != undefined))) {
                                        localStorage.userInfo = JSON.stringify(res.data);
                                        console.log('登录成功');
                                        this.user = res.data;
                                        this.permissionsList(res.data)
                                        window.location.href = '/#/index';
                                    }
                                }
                            }).catch(err=> {
                                alert('err=' + err);
                            });
                        } else {
                        }
                        
                    } 
                }
            },
            tryAutoLogin() {
                var appId = "ww4e237fd6abb635af";//企业微信第三方的SUIT ID
                var url = "http://worktime.ttkuaiban.com/api/corpWXAuth";//授权回调页面
                var weixinUrl="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+encodeURI(url)+"&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
                window.location.href = weixinUrl;
            },
            loginByUserId(userId) {
                this.http.post("/user/loginByUserId", {userId:userId} , res => {
                            if (res.code == "ok") {
                                var user = res.data;
                                localStorage.user = JSON.stringify(res.data);
                                sessionStorage.setItem('user', JSON.stringify(res.data));
                                this.permissionsList(res.data)
                                if(user.moduleList.length > 0) {
                                    this.$router.push({ path: user.moduleList[0].path })
                                }
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                                
                            }
                        }, error => {
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
            },
            loginByCode(code, corpId, jumpurl) {
                this.http.post("/dingding/getUserByCode", {code:code, corpid:corpId} , res => {
                            if (res.code == "ok") {
                                var user = res.data;
                                localStorage.user = JSON.stringify(res.data);
                                sessionStorage.setItem('user', JSON.stringify(res.data));
                                this.permissionsList(res.data)
                                if(jumpurl){
                                    this.$router.push({ path: jumpurl })
                                }else if(user.moduleList.length > 0) {
                                    this.$router.push({ path: user.moduleList[0].path })
                                }
                            } else {
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        }, error => {
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
            },

            handleReset2() {
                this.$refs.ruleForm.resetFields();
            },

            jumpTo() {
                this.$router.push({ path: '/register' });
            },

            handleSubmit(ev) {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        var _this = this;
                        this.logining = true;
                        setTimeout(function () {
                            _this.logining = false;
                            console.log('执行')
                        }, 15000);
                        this.http.post(this.port.manage.login, this.ruleForm , res => {
                            this.logining = false;
                            if (res.code == "ok") {
                                console.log('执行')
                                if(res.data.moduleList.length == 0){
                                    this.$message({
                                        message: '请联系管理员为\u3000' + res.data.roleName + '\u3000分配权限',
                                        type: 'error'
                                    })
                                    return
                                }
                                var user = res.data;
                                sessionStorage.setItem('user', JSON.stringify(res.data));
                                this.permissionsList(res.data)
                                if (user.company.packageSimple == 1) {
                                    //简易模式，直接进入工时统计表
                                    this.$router.push({ path: '/simple' });
                                    sessionStorage.setItem('autoRoute','/simple')
                                } else {
                                    if(user.moduleList.length > 0) {
                                        this.$router.push({ path: user.moduleList[0].path })
                                        sessionStorage.setItem('autoRoute',user.moduleList[0].path)
                                    }
                                }
                            } else {
                                this.logining = false;
                                this.$message({
                                    message: res.msg,
                                    type: 'error'
                                });
                            }
                        }, error => {
                            console.log('执行1')
                            this.logining = false;
                            this.$message({
                                message: error,
                                type: 'error'
                            });
                        })
                    }
                });
            },
            // 米莱得用工号登录
            automaticLogin(jobNumber, token) {
                this.http.post('/user/loginAdminByThirdParty', {
                    jobNumber: jobNumber,
                    token: token
                } , res => {
                    if (res.code == "ok") {
                        if(res.data.moduleList.length == 0){
                            this.$message({
                                message: '请联系管理员为\u3000' + res.data.roleName + '\u3000分配权限',
                                type: 'error'
                            })
                            return
                        }
                        var user = res.data;
                        sessionStorage.setItem('user', JSON.stringify(res.data));
                        this.permissionsList(res.data)
                        if (user.company.packageSimple == 1) {
                            //简易模式，直接进入工时统计表
                            this.$router.push({ path: '/simple' });
                            sessionStorage.setItem('autoRoute','/simple')
                        } else {
                            if(user.moduleList.length > 0) {
                                this.$router.push({ path: user.moduleList[0].path })
                                sessionStorage.setItem('autoRoute',user.moduleList[0].path)
                            }
                        }
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },
            // 权限控制
            permissionsList(item) {
                var arr = []
                var ss = item.functionList
                for(var i in ss) {
                    arr.push(ss[i].name)
                }
                var ssAkl = this.StringUtil.permissions(arr)
                sessionStorage.setItem('permissions', JSON.stringify(ssAkl));
                // console.log(ssAkl, '返回过来的数据原--------')
            },
        },
    }
</script>

<style lang="scss" scoped>
    .login {
        height: 100%;
        .login-par {
            width: 100%;
            min-height: 100%;
            background: #f0f2f5 url('../assets/image/background.png') no-repeat 50%;
            background-size: 100%;
            padding: 110px 0 144px;
            position: relative;
            box-sizing: border-box;
            .login-logo {
                text-align: center;
                margin: 0 0 20px 0;
            }
            .login-container {
                -webkit-border-radius: 5px;
                border-radius: 5px;
                -moz-border-radius: 5px;
                background-clip: padding-box;
                width: 315px;
                height: 380px;
                padding: 25px 35px 25px 35px;
                background: #fff;
                border: 1px solid #eaeaea;
                box-shadow: 0 0 5px #cac6c6;
                border-top: 10px solid #20a0ff;
                margin:auto;
                .title {
                    font-size: 20px;
                    margin: 0px auto 40px auto;
                    text-align: center;
                    color: #505458;
                }
                .remember {
                    margin: 0px 0px 35px 0px;
                }
                .login-input {
                    margin: 30px 0 0 0;
                }
                .login-button {
                    margin: 30px 0 0 0;
                }
                .login-button .el-button {
                    padding: 14px;
                }
            }
        }
    }

    .toRegister {
        margin: 15px 0;
        text-align: right;
        position: relative;

        .service {
            display: none;
            width: 120px;
            position: absolute;
            background: #fff;
            text-align: center;
            padding: 10px;
            left: -30px;
            top: -210px;
            border-radius: 5px;
            box-shadow: 3px 3px 10px #dfdfdf;
            img {
                width: 80px;
            }
        }
    }

    .btn:hover .service {
        display: block;
    }
</style>