<template>
    <view class="page page--divider">
        <view style="display: none;">{{$store.state.hackUpdate}}</view>
        <load-more status="loading" v-if="initializing" />
        <chat-panel :store-key="storeKey" :thistype="thistype" :atme="atme" :at_msg_id='at_msg_id' @close='atuser1'
            :sending="sending" :sendingdata="sendingdata" :manager="ismanage" :no_add="no_add"
            @click-avatar="openProfile" @setSending='setSending' :boardheight='boardheight' ref="panel"
            @chooseQuote="setQuote" />
        <view class="placeholder"></view>
        <v-sender ref='sender' v-if="!initializing" v-model="message" @send="sendTextMessage" :groupid="group.id"
            :isgroup="1" @face="sendVoice" @sendImage="sendImg" @sendVedio="sendVedio" @emoji="sendEmoji"
            @clearQute="clearQute" :no-speaking="no_speaking" :speaking_tips='speaking_tips'
            :forbid-redpack="group.forbid_redpack==1 && !group.owner && !ismanage?true:false"
            @handleEmotion="handleEmotion" @input="inputMessage" @keyboardheight='keyboardheight'
            @senderheight="set_sheight" :sendtype='type' />
        <GroupUser ref='groupuser' :groupid='group.id' :show='groupshow' @atuser='atuser'></GroupUser>
    </view>

</template>

