var utils = require("../../../utils/util.js")
const app = getApp()
const $request = require('../../../utils/request.js');
const $faces = require('../../../utils/faces.js');
Page({

    /**
    * 页面的初始数据
    */
    data: {
        receivebaseInfo: {
            avatar: "http://wx.qlogo.cn/mmopen/ajNVdqHZLLAIliaZvz5B1ibTzTehYzXdfBZ9hXTL7yuhuCUQGyzbuHeYS2yr8rO5PkbUBbHuWb5h9SibpRQkj3GTw/0",
        },
        sendAvatar: 'http://wx.qlogo.cn/mmopen/ajNVdqHZLLAIliaZvz5B1ibTzTehYzXdfBZ9hXTL7yuhuCUQGyzbuHeYS2yr8rO5PkbUBbHuWb5h9SibpRQkj3GTw/0',
        newsList: [
            // {
            //     date: "2020.10.19",
            //     message: '哈喽，好久不见',
            //     type: 0
            // },
            // {
            //     date: "2020.10.20",
            //     message: '是呀，好久不见',
            //     type: 1
            // },
        ],//消息列表
        historyList: [],
        input: null,
        openid: null,
        // 表情
        connectemoji: [],
        emoji_list: ['emoji1i1', 'emoji2i2', 'emoji3i3', 'emoji4i4', 'emoji5i5'],
        emotionVisible: false,
        inputShowed: false,
        scrollTop: 0,
        inputBottom: '0px',
        // 当前登录用户的ID
        receiveMemberId: null,
        // 对方的聊天ID
        sendMemberId: null,
        scrollid: 'scrollid',
        scrollHeight: '300px',
        //  下拉刷新
        triggered: true,
        //  历史记录当前页
        pageNo: 1,
        // 当前产品ID
        businessCommunicationDemandId: null,
        // 当前产品详情
        productInfo: null,
        // 发送框是否获取焦点
        inputShowed: false,
        // 是发送图片---用于阻止触发onhide
        isSendImg: false,
        // 发送图片url
        mangerUrl: "",
    },

    /**
    * 生命周期函数--监听页面加载
    */
    onLoad(options) {
        this.setData({
            mangerUrl: app.mangerUrl + "/file/getPhotos.action?path="
        })
        const eventChannel = this.getOpenerEventChannel()
        // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据

        eventChannel.on('customerid', data => {
            let productInfo = data.info ? data.info : null;
            let businessCommunicationDemandId = null;
            if (data.businessCommunicationDemandId) {
                businessCommunicationDemandId = data.businessCommunicationDemandId;
            }
            this.setData({
                sendMemberId: data.customerid,
                businessCommunicationDemandId,
                receivebaseInfo: {
                    avatar: data.chatHeads,
                },
                productInfo
            })

            //  获取历史记录 
            this.getHistory();
        })
        let customerId = app.globalData.customerId;
        let sendAvatar = app.globalData.businessCommunicationCustomer.chatHeads;
        this.setData({
            receiveMemberId: customerId,
            sendAvatar,
            connectemoji: $faces.getfaces(),
        })
        // 如果全局的 websocket 是连接的，需要关闭连接 调用自身的
        if (app.globalData.isOnSocketOpen) {
            wx.closeSocket();
        }
        //  获取内存中的数据
        this.getStorageBaseInfo()
        //  设置滚动区域的高度
        this.setScrollHeight()
        // 初始化websocket
        this.initWebSocket()
        // setTimeout(() => {

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

    },

    //  websocket初始化
    initWebSocket: function () {
        var _this = this;
        let { receiveMemberId, sendMemberId } = _this.data;
        // console.log()
        //建立连接
        wx.connectSocket({
            url: `ws://` + app.webSocketUrl + `/webSocket/{"userno":${receiveMemberId},"messageModule":"010"}`,//本地
            success: function () {
                console.log('websocket连接成功~')
            },
            fail: function () {
                console.log('websocket连接失败~')
            },
        })

        //连接成功
        wx.onSocketOpen(function () {
            console.log('onSocketOpen', '连接成功,真正的成功');
        })

        //  接收服务器的消息事件
        wx.onSocketMessage(function (res) {
            // 接收到的消息{date,message,type}  type类型为 1 是对方的消息 为 0 是自己的消息
            let list = [];
            list = _this.data.newsList;
            let _data = JSON.parse(res.data);
            _data.chatRecord = JSON.parse(_data.chatRecord);

            let msgData = {};
            // type 0 自己  1 对方
            if (_data.chatRecord.sender != _this.data.receiveMemberId) {
                msgData.type = 1;
            } else {
                msgData.type = 0;
            }
            msgData.isRead = true;
            msgData.message = _data.chatRecord.content;
            msgData.messageType = _data.chatRecord.messageType;
            if (msgData.messageType == 1) {
                msgData.object = _data.chatRecord.object;
            }
            msgData.date = utils.formatTime(new Date(_data.chatRecord.sendTime));
            msgData.date = msgData.date.replaceAll('/', '-');
            list.push(msgData);
            _this.setData({
                newsList: list
            })
            _this.setMsgRead('newsList', _this.data.newsList, 0)
            _this.scrollBottom()
            console.log('--------------对方给你发消息拉  beg -------------')
            console.log(_data);
            console.log('--------------对方给你发消息拉  end -------------')
        },
        )

        //  监听连接关闭
        wx.onSocketClose(function () {
            console.log('监听 WebSocket 连接关闭事件')
        })

    },

    // 获取历史记录
    getHistory() {
        var { sendMemberId, businessCommunicationDemandId } = this.data;
        $request.get('/businessCommunicationDemand/getChatRecordById/' + sendMemberId + '.action').then(res => {

            if (res.status == 0) {
                var historyList = [...res.data.chatRecordList, ...this.data.historyList]
                if (historyList && historyList.length > 0) {
                    historyList.forEach(item => {
                        // type 0 自己  1 对方
                        if (item.sender != sendMemberId) {
                            item.type = 0
                        } else {
                            item.type = 1
                        }
                        item.date = utils.formatTime(new Date(item.sendTime));
                        item.date = item.date.replaceAll('/', '-');
                    });
                    this.setData({
                        historyList
                    })
                    console.log(this.data.historyList, '历史记录数据')
                }
                // 如果产品ID存在
                console.log(businessCommunicationDemandId, '产品ID是否存在')
                if (businessCommunicationDemandId) {
                    if (historyList.length > 0) {
                        let tempArr = [];
                        for (let index = historyList.length - 1; index >= 0; index--) {
                            const element = historyList[index];
                            if (element.messageType == 1 && tempArr.length < 1) {
                                tempArr.push(element);
                            }
                        }
                        // 说明没有一条是messageType == 1 的
                        if (tempArr.length < 1) {
                            this.sendmsgApi("", 1);
                        } else {
                            if (tempArr[0].transactionId != businessCommunicationDemandId) {
                                this.sendmsgApi("", 1);
                            }
                        }
                    } else {
                        this.sendmsgApi("", 1);
                    }
                }
            }
            // 设置消息已读
            this.setMsgRead('historyList', this.data.historyList, 1)
            //  页面进入滚动到底部
            this.scrollBottom()
        }).catch(err => {
            console.log(err)
        })
    },

    // 滚动到底部
    scrollBottom: function () {
        console.log(`触发了吗？`)
        // wx.createSelectorQuery().select('#sendmessage').boundingClientRect(rect => {
        //     console.log(rect.height);
        //     console.log(`触发了吗2？`)
        //     wx.pageScrollTo({
        //         scrollTop:rect.height
        //     })
        // }).exec()

        // var { newsList } = this.data
        // var scrollid = `scrollid${newsList.length - 1}`;
        // if (newsList.length == 0) {
        //     scrollid = "scrollid0"
        // }
        this.setData({
            scrollid:"sendmessage"
        })
    },

    // 设置滚动区域的高度
    setScrollHeight: function () {
        const client = wx.getSystemInfoSync().windowHeight    // 获取当前窗口的高度
        var scrollHeight = (client - 136) + 'px'
        this.setData({
            scrollHeight
        })
    },
    // 进入详情
    goDetails(e) {
        let value = e.currentTarget.dataset.value;
        wx.navigateTo({
            url: '/pages/index/components/listDetails/Details?businessCommunicationDemandId=' + value,
        })
    },
    // 获取内存中聊天列表的用户信息
    getStorageBaseInfo: function () {
        //获取存储信息
        wx.getStorage({
            key: 'receivebaseInfo',
            success: (res) => {
                this.setData({
                    receivebaseInfo: res.data
                })
            }
        })
    },

    // 自定义下拉刷新
    refresh: function () {
        // // 下拉的实际操作
        // var pageNo = this.data.pageNo + 1
        // this.setData({
        //     pageNo
        // })
        // if (this.timer) {
        //     clearTimeout(this.timer)
        // }
        // this.timer = setTimeout(() => {
        //     this.setData({
        //         triggered: false
        //     })
        //     this.getHistory()
        // }, 2000)
    },

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

    /**
    * 生命周期函数--监听页面隐藏
    */
    onHide: function () {
        // 如果是发送图片就不触发
        if (!this.data.isSendImg) {
            wx.closeSocket();
            // 检测到全局的 websocket 是连接的 关闭
            if (app.globalData.isOnSocketOpen) {
                app.globalData.isOnSocketOpen = false;
            }
        }
    },

    /**
    * 生命周期函数--监听页面卸载
    */
    onUnload: function () {
        // 如果是发送图片就不触发
        if (!this.data.isSendImg) {
            wx.closeSocket();
            // 检测到全局的 websocket 是连接的 关闭
            if (app.globalData.isOnSocketOpen) {
                app.globalData.isOnSocketOpen = false;
            }
        }
    },

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

    },

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

    },
    send: function () {
        var _this = this;
        if (_this.data.input) {
            this.sendmsgApi(_this.data.input, 0);
        }
    },
    sendmsgApi(content, msgType) {
        let { sendMemberId, receiveMemberId, businessCommunicationDemandId } = this.data;
        let transactionId = businessCommunicationDemandId;
        if (!businessCommunicationDemandId) {
            if (this.data.historyList.length > 0) {
                transactionId = this.data.historyList[this.data.historyList.length - 1].transactionId;
            }
        }
        if (!transactionId) {
            transactionId = "";
        }
        let params = {
            sender: receiveMemberId, // 发件人Id
            addressee: sendMemberId, // 收件人Id
            transactionId, // 产品ID
            content,
            messageType: msgType,
        };
        $request.post('/businessCommunicationDemand/addChatRecord.action', params).then(res => {
            // 是由需求点击的聊一聊 保存完信息后需要再发送一条
            if (msgType == 1) {
                this.sendmsgApi("你好，我对这个需求很有兴趣，可以聊聊吗？", 0);
            }
        }).catch(err => {
            console.log(err)
        })
        var list = [];
        list = this.data.newsList;
        var temp = { 'message': content, 'date': utils.formatTime(new Date()), type: 0 };
        temp.date = temp.date.replaceAll('/', '-');
        temp.messageType = msgType;
        temp.transactionId = transactionId;
        temp.isRead = false;
        if (msgType == 1) {
            temp.object = {};
            temp.object.info = this.data.productInfo;
        }
        list.push(temp);
        this.setData({
            newsList: list,
            input: null,
            inputShowed: true,
        })

        console.log(this.data.newsList, 'this.data.newsList')
        this.scrollBottom()
        //  表情选择隐藏
        this.setData({
            emotionVisible: false,
        })
        const client = wx.getSystemInfoSync().windowHeight    // 获取当前窗口的高度
        console.log(client, '当前消息高度')
    },
    bindChange: function (res) {
        this.setData({
            input: res.detail.value,
        })
    },
    back: function () {
        wx.closeSocket();
        console.log('连接断开');
    },
    emotionChange() {
        console.log(`测试打开表情`)
        this.setData({
            emotionVisible: !this.data.emotionVisible
        })
    },
    addemotion: function (e) {
        console.log(e.currentTarget.dataset.index, "点了设默默")
        let { connectemoji, input } = this.data
        if (input) {
            input = input + connectemoji[e.currentTarget.dataset.index];
        } else {
            input = connectemoji[e.currentTarget.dataset.index]
        }

        console.log(input, '输入框额值')
        this.setData({
            input,
            emotionVisible: false,
            inputShowed: true,
        })
    },
    closeEmotionVisible() {
        this.setData({
            emotionVisible: false,
        })
    },
    // 发送图片
    upImg() {
        this.setData({
            isSendImg: true
        })
        wx.chooseImage({
            count: 1,
            success: (res) => {
                wx.uploadFile({
                    filePath: res.tempFilePaths[0],
                    name: "file",
                    url: app.mangerUrl + "/file/uploading.action?fileType=TinymceImg",
                    success: (res2) => {
                        let data = JSON.parse(res2.data);
                        this.sendmsgApi(data.data, 2);
                    }
                })
                // /file/uploading.action?fileType=TinymceImg
            },
            complete: (res) => {
                // 调用结束后要关闭isSendImg
                this.setData({
                    isSendImg: false
                })
            }
        })
    },
    // 设置已读未读
    setMsgRead(key, data, type) {
        data.forEach(el => {
            if (el.type == type) {
                el.isRead = true;
            }
        })
        if (key == 'historyList') {
            this.setData({
                historyList: data
            })
        } else {
            this.setData({
                newsList: data
            })
        }
    },
    // 图片预览
    viewImg(e) {
        let url = e.currentTarget.dataset.url;
        url += "?time=" + Date.now();
        console.log(url)
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: [url] // 需要预览的图片http链接列表
        })
    },
})


