<template>
    <div>
        <div class="login" v-if="!bindingqywx">
            <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">{{ $t('workingHoursHousekeeper') }}</h3>
                    <el-form-item class="login-input" prop="username">
                        <el-input type="text" v-model="ruleForm.username" autocomplete="off" :placeholder="$t('zhang-hao-shou-ji-hao')" 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="$t('mi-ma')" 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">{{ $t('login') }}</el-button>
                    </el-form-item>
                    <div class="additional" v-if="wxHrefFlg">
                        <el-divider content-position="center">或</el-divider>
                    </div>
                    <div class="externalLanding" v-if="wxHrefFlg">
                        <div class="externalLanding_img" @click="wxworkCli()">
                            <img src="../assets/image/qiyeweix.png" alt="">
                        </div>
                    </div>
                    <div class="toRegister">
                        <el-link type="primary" class="btn" style="float:left;" :underline="false">{{ $t('lian-xi-ke-fu') }}
                            <div class="service">
                                <p style="color: #333">{{ $t('sao-ma-jia-ke-fu-wei-xin') }}</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">
                            {{ $t('shi-yong-shuo-ming') }} </el-link>
                        <el-link type="primary" v-if="!isCorpWX" @click="jumpTo" :underline="false">{{ $t('qi-ye-zhu-ce') }}</el-link>
                    </div>
                </el-form>
            </div>
            <el-dialog :title="$t('shi-yong-shuo-ming')" :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>
            <el-dialog title="企业微信扫码登陆" :visible.sync="wxworkFlg" width="500px">
                <div>
                    <div id="wxcode"></div>
                </div>
            </el-dialog>
        </div>
        <!-- 绑定企业微信的话显示这个 -->
        <div class="qiweix" v-if="bindingqywx">
            正在进入系统...
        </div>
    </div>
</template>

