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

Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgPath: app.globalData.imgPath,
        cursor: null,
        limit: 10,
        list: [],
        search_btn: true,
        search_chats: false,
        show_mask: false,
        yourname: "",
        unReadSpotNum: 0,
        unReadNoticeNum: 0,
        messageNum: 0,
        unReadTotalNotNum: 0,
        arr: [],
        show_clear: false,
        groupName: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // let that = this;
        // this.getRoster();
        this.listGroups();
        // this.getChatList();
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

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

    },

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

    },

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

    },

    /**
     * 跳转到群组列表
     */
    into_groups: function () {
        wx.navigateTo({
            url: "../chat-group/chat-group?myName=" + this.data.myName
        });
    },

    /**
     * 查询联系人
     */
    getRoster: function () {
        let that = this;
        let rosters = {
            success(roster) {
                console.info(roster)
                var member = [];
                for (let i = 0; i < roster.length; i++) {
                    if (roster[i].subscription == "both") {
                        member.push(roster[i]);
                    }
                }
                wx.setStorage({
                    key: "member",
                    data: member
                });
                that.setData({ member: member });
                that.listGroups();
                //if(!systemReady){
                disp.fire("em.main.ready");
                //systemReady = true;
                //}
                // that.setData({
                //     arr: that.getChatList(),
                //     unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
                // });
            },
            error(err) {
                console.log(err);
            }
        };
        WebIM.conn.getRoster(rosters);
    },

    /**
     * 查询群组
     */
    listGroups: function () {
        var that = this;
        return WebIM.conn.getGroup({
            limit: 100,
            success: function (res) {
                console.info(res)
                let groupName = {}
                let listGroup = res.data || []
                listGroup.forEach((item) => {
                    groupName[item.groupid] = item.groupname
                });

                that.setData({
                    groupName
                })
                wx.setStorage({
                    key: "listGroup",
                    data: res.data
                });
                that.getChatList();
            },
            error: function (err) {
                console.log(err)
            }
        });
    },

    /**
     * 查询聊天记录（包含陌生人版本）
     */
    getChatList: function () {
        var myName = wx.getStorageSync("myUsername");
        var array = [];
        const that = this
        wx.getStorageInfo({
            success: function (res) {
                console.info(res);
                let storageKeys = res.keys;
                console.log('res.keys +++ ', res.keys);
                let newChatMsgKeys = [];
                let historyChatMsgKeys = [];
                let len = myName.length;
                storageKeys.forEach((item) => {
                    console.info(item);
                    // 未读
                    if (item.slice(-len) == myName && item.indexOf('rendered_') == -1) {
                        newChatMsgKeys.push(item);
                    }
                    // 已读
                    else if (item.slice(-len) == myName && item.indexOf('rendered_') > -1) {
                        historyChatMsgKeys.push(item);
                    }
                });

                cul.call(that, newChatMsgKeys, historyChatMsgKeys);
            }
        })

        function cul(newChatMsgKeys, historyChatMsgKeys) {
            let array = []
            let lastChatMsg;
            for (let i = 0; i < historyChatMsgKeys.length; i++) {
                // 判断新消息是否包含历史聊天（截断'rendered_'）
                let index = newChatMsgKeys.indexOf(historyChatMsgKeys[i].slice(9));
                if (index > -1) {
                    let newChatMsgs = wx.getStorageSync(newChatMsgKeys[index]) || [];
                    if (newChatMsgKeys.includes()) { }
                    if (newChatMsgs.length) {
                        lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
                        lastChatMsg.unReadCount = newChatMsgs.length;
                        if (lastChatMsg.unReadCount > 99) {
                            lastChatMsg.unReadCount = "99+";
                        }
                        lastChatMsg.time = that.chatTime(lastChatMsg.time);
                        lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
                        newChatMsgKeys.splice(index, 1);
                    } else {
                        let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
                        if (historyChatMsgs.length) {
                            lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
                            lastChatMsg.time = that.chatTime(lastChatMsg.time);
                            lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
                        }
                    }
                } else {
                    let historyChatMsgs = wx.getStorageSync(historyChatMsgKeys[i]);
                    if (historyChatMsgs.length) {
                        lastChatMsg = historyChatMsgs[historyChatMsgs.length - 1];
                        lastChatMsg.time = that.chatTime(lastChatMsg.time);
                        lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();
                    }
                }
                if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
                    lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
                }
                lastChatMsg && lastChatMsg.username != myName && array.push(lastChatMsg);
            }

            for (let i = 0; i < newChatMsgKeys.length; i++) {
                let newChatMsgs = wx.getStorageSync(newChatMsgKeys[i]) || [];
                if (newChatMsgs.length) {
                    lastChatMsg = newChatMsgs[newChatMsgs.length - 1];
                    lastChatMsg.unReadCount = newChatMsgs.length;
                    if (lastChatMsg.unReadCount > 99) {
                        lastChatMsg.unReadCount = "99+";
                    }
                    lastChatMsg.time = that.chatTime(lastChatMsg.time);
                    lastChatMsg.dateTimeNum = new Date(lastChatMsg.time.replace(/-/g, '/')).getTime();

                    if (lastChatMsg.chatType == 'groupchat' || lastChatMsg.chatType == 'chatRoom') {
                        lastChatMsg.groupName = that.data.groupName[lastChatMsg.info.to];
                    }
                    lastChatMsg.username != myName && array.push(lastChatMsg)
                }
            }

            array.sort((a, b) => {
                return b.dateTimeNum - a.dateTimeNum
            });
            console.info(array)
            this.setData({
                arr: array
            })
        }
    },

    onShow: function () {
        this.getChatList()
        this.setData({
            //arr: this.getChatList(),
            unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
            messageNum: getApp().globalData.saveFriendList.length,
            unReadNoticeNum: getApp().globalData.saveGroupInvitedList.length,
            unReadTotalNotNum: getApp().globalData.saveFriendList.length + getApp().globalData.saveGroupInvitedList.length
        });

        if (getApp().globalData.isIPX) {
            this.setData({
                isIPX: true
            })
        }
    },

    openSearch: function () {
        this.setData({
            search_btn: false,
            search_chats: true,
            gotop: true
        });
    },

    onSearch: function (val) {
        var myName = wx.getStorageSync("myUsername");
        const that = this
        let searchValue = val.detail.value
        let chartList = this.data.arr;
        let serchList = [];
        console.log('arr', that.data.arr)
        chartList.forEach((item, index) => {
            if (String(item.username).indexOf(searchValue) != -1 || (item.groupName && item.groupName.indexOf(searchValue) != -1)) {
                serchList.push(item)
            }
        })
        this.setData({
            arr: serchList,
        })
    },

    cancel: function () {
        this.getChatList()
        this.setData({
            search_btn: true,
            search_chats: false,
            //arr: this.getChatList(),
            unReadSpotNum: getApp().globalData.unReadMessageNum > 99 ? '99+' : getApp().globalData.unReadMessageNum,
            gotop: false
        });
    },

    clearInput: function () {
        this.setData({
            input_code: '',
            show_clear: false
        })
    },

    onInput: function (e) {
        let inputValue = e.detail.value
        if (inputValue) {
            this.setData({
                show_clear: true
            })
        } else {
            this.setData({
                show_clear: false
            })
        }
    },

    tab_contacts: function () {
        wx.redirectTo({
            url: "../main/main?myName=" + wx.getStorageSync("myUsername")
        });
    },

    close_mask: function () {
        this.setData({
            search_btn: true,
            search_chats: false,
            show_mask: false
        });
    },

    tab_setting: function () {
        wx.redirectTo({
            url: "../setting/setting"
        });
    },

    tab_notification: function () {
        wx.redirectTo({
            url: "../notification/notification"
        });
    },

    into_chatRoom: function (event) {
        let detail = event.currentTarget.dataset.item;
        console.info('detail:', detail);
        //群聊的chatType居然是singlechat？脏数据？ 等sdk重写后整理一下字段
        if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom' || detail.groupName) {
            this.into_groupChatRoom(detail);
        } else {
            this.into_singleChatRoom(detail);
        }
    },

    //	单聊
    into_singleChatRoom: function (detail) {
        var my = wx.getStorageSync("myUsername");
        var nameList = {
            myName: my,
            your: detail.username
        };
        wx.navigateTo({
            url: "../chat-detail/chat-detail?username=" + JSON.stringify(nameList)
        });
    },

    //	群聊 和 聊天室 （两个概念）
    into_groupChatRoom: function (detail) {
        var my = wx.getStorageSync("myUsername");
        var nameList = {
            myName: my,
            your: detail.groupName,
            groupId: detail.info.to
        };
        wx.navigateTo({
            url: "../chat-group-detail/chat-group-detail?username=" + JSON.stringify(nameList)
        });
    },

    del_chat: function (event) {
        let detail = event.currentTarget.dataset.item;
        let nameList;
        let that = this;
        if (detail.chatType == 'groupchat' || detail.chatType == 'chatRoom') {
            nameList = {
                your: detail.info.to
            };
        } else {
            nameList = {
                your: detail.username
            };
        }

        var myName = wx.getStorageSync("myUsername");
        var currentPage = getCurrentPages();

        wx.showModal({
            title: "删除该聊天记录",
            confirmText: "删除",
            success: function (res) {
                if (res.confirm) {
                    wx.removeStorageSync(nameList.your + myName);
                    wx.removeStorageSync("rendered_" + nameList.your + myName);
                    if (currentPage[0]) {
                        currentPage[0].onShow();
                    }
                    that.getChatList()
                    disp.fire("em.chat.session.remove");
                }
            },
            fail: function (err) {
            }
        });
    },

    chatDetail: function (e) {
        let id = e.currentTarget.dataset.id;
        let name = e.currentTarget.dataset.name;
        wx.navigateTo({
            url: '../chat-detail/chat-detail?id=' + id + "&name=" + name,
        })
    },

    /**
     * 自定义格式化聊天时间
     * @param {*} chatTime 
     */
    chatTime: function (chatTime) {
        let dateArr = chatTime.split(' ')[0].split('-');
        let timeArr = chatTime.split(' ')[1].split(':');
        let nowArr = util.formatDate(null).split(' ')[0].split('-');
        let month = dateArr[1] < 10 ? '0' + dateArr[1] : dateArr[1];
        console.info('dateArr', dateArr);
        console.info('nowArr', nowArr);
        if (nowArr[0] == dateArr[0] && nowArr[1] == month && nowArr[2] == dateArr[2]) {
            return `${timeArr[0]}:${timeArr[1]}`;
        } else {
            return `${dateArr[0]}/${dateArr[1]}/${dateArr[2]}`;
        }
    }
})