<template>
    <el-dialog v-el-drag-dialog title="聊天室" :visible.sync="dialogVisible" width="40%" :before-close="handleClose"
        @open="handleDialogOpen">
        <div class="info-messageInfo">
            <div class="messageInfo-content">
                <div id="chatContent" class="chatContent" ref="chatContent">
                    <div v-for="item in chatMessageList" class="everyMessage">
                        <div :style="{ justifyContent: item.fromUserId == userInfo.account ? 'flex-end' : 'flex-start' }">
                            <template v-if="item.fromUserId != userInfo.account">
                                <img class="avatarImg" :src="avatar" alt="">
                                <!-- <div v-text="item.content" style="background-color:white"></div> -->
                                <div v-if="item.messageForm == 'TEXT'" v-html="item.content" style="background-color: white;">
                                </div>
                                <el-image v-else-if="item.messageForm == 'PICTURE'"  style="width: 150px; height: 100px"
                                    :src="item.content" :preview-src-list="[item.content]">
                                </el-image>
                            </template>
                            <template v-else-if="item.fromUserId == userInfo.account">
                                <div v-if="item.messageForm == 'TEXT'" v-html="item.content"
                                    style="background-color: #85ce61;">
                                </div>
                                <el-image v-else-if="item.messageForm == 'PICTURE'"  style="width: 150px; height: 100px"
                                    :src="item.content" :preview-src-list="[item.content]">
                                </el-image>
                                <img class="avatarImg" :src="avatar" alt="">
                            </template>
                        </div>
                    </div>
                </div>
                <div class="chatSendMessage">
                    <div class="messageContent">
                        <div ref="editor" class="preview" contenteditable @paste.prevent="onPaste" @input="inputText"></div>
                        <!-- <el-input type="textarea" autosize placeholder="请输入内容" v-model="sendMessage">
                        </el-input> -->
                    </div>
                    <div class="sendMessageButtonList">
                        <el-button size="mini" type="success" @click="sendMessageFn">发送</el-button>
                    </div>
                </div>
            </div>
        </div>
    </el-dialog>
</template>


<script>
import avatar from '../../../assets/img/ddkz/headPhoto.jpg';
import { getRecordsByPagingTeam } from '../../../api/chat/chatRecords';
import elDragDialog from "@/util/directive/el-dragDialog";
import onPaste from '@/util/onPaste.js';
import { upLoadFiles } from '@/api/chat/chatRoom';
import { getTime_extent, download } from '@/util/http_util.js';
export default {
    data() {
        return {
            dialogVisible: false,
            avatar: avatar,
            sendMessage: [],
            chatMessageList: [],
            // stompClient: '',
            // ws: null,
            analogDataList: [],
            currentChatRoom: {},
            myStompClient: null,
            file: null,
            imgList: [],
            noticeMessage: ''
        }
    },
    directives: {
        elDragDialog
    },
    props: {
        visible: Boolean,
        analogData: Array,
        stompClient: Object,
        currentChatRoomInfo: Object

    },
    methods: {
        handleClose() {
            this.dialogVisible = false;
            // this.$emit('handleCancel');
        },
        showDialog() {
            this.dialogVisible = true;
        },
        base64ImgtoFile(dataurl, filename = 'file') {
            const arr = dataurl.split(',')
            const mime = arr[0].match(/:(.*?);/)[1]
            const suffix = mime.split('/')[1]
            const bstr = atob(arr[1])
            let n = bstr.length
            const u8arr = new Uint8Array(n)
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
                type: mime
            })
        },
        upLoadImg() {

        },
        sendMessageFn() {
            if (this.$refs.editor.innerHTML.trim().length > 0) {
                this.sendMessage = []
                let tmpArr = this.$refs.editor.innerHTML.trim().split(/\<img\s*src=\"([^\"]*?)\"[^>]*>/gi).filter(item => item.length !== 0);
                this.imgList = [];
                tmpArr.forEach((item, index) => {
                    let tmpObj = { content: item, messageForm: 'TEXT' }
                    if (item.indexOf('data:image/jpeg;base64') == 0) {
                        let obj = { index: index, url: item }
                        this.imgList.push(obj);
                        tmpObj.messageForm = 'PICTURE';
                    }
                    this.sendMessage.push(tmpObj);
                })
                let promiseArr = [];
                for (let i = 0; i < this.imgList.length; i++) {
                    let p = new Promise((resolve, reject) => {
                        let fd = new FormData();
                        fd.append('file', this.base64ImgtoFile(this.imgList[i].url));
                        upLoadFiles('CHAT', fd).then(res => {
                            this.sendMessage[this.imgList[i].index].content = 'api/rest/file/viewPicture/CHAT?objectName=' + res;
                            resolve();
                        })
                    })
                    promiseArr.push(p);
                }
                Promise.all(promiseArr).then(res => {
                    for (let i = 0; i < this.sendMessage.length; i++) {
                        this.myStompClient.send("/app/sendToChatRoomTeam/" + this.currentChatRoom.id + '/' + this.currentChatRoom.teamId, {}, JSON.stringify({
                            'content': this.sendMessage[i].content,
                            messageForm: this.sendMessage[i].messageForm,
                        }));
                    }
                })
            } else {
                this.$message.warning('不能发送空白信息');
            }
            setTimeout(() => {
                this.keepBottom();
                this.sendMessage = [];
                this.$refs.editor.innerHTML = '';
            }, 100);
        },
        keepBottom() {
            this.$refs.chatContent.scrollTop = this.$refs.chatContent.scrollHeight;
        },
        listChatroom(data) {
            //取消群聊的订阅
            for (const sub in this.stompClient.subscriptions) {
                if (sub.startsWith("multicast")) {
                    this.stompClient.unsubscribe(sub);
                }
            }
            data.forEach(e => {
                //订阅聊天室主题，订阅功能中设置ID：
                this.stompClient.subscribe('/topic/multicast/' + e.id + '/' + e.teamId, data => {
                    this.chatMessageList.push({
                        content: JSON.parse(data.body).content,
                        fromUserId: data.headers.fromUserId,
                        messageForm: JSON.parse(data.body).messageForm
                    });
                    this.$nextTick(() => {
                        this.keepBottom();
                    });
                }, { id: "multicast" + e.id + new Date().getTime() });

            })
        },
        getCurrentMessageList(item) {
            //查询我方聊天记录
            getRecordsByPagingTeam(item.id, 1, 500, '2023-10-01 00:00:00', getTime_extent(0).pre_rq_end, null, item.teamId).then(res1 => {
                this.chatMessageList = res1.records;
                this.$nextTick(() => {
                    this.keepBottom();
                });
            })
        },
        handleDialogOpen() {
            this.analogDataList = this.$props.analogData;
            this.currentChatRoom = this.$props.currentChatRoomInfo;
            this.myStompClient = this.$props.stompClient;
            //订阅
            this.listChatroom(this.analogDataList);
            this.getCurrentMessageList(this.$props.currentChatRoomInfo);
        },
        // 监听输入框内容
        inputText(event) {

        },
        onPaste(event) {
            new Promise((resolve, reject) => {
                const result = onPaste(event);
                result.then(res => {
                    const imgRegx = /^data:image\/png|jpg|jpeg|gif|svg|bmp|tif/; // 支持的图片格式
                    if (res.type) {
                        if (imgRegx.test(res.compressedDataUrl)) {
                            const sel = window.getSelection(); // 获取当前光标位置
                            if (sel && sel.rangeCount === 1 && sel.isCollapsed) {
                                const range = sel.getRangeAt(0);
                                const img = new Image();
                                img.src = res.compressedDataUrl; // 使用压缩后的图片
                                range.insertNode(img);
                                range.collapse(false);
                                sel.removeAllRanges();
                                sel.addRange(range);
                                resolve('hi');
                            }
                        }
                    } else {
                        document.execCommand('insertText', false, res.data);
                    }
                })

            })
        }
    },
    computed: {
        userInfo() {
            if (this.$store.getters.userInfo) {
                return this.$store.getters.userInfo;
            } else {
                return { account: "" };
            }
        }
    }
}
</script>

