// pages/light-map/light-map.js
const app = getApp();
const util = require('../../utils/util');
const WebIM = require("../../utils/WebIM.js")["default"];
const disp = require("../../utils/broadcast");

Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgPath: app.globalData.imgPath,
        longitude: 106.51778136583812,
        latitude: 29.617295391392194,
        scale: 16,
        markers: [],
        show: false,
        username: '刘元云',
        roleName: '工作人员'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let that = this;
        wx.getSetting({
            success: function (res) {
                console.info(res);
                if (!res.authSetting['scope.userLocation']) {
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success: function (res) {
                            wx.getLocation({
                                type: 'gcj02',
                                success: function (res) {
                                    console.info('getLocation', res);
                                    that.setData({
                                        latitude: res.latitude,
                                        longitude: res.longitude
                                    });
                                }
                            });
                        },
                        fail: function (e) {
                            console.info(e);
                            wx.showToast({
                                title: '用户未授权',
                                icon: 'error'
                            });
                        }
                    });
                } else {
                    wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                            console.info('getLocation', res);
                            that.setData({
                                latitude: res.latitude,
                                longitude: res.longitude
                            });
                        }
                    });
                }
            }
        });
        that.getGroupList();

        // for (let i in that.data.groupIdList) {
        // let obj = {
        //     latitude: result.latitude,
        //     longitude: result.longitude
        // }
        // 发送当前用户的实时定位信息
        // that.sendGroupText(that.data.groupIdList[i], obj);
        // 显示其他用户的实时定位信息
        // that.showMapMarker(that.data.groupIdList[i]);
        // }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.mapCtx = wx.createMapContext('map', this);
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let that = this;
        //需要基础库： 2.8.0
        wx.startLocationUpdate({
            type: 'gcj02',
            success: (res) => {
                console.info('startLocationUpdate', res);
                if (res.errMsg == 'startLocationUpdate:ok') {
                    //需要基础库： 2.8.1
                    wx.onLocationChange((result) => {
                        console.info('onLocationChange', result);
                        that.setData({
                            latitude: result.latitude,
                            longitude: result.longitude
                        });
                        for (let i in that.data.groupIdList) {
                            let obj = {
                                latitude: result.latitude,
                                longitude: result.longitude
                            }
                            // 显示其他用户的实时定位信息
                            that.showMapMarker(that.data.groupIdList[i]);
                            // 发送当前用户的实时定位信息
                            that.sendGroupText(that.data.groupIdList[i], obj);
                        }
                    });
                }
            },
        });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        wx.offLocationChange((result) => {
            console.info('offLocationChange', result);
        });
        wx.stopLocationUpdate({
            success: (res) => {
                console.info('stopLocationUpdate', res);
            },
        });
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        wx.offLocationChange((result) => {
            console.info('offLocationChange', result);
        });
        wx.stopLocationUpdate({
            success: (res) => {
                console.info('stopLocationUpdate', res);
            },
        });
    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    markerTap: function (e) {
        console.info(e);
        let id = e.markerId;

        util.post({
            url: '/api/easemob/getUpUserAttribute/' + id,
            success: (res) => {
                wx.hideLoading();
                console.info(res);
            }
        });
    },

    /**
     * 群组列表
     */
    getGroupList: function () {
        var that = this;
        WebIM.conn.getGroup({
            limit: 50,
            success: function (res) {
                console.info('groupList', res);
                let arr = [];
                if (res.data && res.data.length > 0) {
                    for (let i in res.data) {
                        arr.push(res.data[i].groupid);
                    }
                }
                that.setData({
                    groupIdList: arr
                });
            },
            error: function (e) {
                console.info(e)
            }
        });
    },

    /**
     * 发送群组文本消息
     */
    sendGroupText: function (groupId, message) {
        // 生成本地消息id
        let id = WebIM.conn.getUniqueId();
        // 创建文本消息
        let msg = new WebIM.message('txt', id);
        let option = {
            // 消息内容
            msg: 'location',
            // 接收消息对象(群组id)
            to: groupId,
            // 群聊类型设置为群聊
            chatType: 'groupChat',
            // 扩展消息
            ext: message,
            // 对成功的相关定义，sdk会将消息id登记到日志进行备份处理
            success: function () {
                console.log('send room text success');
                // disp.fire('em.chat.sendSuccess', id, 'location');
            },
            // 对失败的相关定义，sdk会将消息id登记到日志进行备份处理
            fail: function () {
                console.log('failed');
            }
        };
        msg.set(option);
        WebIM.conn.send(msg.body);
    },

    /**
     * 显示其他群组成员定位
     */
    showMapMarker: function (groupId) {
        let that = this;
        let myName = wx.getStorageSync("myUsername");
        console.info(groupId, myName);
        let historyChatMsgs = wx.getStorageSync("rendered_" + groupId + myName) || [];
        let chatMsg = wx.getStorageSync(groupId + myName) || [];
        chatMsg = historyChatMsgs.concat(chatMsg);
        if (!chatMsg.length) return;
        chatMsg = chatMsg.slice(-20);
        console.info('chatMsg:', chatMsg);
        let psersonList = [];
        let markerList = [];
        for (let i in chatMsg) {
            if (chatMsg[i].info.from == myName) continue;
            if (chatMsg[i].msg.data[0].data != 'location') continue;
            if (psersonList.indexOf(chatMsg[i].info.from) >= 0) continue;
            psersonList.push(chatMsg[i].info.from);
            markerList.push({
                id: Number(chatMsg[i].info.from),
                latitude: chatMsg[i].msg.ext.latitude,
                longitude: chatMsg[i].msg.ext.longitude,
                iconPath: app.globalData.imgPath + '/map-user.png',
                width: 34,
                height: 40
            });
            that.setData({
                psersonList: psersonList,
                markers: markerList,
            });
        }
    }

})