<script>
    import * as dd from 'dingtalk-jsapi';
    import "../permissions.js"
    import WxLogin from "../assets/js/wwLogin.js"
    export default {
        inject:['reloads'],
        data() {
            return {
                isCorpWX: false,
                dialogVisible: false,
                logining: false,
                // 登录信息
                ruleForm: {
                    username: '',
                    password: ''
                },
                rules: {
                    username: [{ required: true, message: this.$t('peaseenterthe'), trigger: 'blur' },],
                    password: [{ required: true, message: this.$t('peaseenterthe'), trigger: 'blur' },]
                },
                wxworkFlg: false,
                bindingqywx: false,

                wxHrefFlg: false
            };
        },
        watch: {
            $route(to) {
				if (to.query.code) {
					this.getStaffInfo(to.query.code)
				}
			}
        },
        created() {
            // this.langChange()
            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)
            }
            // 用户绑定了企业微信 和 飞书
            if(windowHerf.indexOf('userId') != '-1' || windowHerf.indexOf('appId') != '-1') {
                this.bindingqywx = true
            }
        },
        mounted() {
            // this.wxworkCli()
            var ua = navigator.userAgent.toLowerCase();
            console.log(ua, '打印出来')
            if (ua.indexOf("wxwork") > 0) {
                this.isCorpWX = true;
            } 
            let href = window.location.href;
            this.wxHrefFlg = href.indexOf('//worktime.ttkuaiban.com') != '-1'
            if (this.isCorpWX) {
                //企业微信环境下，尝试自动登录
                //判断企业微信，是否存在授权
                //尝试自动登录
                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('#/'));
                    }
                    if (loginUserId.includes('&')) {
                        loginUserId = loginUserId.substring(0, loginUserId.indexOf('&'));
                    }
                    var path = null;
                    if (href.indexOf('path') > 0) {
                        path = href.split('path=')[1].split('&')[0];
                    }
                    this.loginByUserId(loginUserId, path);
                } else {
                    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 {
                                //没有授权任何模块，需要提示用户
                                alert('无权访问，请联系管理员为您分配权限');
                            }
                        }
                    } else if (href.indexOf('errorMsg=') > 0) {
                        var errorMsg = href.split('errorMsg=')[1].split('#')[0];
                        errorMsg = decodeURI(errorMsg);
                        this.$message({
                            message: errorMsg,
                            type: 'error'
                        });
                    }
                }
            } 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('#/'));
                    }
                    if (loginUserId.includes('&')) {
                        loginUserId = loginUserId.substring(0, loginUserId.indexOf('&'));
                    }
                    var path = null;
                    if (href.indexOf('path') > 0) {
                        path = href.split('path=')[1].split('&')[0];
                    }
                    this.loginByUserId(loginUserId, path);
                } else 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 {
                            //没有授权任何模块，需要提示用户
                            alert('无权访问，请联系管理员为您分配权限');
                        }
                    }
                } else {
                    if(href.indexOf("corpid") > 0) {
                        // 钉钉登陆
                        //检查环境，如果是钉钉有$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);
                                    }});
                            });
                        } 
                    } else {
                        // 飞书登陆
                        if(href.indexOf("appId") > 0) {
                            console.log('执行到这里---飞书')
                            let arr = href.split('appId=')[1]
                            let str = arr.split('#')[0]
                            console.log(str, window)
                            window.h5sdk.ready(() => { // ready方法不需要每次都调用
                                tt.requestAuthCode({
                                appId: str,
                                success: (info) => {
                                    console.info(info.code, '飞书 code')
                                    this.flyingBook(str, info.code)
                                },
                                fail: (error) => {
                                    console.error(error)
                                }
                                });
                            });
                        }
                    }
                }
            }
            
            let urls = window.location.href
            console.log(urls, '连接')
            if(urls.indexOf('english=1') != '-1' && localStorage.getItem('lang') != 'en') {
                this.setlangChange()
                location.reload()
            } 
            if(urls.indexOf('english=1') == '-1' && localStorage.getItem('lang') != 'zh') {
                localStorage.setItem("lang", 'zh')
                location.reload()
            }
        },
        methods: {
            wxworkCli() {
                // this.wxworkFlg = true
                // this.$nextTick(()=>{
                //     var obj = new WxLogin({
                //         id: 'wxcode', // 登录页面显示二维码的容器id
                //         appid: 'wwf11426cf618e1703', // 企业微信的CorpID，在企业微信管理端查看
                //         redirect_uri: encodeURIComponent('http://localhost:10086/#/login'), // 重定向的地址，需要进行encode
                //         usertype: 'member'
                //     })
                // })
                var appId = "wwf11426cf618e1703";//企业微信第三方的SUIT ID
                var url = "https://worktime.ttkuaiban.com/api/corpWXScanningAuth";//授权回调页面
                var weixinUrl=`https://open.work.weixin.qq.com/wwopen/sso/3rd_qrConnect?appid=${appId}&redirect_uri=${url}&state=0&usertype=member`;
                window.location.href = weixinUrl;
            },
            getStaffInfo() {
                console.log('执行了没')
            },
            setlangChange() {
                localStorage.setItem("lang", 'en')
            },
            langChange() {
                let jsSrc =(navigator.language || navigator.browserLanguage).toLowerCase();
                let str =  localStorage.getItem("lang")
                if(jsSrc.indexOf('zh')!=-1){
                    // 浏览器语言是中文
                    localStorage.setItem("lang", 'zh')
                    // localStorage.setItem("lang", 'en')
                } else {
                    // 浏览器语言是英文
                    localStorage.setItem("lang", 'en')
                    // localStorage.setItem("lang", 'zh')
                }
                if(str != localStorage.getItem("lang")) {
                    // this.reloads()
                    location.reload()
                }
                console.log(str, localStorage.getItem("lang"))
            },
            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 = "https://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, path) {
                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) {
                                    if (path) {
                                        var action = '';
                                        //url上传来的格式
                                        if (path.includes('projectInside')) {
                                            //跳转进入项目的任务看板
                                            path = decodeURIComponent(path);
                                            console.log('pppp='+path);
                                            if (path.includes('@adjustBudget-')) {
                                                //需要打开分组预估工时设置
                                                action = path.split('@')[1];
                                                path = path.split('@')[0];
                                            }
                                        }
                                        console.log('action==='+action);
                                        sessionStorage.action = action
                                        this.$router.push({ path: path})
                                    } else {
                                        this.$router.push({ path: user.moduleList[0].path })
                                    }
                                    if (!path) {
                                        path = user.moduleList[0].path;
                                    }
                                    //去掉链接上存在的参数
                                    if (location.href.indexOf("?")>0) {
                                        var newHref = location.href.split("?")[0] + '#' + (path.indexOf('/')>-1?path:('/'+path));
                                        location.href = newHref;
                                    }
                                } else {
                                    //没有授权任何模块，需要提示用户
                                    alert('无权访问，请联系管理员为您分配权限');
                                }
                            } 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 {
                                    //没有授权任何模块，需要提示用户
                                    alert('无权访问，请联系管理员为您分配权限');
                                }
                            } 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") {
                                if(res.data.moduleList.length == 0){
                                    this.$message({
                                        message: this.$t('qing-lian-xi-guan-li-yuan-wei')+'\u3000' + res.data.roleName + '\u3000'+this.$t('assignpermissions'),
                                        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;
                                // if(res.msg.indexOf('到期') != -1){
                                
                                // this.$router.push({ path: '/expire', query:{datetext:'2022.11.24',ddd: '111'}})
                                // console.log('到期skip');
                                // return
                                // }
                                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: this.$t('qing-lian-xi-guan-li-yuan-wei')+'\u3000' + res.data.roleName + '\u3000'+this.$t('assignpermissions'),
                                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 {
                                //没有授权任何模块，需要提示用户
                                alert('无权访问，请联系管理员为您分配权限');
                            }
                        }
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    this.$message({
                        message: error,
                        type: 'error'
                    });
                })
            },
            // 飞书登陆
            flyingBook(appid, code) {
                this.http.post('/feishu-info/loginByFeishu', {
                    appId: appid,
                    code: code
                } , res => {
                    console.log(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 {
                            //没有授权任何模块，需要提示用户
                            alert('无权访问，请联系管理员为您分配权限');
                        }
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        });
                    }
                }, error => {
                    console.log(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>
    .qiweix {
        width: 100%;
        display: flex;
        justify-content: center;
        padding: 50px 0;
        font-size: 40px;
        color: #505458;
    }
    .additional {
        width: 100%;
        text-align: center;
        padding: 20px 0;
        color: #505458;
    }
    .externalLanding {
        width: 100%;
        display: flex;
        justify-content: center;
        .externalLanding_img {
            width: 30px;
            height: 30px;
            border: 1px solid #409EFF;
            border-radius: 50%;
            position: relative;
            overflow: hidden;
            cursor: pointer;
            display: flex;
            justify-content: center;
            align-items: center;
            img {
                width: 80%;
                height: 80%;
            }
        }
    }
    .login {
        height: 100%;
        .login-par {
            width: 100%;
            // min-height: 100%;
            height: 100vh;
            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>