const _Http = getApp().globalData.http;
let DataCarousel = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        site: getApp().globalData.site,
        bannerList: [], //banner列表
        user: {},
        annunciateList: [], //通告列表
        gridList: [],
        unreadNum: 0, //通告未读
        notice: "",
        msgCount: 1,
        subassembly: [], //首页部件
        msgList: [], //消息列表
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.refreshData() //更新权限等信息
        this.setData({ //获取胶囊位置信息
            capsule: wx.getMenuButtonBoundingClientRect()
        })
    },
    /* 更新站点信息 */
    refreshData() {
        this.setData({
            user: wx.getStorageSync('userMsg')
        })
        /* 首页宫格授权查询 */
        if (wx.getStorageSync('userauth').length != 0) {
            let auth = getApp().globalData.queryPer.query(wx.getStorageSync('userauth'), ['营销工具'], ['通告', '推广素材', '商学院', '提报', '销售线索', '营销物料', '销售预测', '销售目标']),
                gridList = [],
                subassembly = [];
            auth.forEach(v => {
                switch (v.systemmodulename) {
                    case "通告":
                        gridList.push({
                            name: "通告",
                            path: "/pages/annunciate/index",
                            icon: "icon-a-shouyejingangqutonggao",
                            apps: v.apps
                        });
                        if (v.apps[0].meta.wedgits.some(value => value.wedgit == 'homenoticelist')) subassembly.push('homenoticelist');
                        this.setData({
                            annunciateAuthList: v.apps[0].meta.auth.map(v => v.optionname)
                        });
                        break;
                    case "推广素材":
                        gridList.push({
                            name: "推广素材",
                            path: "/pages/promotional/index",
                            icon: "icon-a-shouyejingangqutuiguangsucai",
                            apps: v.apps
                        })
                        break;
                    case "商学院":
                        gridList.push({
                            name: "商学院",
                            path: "/pages/college/index",
                            icon: "icon-a-shangxueyuanxuexi",
                            apps: v.apps
                        })
                        break;
                    case "提报":
                        gridList.push({
                            name: "提报",
                            path: "/pages/submission/index",
                            icon: "icon-a-tibaoguanlitibao",
                            apps: v.apps
                        })
                        break;
                    case "营销物料":
                        gridList.push({
                            name: "营销物料",
                            path: "/pages/tabbar/smartStore/index",
                            icon: "icon-a-shouyejingangquyingxiaowuliao",
                            apps: v.apps
                        })
                        break;
                    case "销售线索":
                        gridList.push({
                            name: "销售线索",
                            path: "/pages/threadedTree/index",
                            icon: "icon-xiaoshouxiansuo",
                            apps: v.apps
                        })
                        //获取销售线索待办数量
                        setTimeout(this.getCount, 100);
                        break;
                    case "销售预测":
                        gridList.push({
                            name: "销售预测",
                            path: "/packageA/forecast/index",
                            icon: "icon-xiaochengxu_xiaoshouyuce",
                            apps: v.apps
                        })
                        break;
                    case "销售目标":
                        gridList.push({
                            name: "销售目标",
                            path: "/packageA/target/index",
                            icon: "icon-xiaochengxu_xiaoshoumubiao",
                            apps: v.apps
                        })
                        break;
                };
            });
            if (!['美大'].includes(this.data.site)) {
                gridList.push({
                    name: "联系人",
                    path: "/packageA/contacts/index",
                    icon: "icon-xiaochengxutongxunlu",
                    apps: {}
                })

                gridList.push({
                    name: "我的客户",
                    path: "/packageA/setclient/index",
                    icon: "icon-xiaochengxutongxunlu",
                    apps: {}
                })

                gridList.push({
                    name: "项目管理",
                    path: "/packageA/project/index",
                    icon: "icon-xiaochengxutongxunlu",
                    apps: {}
                })
            }
            /* 首页小组件查询 */
            try {
                let home = getApp().globalData.queryPer.query(wx.getStorageSync('userauth'), ['通用'], ['首页'])[0].apps[0].meta.wedgits;
                if (home.some(v => v.wedgit == 'homedatadisplay')) subassembly.push('homedatadisplay');
            } catch (e) {
                this.setData({
                    gridList,
                    subassembly: []
                })
            }
            this.setData({
                gridList,
                subassembly
            })
        } else {
            setTimeout(this.refreshData, 10);
            return;
        }
        /* 获取首页banner */
        let banner = wx.getStorageSync('banner_list').find(v => v.location == "index_top");
        if (banner) this.setData({
            bannerList: banner.ads
        })
        this.queryNoticeList(0); //获取通告列表
    },
    /* 销售线索待办 */
    getCount() {
        const index = this.data.gridList.findIndex(v => v.name == '销售线索');
        if (index == -1) return;
        _Http.basic({
            "classname": "saletool.orderclue.web.orderclue",
            "method": "getCount",
            "content": {
                "nocache": true,
                "status": "待跟进"
            }
        }, false).then(res => {
            if (res.data.count == 0) res.data.count = '';
            if (res.data.count > 99) res.data.count = '99+';
            try {
                this.data.gridList[index].count = res.data.count;
            } catch (e) {

            }
            this.setData({
                gridList: this.data.gridList
            })
        })
    },
    /* 查看通告详情 */
    toAnnunciateDetails(e) {
        const {
            item
        } = e.currentTarget.dataset;
        let authList = this.data.annunciateAuthList;
        wx.navigateTo({
            url: `/pages/annunciate/details?id=${item.sat_noticeid}&auth=${authList}`,
        })
    },
    /* 获取通告列表 */
    queryNoticeList(i) {
        if (i == 5) return;
        let obj = this.data.gridList.find(v => v.name == '通告');
        if (!obj || obj.apps.length == 0) return;
        _Http.basic({
            "classname": "saletool.notice.notice",
            "method": "queryNoticeList",
            "content": {
                "nocache": true,
                "pageNumber": 1,
                "pageSize": 3
            }
        }, false).then(res => {
            if (res.msg != '成功') return this.queryNoticeList(i + 1);
            this.setData({
                annunciateList: res.data,
                unreadNum: res.total - res.tips.readNum
            })
        });
    },
    /* 获取最新信息 */
    queryMessage(i = 0) {
        _Http.basic({
            "classname": "system.message.Message",
            "method": "queryMessage",
            content: {
                nocache: true,
                pageNumber: 1,
                pageSize: 5,
                pageTotal: 1,
                type: "",
                where: {}
            },
        }, false).then(res => {
            if (res.msg != '成功') return (i <= 5) ? this.queryMessage(i + 1) : wx.showToast({
                title: res.msg,
                icon: "none"
            })
            this.setData({
                msgList: res.data,
                notice: res.data[0]
            })
            if (this.data.msgList.length > 2) this.startDataCarousel();
        })
    },
    /* 开启消息轮播 */
    startDataCarousel() {
        clearInterval(DataCarousel);
        DataCarousel = setInterval(() => {
            let count = this.data.msgCount < this.data.msgList.length ? this.data.msgCount : 0;
            this.setData({
                msgCount: count + 1,
                notice: this.data.msgList[count]
            })
        }, 5000)
    },
    /* 宫格区域应用程序 */
    applications(e) {
        const {
            item
        } = e.currentTarget.dataset;
        const url = `${item.path}?auth=${JSON.stringify(item.apps)}`
        if (item.name == "营销物料") {
            wx.switchTab({
                url
            });
        } else {
            wx.navigateTo({
                url
            });
        }
    },
    /* 去消息详情 */
    toMsg(e) {
        const {
            item
        } = e.currentTarget.dataset;
        wx.navigateTo({
            url: '/pages/tabbar/message/details?id=' + item.messageid,
        })
    },
    /* 去通告 */
    toAnnunciate() {
        this.applications({
            currentTarget: {
                dataset: {
                    item: this.data.gridList.find(v => v.name == '通告')
                }
            }
        })
    },
    /* banner */
    bannerClick(e) {
        const {
            item
        } = e.currentTarget.dataset,
            hyperlink = item.hyperlink.split(":");
        if (hyperlink[0] == 'path') wx.navigateTo({
            url: hyperlink[1]
        })
    },
    onShow() {
        this.getTabBar().init();
        if (this.data.msgList.length > 2) this.startDataCarousel();
        this.getCount(); //更新徽标数据
        this.queryMessage(0); //更新最新消息
        this.queryNoticeList(0); //获取通告列表
    },
    onHide() {
        clearInterval(DataCarousel);
    },
    onShareAppMessage() {}
})