<style lang="scss">
.info-messageInfo {
    width: 100%;
    height: 60%;

    .title {
        width: 100%;
        height: 30px;
        line-height: 30px;

        img {
            width: 20px;
            height: 20px;
        }

        span {
            font-size: 16px;
            font-weight: 500;
            color: white;
            vertical-align: text-bottom;
        }
    }

    .messageInfo-content {
        width: 100%;
        height: calc(100% - 40px);
        margin-top: 10px;
        padding: 0px 10px;
        border: 1px solid #515151c9;
        box-sizing: border-box;

        .chatContent {
            width: 100%;
            height: 64%;
            border-bottom: 1px solid #37383f;
            padding: 10px 0px;
            box-sizing: border-box;
            overflow-y: auto;

            .everyMessage {
                width: 100%;
                margin-top: 10px;

                &>div {
                    width: 100%;
                    display: flex;
                    align-items: flex-start;
                    margin-top: 10px;
                    font-size: 13px;



                    .avatarImg {
                        width: 20px;
                        height: 20px;
                        margin: 0px 10px;
                    }

                    .el-imgage {
                        img {
                            width: 100%;
                            height: 100%;
                        }
                    }

                    &>div {
                        max-width: 50%;
                        padding: 5px 10px;
                        border-radius: 5px;
                        color: black;
                    }
                }
            }
        }

        .chatSendMessage {
            width: 100%;
            height: 35%;
            position: relative;

            .messageContent {
                width: 100%;
                height: 100%;
                padding: 5px 0px;
                box-sizing: border-box;

                .preview {
                    width: 100%;
                    height: 100%;
                    padding: 10px;
                    box-sizing: border-box;
                    color: white;
                    border: 1px solid #474748;
                    outline: none;
                    /* 隐藏聚焦时外边框 */
                    white-space: pre-wrap;
                    overflow: hidden;
                    overflow-y: auto;
                    word-break: break-all;
                }

                .el-textarea__inner {
                    height: 100% !important;
                    color: white !important;
                    background-color: transparent !important;
                    border: 1px solid #37383f !important;
                }
            }

            .sendMessageButtonList {
                position: absolute;
                right: 10px;
                bottom: 15px;
            }
        }
    }
}
</style>