<template>
    <view class="page" ref="page">
        <view style="display: none;position: fixed;left: 50%;top: 50%;">{{ $store.state.hackUpdate }}</view>
        <load-more status="loading" v-if="initializing" />
        <!-- 消息记录 -->
        <chat-panel :storeKey="storeKey" :sending="sending" :sendingdata="sendingdata" @click-avatar="openProfile"
            @setSending="setSending" :boardheight="boardheight" @chooseQuote="setQuote" ref="panel" />
        <!-- 底部 -->
        <v-sender v-if="!initializing" v-model="message" ref="sender" @send="sendTextMessage" @face="sendVoice"
            @sendImage="sendImg" @sendVedio="sendVedio" @emoji="sendEmoji" @input="inputMessage"
            @handleEmotion="handleEmotion" @senderheight="set_sheight" @keyboardheight="keyboardheight"
            :showboard="showboard" :sendtype="type" :isgroup="0" :groupid="friend.id" :quote="quoteItem" />
    </view>
</template>


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

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

            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;
            })

        },

        onLoad(opts) {

            uni.setNavigationBarTitle({
                title: decodeURI(opts.nickname)
            });
            // #ifdef APP-PLUS  
            let currentWebview = this.$mp.page.$getAppWebview();
            currentWebview.setStyle({
                titleNView: {
                    titleText: ''
                },
            })
            // #endif

            this.friend = opts;

            this.storeKey = 'U' + this.friend.id;
            uni.setStorageSync('cache_key', this.storeKey);

            this.getUserInfo(this.friend.id);
            this.sender = this.user;
            this.receiver = this.friend;

        },
        onUnload() {

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


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

                    id = parseInt(id);
                    http.setWait(false).get('user.php?act=userdetail', {
                        id: id,
                        group_id: 0,
                        userid: this.user.id
                    }).then(res => {
                        this.friend = res.data;
                        uni.setNavigationBarTitle({
                            title: decodeURI(this.friend.nickname)
                        });

                    })


                } else {
                    var avatar = this.system.admin_logo;
                    if (avatar.indexOf('http') <= -1) avatar = config.imgUri + avatar;
                    this.friend = {
                        id: 0,
                        nickname: this.system.admin_nickname,
                        avatar: avatar
                    };

                }

            },
            toHtml(str) {
                str = str.replace(/ /g, "&nbsp;");
                str = str.replace(/\n/g, "<br>");
                return str;
            },
            set_sheight(e) {
                this.$refs.panel.setAutoHeight(e);
            },
            keyboardheight(e) {
                this.boardheight = e;

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

            // 选择表情
            handleEmotion(value) {
                //  console.log(value);
                this.emotion = value;
                this.type = 'emotion';
            },
            sendEmoji(e) {
                this.commitMessage('face', e);
            },
            sendImg(e) {
                this.commitMessage('image', e);
            },
            sendVedio(e) {
                this.commitMessage('vedio', e);
            },

            // 发送文本消息
            sendTextMessage() {
                // this.commitMessage('text',this.message);
                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
                    }
                    console.log('-------------表情---------------', this.emotionInfo);
                    this.commitMessage('emotion', this.emotionInfo);
                } else {
                    var msg = this.toHtml(this.message) + addStr;
                    console.log('---------文本发送---------', msg);
                    this.commitMessage('text', msg,1);
                }
                this.quoteItem = {}
                this.$refs.sender.clearQute()
            },
            setSending(e) {
                this.sending = e;
            },
            commitMessage(type, sendData) {
                this.message = '';
                //   this.showboard=true
                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);
                }

                let data = {
                    userid: this.user.id,
                    friend_uid: this.friend.id,
                    type: 'chat',
                    msgtype: type,
                    content: sendData,
                    mid: mid
                };
                //    console.log(data);

                var sendlocal = 0;
                if ((type == 'image' && sendData.indexOf('http') <= -1) || (type == 'vedio' && sendData.src.indexOf(
                        'http') <= -1) || (type == 'voice' && sendData.url.indexOf('http') <= -1)) {
                    //本地图片不发到服务器  
                    // console.log(sendData);
                    sendlocal = 1;
                } else {
                    this.$socket.send(data);
                }
                if (type !== 'image' && type !== 'voice') sendlocal = 1;
                // uni.showLoading({
                //     title: '发送中'
                // });

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

                    var arr = {};
                    arr.id = that.receiver.id;
                    arr.cache_key = 'U' + arr.id;
                    arr['self'] = 1;
                    arr['isloading'] = 1;
                    arr['receiver_id'] = arr['id'];
                    arr['sender_id'] = that.sender.id;
                    arr['group_id'] = 0;
                    arr['timestamp'] = parseInt(new Date().getTime() / 1000);
                    arr['time'] = '';
                    arr['message'] = {
                        type: type,
                        content: sendData
                    };
                    arr['sender'] = that.sender;
                    arr['receiver'] = that.receiver;
                    arr['nickname'] = that.sender.nickname;
                    arr['avatar'] = that.sender.avatar;
                    arr['msg_id'] = '';
                    arr['_mid'] = mid;
                    that.sendingdata = arr;
                    that.sending = true;
                    this.type = 'text';

                    //that.sendmsg(arr);
                    // console.log(sendlocal);
                }

                //that.sending=true;
            },

            sendVoice(e) {
                this.commitMessage('voice', e);
            },
            openProfile(e) {
                //     console.log(JSON.stringify(e));
                let params = {
                    id: e.id,
                    status: 'friend'
                };
                return this.$jump('friend.detail', params);
            }
        },
        onNavigationBarButtonTap(e) {
            let params = {
                ...this.friend,
                status: 'friend'
            };
            return this.$jump('friend.userset', params);
        }
    };
</script>

<style lang="scss">
    $avatar-width: 80upx;
    $control-height: 100upx;
    $control-input-height: $control-height - $uni-spacing-col-base * 2;


    .placeholder {
        width: 750upx;
        height: 1upx;
    }

    .message {
        &-time {
            color: #999;
            font-size: 24upx;
            text-align: center;
        }

        &-info {
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: flex-start;
            padding: $uni-spacing-col-lg $uni-spacing-row-lg;

            .spacing {
                width: $uni-spacing-row-lg;
                height: $avatar-width;
                position: relative;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;

                &::before {
                    display: block;
                    content: '';
                    border: $uni-spacing-row-lg/2 solid transparent;
                    border-right-color: #fff;
                }
            }
        }

        &.right &-info {
            flex-direction: row-reverse;
            padding-left: $uni-spacing-row-lg;
            padding-right: $uni-spacing-row-lg * 2 + $avatar-width;

            .spacing::before {
                border-right-color: transparent;
                border-left-color: $uni-color-primary;
            }
        }

        &.right &-info {
            padding-left: $uni-spacing-row-lg * 2 + $avatar-width;
            padding-right: $uni-spacing-row-lg;
        }

        &-avatar {
            width: $avatar-width;
            height: $avatar-width;
            vertical-align: middle;
            border-radius: $uni-border-radius-base;
            flex-shrink: 0;
        }

        &-content {
            font-size: 32upx;
            background: rgba(255, 255, 255, 1);
            border-radius: $uni-border-radius-base;
        }

        &.right &-content {
            color: white;
            background-color: $uni-color-primary;
        }

        &--text &-content {
            padding: 20upx $uni-spacing-row-base;
        }

        &-failed {
            width: 30upx;
            height: 30upx;
            background-color: $uni-color-error;
            border-radius: 50%;
            margin: ($avatar-width - 30upx)/2 $uni-spacing-row-base 0;
        }
    }
</style>