<template>
    <div class="body">
        <van-swipe class="my-swipe" :autoplay="3000" :height="200" indicator-color="white">
            <van-swipe-item v-for="(item, index) in images" :key="index" class="swipe-img">
                <img :src="item"/>
            </van-swipe-item>
        </van-swipe>
        <van-grid :column-num="3">
            <van-grid-item v-for="(item,index) in routers" :key="index" :icon="item.icon" :text="item.name" 
            :info="(item.name=='消息记录'&&unreadNum>0)?unreadNum:''"
            :to="item.url">
            </van-grid-item>
        </van-grid>
        <div class="tip"  v-if="isCorpWX">
            工时报表统计等更多功能，请从PC端企业微信进入
        </div>
        <div class="tip"  v-if="!isCorpWX">
            体验报表统计等更多功能，尽在PC端<br>
            网页用户访问http://worktime.ttkuaiban.com，钉钉用户直接从钉钉PC端进入工时管家
        </div>
        <Footer page="index"></Footer>
    </div>
</template>
<script>
    import Footer from "@/components/Footer";
    export default {
        data() {
            return {
                isCorpWX:false,
                isWX:false,
                user: JSON.parse(localStorage.userInfo),
                unreadNum:0,
                images: [
                    // require('../../assets/img/index/banner_1.png'),
                    require('../../assets/img/index/banner4.jpeg'),
                    // require('../../assets/img/index/banner_3.png'),
                ],
                routers: [],
            };
        },
        created() {
        },
        mounted() {
            // if(this.user.companyName == '比基尼小镇'){
            //     let consoleScript = document.createElement("script");
            //     consoleScript.src = "https://cdn.bootcss.com/vConsole/3.3.4/vconsole.min.js";
            //     consoleScript.onload = function () {
            //         new VConsole()
            //     }
            //     document.head.appendChild(consoleScript);
            // }
            // console.log('userNameNeedTranslate',window.location.href);
            if(this.user.userNameNeedTranslate == '1'){
                this.agentConfig()
            }
            var ua = navigator.userAgent.toLowerCase();
            if (ua.indexOf("wxwork") > 0) {
                this.isCorpWX = true;
            } else if (ua.indexOf("micromessenger") > 0) {
                this.isWX = true;
            }

            if (this.user.company.packageEngineering == 1) {
                this.routers.push(
                {
                    name: '专业审核',
                    url: '/profession_review',
                    icon: 'todo-list-o'
                });
            }
            var list = this.user.moduleList
            for (var i in list) {
                if(list[i].name == '工时报告') {
                    this.routers.push({name: '查看日报',url: '/calendar',icon: 'description'})
                    this.routers.push({name: '填写日报',url: '/edit',icon: 'edit'})
                    // if (this.user.companyId == 817 || this.user.companyId == 7 || this.user.companyId == 10) {
                        this.routers.push({name: '按周填报',url: '/weekEdit',icon: 'records'})
                    // }
                }
                if(list[i].name == '项目报告审核') {
                    this.routers.push({name: '项目报告审核',url: '/review',icon: 'todo-list-o'})
                }
                if(list[i].name == '项目管理') {
                    this.routers.push({name: '项目管理',url: '/project',icon: 'label-o'})
                }
                if(list[i].name == '导入日报审核') {
                    this.routers.push({name: '导入日报审核',url: '/audit',icon: 'label-o'})
                }
            }
            if (this.user.manageDeptId != 0 && this.user.company.packageEngineering == 1) {
                this.routers.push(
                {
                    name: '部门审核',
                    url: '/department_review',
                    icon: 'todo-list-o'
                });
            }
            
            this.routers.push({
                                name: '消息记录',
                                url: '/msg',
                                icon: 'todo-list-o',
                                info: this.unreadNum
                            });
            this.getMessage();
            this.bindIfNessary();
            if (localStorage.userInfo != null) {
                this.getAccountInfo();
            }
            
            this.getMessage();
            this.bindIfNessary();
            if (localStorage.userInfo != null) {
                this.getAccountInfo();
            }
            
            
        },
        components: {
            Footer
        },
        methods: {
            // 获取企业微信参数
            agentConfig(){
                let curUrl = window.location.href.split('#')[0]
                this.$axios.post('/wxcorp/getCorpWXConfig',{
                    url: curUrl,
                    token: this.user.id
                }).then(res => {
                    if(res.code == 'ok'){
                        wx.config({
                            beta: true,
                            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                            appId: res.data.appid, // 必填，公众号的唯一标识 
                            timestamp: res.data.timestamp, // 必填，生成签名的时间戳 
                            nonceStr: res.data.noncestr, // 必填，生成签名的随机串 
                            signature: res.data.sign, // 必填，签名，见附录1 
                            jsApiList: ['chooseImage','previewImage','uploadImage','downloadImage','previewFile','getLocation','agentConfig'] 
                        })
                        let that = this
                        wx.ready(function(){
                        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
                            that.$axios.post('/wxcorp/getCorpWXAgentConfig', {
                                url: curUrl,
                                token: that.user.id
                            }).then(res => {
                                if(res.code == 'ok'){
                                    wx.agentConfig({
                                        corpid: res.data.corpid, // 必填，企业微信的corpid，必须与当前登录的企业一致
                                        agentid: res.data.agentid, // 必填，企业微信的应用id （e.g. 1000247）
                                        timestamp: res.data.timestamp, // 必填，生成签名的时间戳
                                        nonceStr: res.data.nonceStr, // 必填，生成签名的随机串
                                        signature: res.data.signature, // 必填，签名，见附录-JS-SDK使用权限签名算法
                                        jsApiList: ['selectExternalContact'], //必填，传入需要使用的接口名称
                                        success: function (result) {
                                            // console.log(result, '请求微信成功')
                                            // console.log(window, 'window')
                                            //  wx.agentConfig成功回调后，WWOpenData 才会注入到 window 对象上面
                                            window.WWOpenData.bind(document.querySelector('ww-open-data'))
                                        },
                                        fail: function (res) {
                                            // console.log('查看错误信息', res)
                                            if (res.errMsg.indexOf('function not exist') > -1) {
                                                alert('版本过低请升级')
                                            }
                                        },
                                    })
                                }
                            }).catch(err => {
                                if (err.errMsg.indexOf('function not exist') > -1) {
                                    alert('版本过低请升级')
                                }
                            })
                        });
                    }
                }).catch(err => {

                })
            },

            //获取账户信息
            getAccountInfo() {
                this.$axios.get('/user/loginByUserId', {params:{userId: this.user.id}})
                            .then(res => {
                                // console.log(res);
                                if (res.code == 'error') {
                                    localStorage.errorMsg = res.msg;
                                    //账号信息有问题，不能使用。
                                    this.$router.push("/error");
                                } else {
                                    
                                    localStorage.userInfo = JSON.stringify(res.data);
                                    this.user = res.data;
                                } 
                            }).catch(err=> {
                                alert('err=' + err);
                            });
            },
            bindIfNessary() {
                let href = window.location.href;
                var requestUrl = "";
                if (this.isCorpWX && (this.user.corpwxUserid == null|| this.user.corpwxUserid == undefined || this.user.corpwxUserid == 'undefined')) {//优先检查企业微信环境
                    requestUrl = "/wxcorp/bindCorpWeiXin";
                } else if (this.isWX && (this.user.wxOpenid == null || this.user.wxOpenid == undefined || this.user.wxOpenid == 'undefined')) {
                    requestUrl = "/wechat/bindWeiXin";
                } 
                
                if (requestUrl.length > 0) {
                    // 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);
                        // window.location = urlLeft + "#/home" + urlRight;//拼接跳转
                        //获取code
                        var code = urlRight.substring('?code='.length,urlRight.indexOf('#/index'));
                        if (code.indexOf('&state=1') > 0) {
                            code = code.substring(0, code.indexOf('&state=1'));
                        }

                        //调用后台接口，注册用户
                        // console.log('获取到code=='+code);

                        this.$axios.get(requestUrl, {params:{code:code, userId: this.user.id}})
                            .then(res => {
                                // console.log(res);
                                if (res == null) {
                                    this.$toast.fail('绑定失败');
                                } 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;
                                        window.location.href = '/#/my/center';
                                    }
                                }
                            }).catch(err=> {
                                alert('err=' + err);
                            });
                    }
                }
            },
            //获取消息
            getMessage() {
                this.$axios.post("/information/list", {
                })
                .then(res => {
                    if(res.code == "ok") {
                        var list = res.data;
                        this.unreadNum = list.filter(l=>l.checked==0).length;
                        // console.log(this.unreadNum);
                        
                    } 
                }).catch(err=> {this.$toast.clear();});
            },
        },
        activated(){
            this.getMessage()
        }
    };
</script>

<style lang="less" scoped>
    .swipe-img {
        img {
            width: 100%;
            height: 100%;
        }
    }

    .body {
        height: calc(100vh - 50px);
        position: relative;
    }

    .tip {
        position: absolute;
        width: 100%;
        bottom: 5px;
        font-size: 14px;
        color: #8f8f8f;
        margin-top: 20px;
        text-align: center;
        line-height: 20px;
    }
</style>