<script>
    import GroupUser from '../../components/GroupUser.vue';
    import ChatPanel from '../../components/chat-panel.vue'
    import chat from "../../library/chat.js"
    import {
        mapState,
        mapGetters
    } from 'vuex';
    import api from "../../library/index.js"
    import config from "../../config.js"

    export default {
        components: {
            ChatPanel,
            GroupUser
        },
        data() {
            return {
                quoteItem: {}, //引用内容
                userid: uni.getStorageSync('access_token'),
                user: uni.getStorageSync('userInfo'),
                loaded: 'more',
                group: {},
                message: '',
                initializing: false,
                showPickMoney: '',
                getPick: '',
                pickErrorText: '',
                redpackInfo: {},
                sending: false,
                sendingdata: {},
                ismanage: false,
                no_speaking: false,
                no_add: false,
                sender: [],
                receiver: [],
                boardheight: 0,
                groupshow: 0,
                oldstr: '',
                atusers: {},
                type: '',
                speaking_tips: '',
                atme: 0,
                at_msg_id: 0,
                thistype: '',
                storeKey: '',
                list: [
                    ['微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴'],
                    ['睡', '大哭', '尴尬', '发怒', '调皮', '呲牙', '惊讶', '难过'],
                    ['酷', '冷汗', '抓狂', '吐', '偷笑', '可爱', '白眼', '傲慢'],
                    ['饥饿', '困', '惊恐', '流汗', '憨笑', '大兵', '奋斗', '咒骂'],
                    ['疑问', '嘘', '晕', '折磨', '衰', '骷髅', '敲打', '再见'],
                    ['擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼', '右哼哼', '哈欠'],
                    ['鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀'],
                    ['西瓜', '啤酒', '篮球', '乒乓', '咖啡', '饭', '猪头', '玫瑰', ],
                    ['凋谢', '示爱', '爱心', '心碎', '蛋糕', '闪电', '炸弹', '刀'],
                    ['足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱', '强'],
                    ['弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你'],
                    ['NO', 'OK', '爱情', '飞吻', '跳跳', '发抖', '怄火', '转圈'],
                    ['磕头', '回头', '跳绳', '挥手', '激动', '闭嘴', '笑哭', '吐舌'],
                    ['耶', '跳舞', '恐惧', '失望', '脸红', '无语', '奸笑', '嘿哈'],
                    ['鬼混', '福', '合十', '强壮', '红包', '发财', '庆祝', '礼物']
                ],
                reg: /\S{1,3}/gi,
                lists: [],
                listss: []
            };
        },
        onLoad(opts) {
            //   console.log(opts);
            if (opts.atme > 0) this.atme = opts.atme
            if (opts.msg_id > 0) this.at_msg_id = opts.msg_id

            uni.setNavigationBarTitle({
                title: decodeURI(opts.nickname)
            })

            this.group = opts;

            this.group.id = parseInt(this.group.id);
            this.storeKey = 'G' + this.group.id;

            uni.setStorageSync('cache_key', this.storeKey);
            this.joingroup();
            // console.log(opts);


            this.$socket.on('group_update', (res) => {
                this.getInfo();
                this.getGroupUsers();

            })
            this.sender = uni.getStorageSync('userInfo');
            // #ifdef APP-PLUS
            let currentWebview = this.$mp.page.$getAppWebview();
            currentWebview.setStyle({
                titleNView: {
                    titleText: ''
                },
            })
            // #endif
        },

        onUnload() {

            uni.setStorageSync('cache_key', '');
        },

        onShow() {

            this.getInfo();
            this.getGroupUsers();

            var value = '';
            this.list = this.list.map((line, index) => {
                this.listss = [];
                line = line.map((item, idx) => {

                    value = item;

                    item = item.replace(/\S{1,3}/gi, this.getemotion(item));

                    this.listss.push({
                        "name": item,
                        "index": index,
                        "value": value,
                        "idx": idx
                    })

                    return item;

                })

                this.lists.push(this.listss);

                return line;
            })
            console.log(this.list, 'this.list');

        },
        methods: {
            getemotion(res) {

                let word = res.replace(/\[|\]/gi, '')

                const list = ['微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭', '尴尬', '发怒', '调皮', '呲牙', '惊讶',
                    '难过', '酷', '冷汗', '抓狂', '吐', '偷笑', '可爱', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑', '大兵', '奋斗',
                    '咒骂', '疑问', '嘘', '晕', '折磨', '衰', '骷髅', '敲打', '再见', '擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼', '右哼哼',
                    '哈欠', '鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', '西瓜', '啤酒', '篮球', '乒乓', '咖啡', '饭', '猪头',
                    '玫瑰', '凋谢', '示爱', '爱心', '心碎', '蛋糕', '闪电', '炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱',
                    '强', '弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你', 'NO', 'OK', '爱情', '飞吻', '跳跳', '发抖', '怄火',
                    '转圈', '磕头', '回头', '跳绳', '挥手', '激动',
                    '闭嘴', '笑哭', '吐舌', '耶', '跳舞', '恐惧', '失望', '脸红', '无语', '奸笑', '嘿哈', '鬼混', '福', '合十', '强壮', '红包',
                    '发财', '庆祝', '礼物'
                ]
                let index = list.indexOf(word);
                var index1 = index + 100;
                return '^' + index1 + '^';

            },
            // 清除qute
            clearQute() {
                this.quoteItem = {}
            },
            setQuote(item) {
                if (item.message.type == 'text') {
                    if (!item.message.content.type) {
                        item.ttype = 'text'
                        // 空格替换回车
                        item.message.qute = item.message.content.replace(/<br>/g, " ").replace(/&nbsp;/g, ' ')
                    } else if (item.message.content.type == "remind") {
                        // 去除html 标签 && 去除 回车替换成空格
                        if(item.message.content.remind && item.message.content.remind.nickname) {
                            item.message.qute = item.message.content.content.replace(/<span.*?>.*?<\/span>/g, '@' + item.message.content.remind.nickname).replace(
                                /<br>/g, " ").replace(/&nbsp;/g, ' ')
                        }else {
                            item.message.qute = item.message.content.content.replace(/<span.*?>|<\/span>/g, '@' + '').replace(
                                /<br>/g, " ").replace(/&nbsp;/g, ' ')
                        }
                       
                        item.ttype = 'remind'
                    }
                }
                if (item.message.type == 'emotion') {
                    item.ttype = 'emotion'
                    console.log(item.message.content,'item.message.content');
                    item.message.qute = item.message.content.content.replace(/<br>/g, " ")
                    var content = item.message.qute.replace(/\[\S{1,3}\]/gi, this.getemotion).split('^');
                    var imgs = [];
                    for (var i = 0; i < content.length; i++) {
                        if (content[i] >= 100 && content[i] <= 222) {
                            imgs.push({
                                'type': 'img',
                                'content': "/static/emoji/" + content[i] + '.gif'
                            })
                        } else {
                            imgs.push({
                                'type': 'text',
                                'content': content[i]
                            })
                        }
                    }
                    
                   item.message.face = imgs;
                    console.log('content', content);
                }
                if(item.message.type == 'image') {
                    console.log('引用图片');
                    item.ttype = 'image'
                    item.message.qute = item.message.content
                }
                this.$refs.sender.setQute(item)
                this.quoteItem = item
                console.log("设置item", item);
            },
            // 检测输入值
            inputMessage(e) {
                // console.log(e);
                //console.log(this.oldstr,e);
                if (e.substr(e.length - 1, 1) == '@' && this.oldstr != e && e.length > 0 && e.length > this.oldstr
                    .length) {
                    this.groupshow = 1;
                    uni.hideKeyboard();
                } else {
                    this.groupshow = 0;
                }


                this.oldstr = e;

                this.emotion = e;
            },

            atuser(e) {

                this.groupshow = 0;
                if (e.nickname) {
                    this.$refs.sender.setinputvalue(e.nickname);
                    this.atusers = e;
                }
            },

            atuser1(e) {
                console.log(e);
                if (e.nickname) {

                    this.$refs.sender.setinputvalue('@' + e.nickname);
                    this.atusers = e;

                }
            },

            set_sheight(e) {

                this.$refs.panel.setAutoHeight(e);
            },
            keyboardheight(e) {
                this.boardheight = e;

                this.$refs.panel.setAutoHeight(0);
            },


            setSending(e) {

                this.sending = e;

            },
            group_init(id) {

                var group = uni.getStorageSync('group_' + id);
                if (group.id > 0 && group.id == id) this.group_set(group);
            },

            group_set(group) {
                this.group = group;
                if (group.deny_id == null) group.deny_id = '';
                if (group.manager_id == null) group.manager_id = '';
                if (this.user.status == 1 || (this.user.status == 2 && parseInt(this.user.lock_time) >= Date.parse(
                        new Date()) / 1000)) {
                    this.no_speaking = true;
                    this.speaking_tips = '您的账号已被冻结';
                } else if ((group.no_speaking == 1) && !group.owner && group.manager_id.indexOf(this.userid) <= -1) {
                    this.no_speaking = true;
                    this.speaking_tips = '全体禁言,限群主和管理员可发消息';
                } else if ((group.deny_id.indexOf(this.userid) > -1) && !group.owner && group.manager_id.indexOf(this
                        .userid) <= -1) {
                    this.no_speaking = true;
                    this.speaking_tips = '您已被禁言';
                } else {
                    this.no_speaking = false;
                }


                if (group.manager_id.indexOf(this.userid) > -1 || group.owner) this.ismanage = true;
                else this.ismanage = false;
                if (group.is_owner == 1) var type = 'owner';
                else if (group.is_manager == 1) var type = 'manager';
                else var type = 'user';
                this.thistype = type;


                //    console.log(this.group);
                if ((group.no_add == 1) && this.ismanage == false)
                    this.no_add = true;
                else this.no_add = false;

                uni.setNavigationBarTitle({
                    title: `${group.name}(${group.people_count}人)`
                })

                uni.setStorageSync('group_' + group.id, group);
            },



            getInfo() {
                if (this.group.id > 0) {

                    this.group_init(this.group.id);
                    api.getGroupInfo({
                        group_id: this.group.id,
                        from_id: this.userid,
                    }).then(res => {
                        this.group_set(res.data);
                    })

                }

            },

            handleEmotion(value) {
                //console.log(value);
                this.emotion = value;
                this.type = 'emotion';
            },
            joingroup() {
                let data = {
                    GroupId: this.group.id,
                    type: 'joinGroup'
                }
                this.getGroupUsers()
                this.$socket.send(data);
            },
            getGroupUsers() {
                if(this.loaded == 'loading' || this.loaded == 'noMore') {
                    return
                }
                this.loaded = 'loading'
                api.getGroupUsers({
                    group_id: this.group.id,
                    userid: this.userid,
                }).then(res => {
                    this.loaded = 'noMore'
                    uni.setStorageSync(this.group.id + '_group_members', res.data);
                }).catch(err => {
                     this.loaded = 'more'
                })
            },
            toHtml(str) {
                str = str.replace(/ /g, "&nbsp;");
                str = str.replace(/\n/g, "<br>");
                return str;
            },
            sendImg(e) {
                this.commitMessage('image', e);
            },
            sendVedio(e) {

                this.commitMessage('vedio', e);
            },
            // 发送文本消息
            sendTextMessage() {
                let that = this;
                let addStr = '';
                console.log(that.quoteItem,'发送that.quoteItem');
                if (this.quoteItem && this.quoteItem.id) {
                    addStr += '-qute-nickname=' + that.quoteItem.sender.nickname + 'q&qcontent=' + that.quoteItem
                        .message
                        .qute + 'q&qttype=' + that.quoteItem.ttype
                }
                if (this.type == "emotion") {
                    this.emotionInfo = {
                        "type": "emotion",
                        "value": this.emotion + addStr,
                        "content": this.emotion + addStr
                    }
                   
                    this.commitMessage('emotion', this.emotionInfo);
                } else {
                    var msg = this.toHtml(this.message) + addStr;
                    
                    this.commitMessage('text', msg,1);
                }
                this.quoteItem = {}
                this.$refs.sender.clearQute()
                // this.commitMessage('text', this.message);
            },
            commitMessage(type, sendData,ttype=0) {
                console.log('type：',type,'sendData:',sendData)

                this.message = '';
                if (type == 'image') {
                    var mid = sendData.mid;
                    sendData = sendData.src;

                } else if (type == 'vedio') {
                    var mid = sendData.mid;
                    //  sendData=sendData.src;

                } else if (type == 'voice') {
                    var mid = sendData.mid;
                } else {
                    var mid = 'm' + Math.random().toString(36).substring(2);
                }
                var atuser = 0;

                if (type == 'text' && parseInt(this.atusers.id) > 0) {

                    if (sendData.indexOf(this.atusers.nickname) > -1) {
                        let arr = sendData.split('-qute-')
                        if(arr[0].indexOf('@' + this.atusers.nickname) != -1) {
                            var content = sendData.replace('@' + this.atusers.nickname, '@{' + this.atusers.id + '}');
                            console.log('包含',content);
                            // console.l
                        }else {
                             var content = sendData
                        }
                        
                        sendData = {
                            type: 'remind',
                            remind: this.atusers,
                            content: content
                        }

                        this.oldstr = '';
                        this.atusers = {};
                    }

                }
                if (type == 'text' && sendData == '') return false;

                let data = {
                    userid: this.userid,
                    group_id: this.group.id,
                    type: 'group',
                    msgtype: type,
                    content: sendData,
                    mid: mid
                }

                var sendlocal = 0;

                if ((type == 'image' && sendData.indexOf(config.imgUri) <= -1) || (type == 'vedio' && sendData.src
                        .indexOf(config.imgUri) <= -1) || (type == 'voice' && sendData.url.indexOf(config.imgUri) <= -
                        1)) {

                    sendlocal = 1;
                } else {

                    this.$socket.send(data);
                }
                this.type = 'text';
                if (type !== 'image' && type !== 'voice') sendlocal = 1;

                var that = this;
                if (sendlocal == 1) {


                    //    setTimeout(function(){
                    var arr = {};
                    arr.id = that.group.id;
                    arr.cache_key = 'G' + arr.id;
                    arr['self'] = 1;
                    arr['isloading'] = 1;
                    arr['receiver_id'] = 0
                    arr['sender_id'] = that.sender.id;
                    arr['group_id'] = that.group.id;
                    arr['timestamp'] = parseInt(new Date().getTime() / 1000);
                    arr['time'] = '';
                    arr['message'] = {
                        type: type,
                        content: sendData
                    }
                    arr['sender'] = that.sender;
                    arr['receiver'] = that.group;
                    arr['nickname'] = that.sender.nickname;
                    arr['avatar'] = that.sender.avatar;
                    arr['msg_id'] = '';
                    arr['_mid'] = mid;
                    // that.$refs.panel.sendmsg({ data:arr});
                    that.sendingdata = arr;
                    that.sending = true;
                    //   console.log(arr)
                    // that.sendmsg(arr);
                    //  },20,that,mid)

                }

            },
            sendVoice(e) {

                this.commitMessage('voice', e);

            },
            sendEmoji(e) {
                this.commitMessage('face', e)
            },
            openProfile(e) {
                let params = {
                    id: e.id,
                    status: 'friend'
                };
                return this.$jump('friend.detail', params)
            }
        },
        onNavigationBarButtonTap() {
            this.$refs.panel.endVedio();
            this.$jump('group.detail', {
                id: this.group.id,
                'from': 'chat'
            });

        }

    }
</script>