<template>
    <el-dialog :visible.sync="visible" title="动态详情" width="26%" class="detail-dialog" :close-on-click-modal="false">
        <div class="dynamic-item">
            <div class="user-info-box">
                <img class="avatar" src="@/assets/images/default-avatar.png"></img>
                <div class="user-name">{{ form.nickName }}</div>
                <img class="more-icon" src="@/assets/images/more-icon.png"></img>
            </div>
            <div class="topics-box" v-if="form.topicNames && form.topicNames.length > 0">
                <template v-for="(name, index) in form.topicNames">
                    <div class="topic-box-common"># {{ name }}</div>
                </template>
            </div>
            <div class="dynamic-content-box">
                <div class="text" v-html="formatContent(form.content)"></div>
                <div class="imgs" v-if="form.type == 'IMAGE' && form.attachments && form.attachments.length > 0">
                    <template v-for="(item, index) in form.attachments">
                        <el-image class="item" :src="item.url" :preview-src-list="[item.url]"></el-image>
                    </template>
                </div>
                <div class="imgs" v-if="form.type == 'VIDEO' && form.attachments && form.attachments.length > 0">
                    <template v-for="(item, index) in form.attachments">
                        <video class="item" :src="item.url"></video>
                    </template>
                </div>
            </div>
            <div class="datetime-box">{{ form.createTime }}</div>
            <div class="operation-box">
                <div class="favorite-box">
                    <img src="@/assets/images/favorite.png" v-if="form.isLike == 0" class="icon"></img>
                    <img src="@/assets/images/favorite-active.png" v-if="form.isLike == 1" class="icon"></img>
                    <div class="num">{{ form.likeCount }}</div>
                </div>
                <div class="comment-box" style="border-top: 0;">
                    <img class="icon" src="@/assets/images/comment-icon.png"></img>
                    <div class="text">评论</div>
                </div>
            </div>
            <!-- pk -->
            <div class="pk-box" v-if="form.isEnableVote == 1">
                <div class="pk-title-box">
                    <img src="@/assets/images/pk-icon.png" class="pk-icon"></img>
                    <div class="pk-title-text">{{ form.voteTitle }}</div>
                </div>
                <div class="pk-imgs" v-if="form.voteOptionType == 'IMAGE' && form.voteOptions.length > 0">
                    <template v-for="(item, index) in form.voteOptions">
                        <img :src="item.imageUrl" class="img"></img>
                    </template>
                </div>
                <div class="pk-btns" v-if="form.voteOptions.length > 0">
                    <div class="btns red-btn">{{ form.voteOptions[0].name }}</div>
                    <img src="@/assets/images/pk-img.png" class="img"></img>
                    <div class="btns blue-btn">{{ form.voteOptions[1].name }}</div>
                </div>
                <div class="pk-tips">点击上方按钮，选择你的观点</div>
            </div>
            <!-- 评论区 -->
            <div class="comment-box" v-if="form.isEnableComment == 1">
                <div class="comment-display-box" v-if="commentList.length > 0">
                    <div class="comment-item" v-for="(item, index) in commentList">
                        <div class="user-info">
                            <div class="username">{{ item.nickName }}：</div>
                            <div class="datetime">{{ item.createTime }}</div>
                        </div>
                        <div class="content">
                            <div class="text" v-if="!item.replyNickName">
                                {{ item.content }}
                            </div>

                            <div class="text" v-else>
                                回复<span style="color: #0058B6;">{{ item.replyNickName }}：</span>{{ item.content }}
                            </div>
                            <div class="operation-text">
                                <div v-if="item.isFeatured == 1" style="color: #F2AC39;margin-right: 10rpx;">精选</div>
                                <div @click.stop="handleDelete(item)">删除</div>
                            </div>
                        </div>
                    </div>
                    <div class="show-more-box" v-if="commentList.length < total" @click="loadMore">
                        加载更多
                    </div>
                </div>
            </div>
        </div>
    </el-dialog>
</template>
<script>
import { detailData, getMomentComments } from '@/api/moments'
import { delData } from '@/api/comment';
import emotions from '@/utils/emjo';
export default {
    data() {
        return {
            visible: false,
            form: {},
            queryParams: {
                pageNum: 1,
                pageSize: 5
            },
            commentList: [],
            total: 0,
            currentRow: {},
            emotions,
            // 预创建表情符号到iconfont的映射表，提高性能
            emotionMap: {}
        }
    },
    methods: {
        openModal(row) {
            this.visible = true;
            this.currentRow = { ...row }
            this.queryParams.pageNum = 1;
            // 初始化表情映射表
            this.emotions.forEach(emotion => {
                this.emotionMap[emotion.symbol] = emotion.code;
            });
            this.commentList = [];
            this.getData();
            this.getComments()
        },
        // 详情
        getData() {
            detailData(this.currentRow.id).then(res => {
                console.log(res)
                this.form = { ...res.data }
            })
        },
        // 动态评论
        getComments() {
            getMomentComments(this.currentRow.id, this.queryParams).then(res => {
                console.log(res)
                this.commentList = [...this.commentList, ...res.rows] || []
                this.total = res.total
            })
        },
        loadMore() {
            this.queryParams.pageNum += 1;
            this.getComments()
        },
        // 删除
        handleDelete(row) {
            this.$modal.confirm('确认要删除评论内容为：' + row.content + '的数据吗？').then(function () {
                return delData(row.id);
            }).then(() => {
                this.$modal.msgSuccess("删除成功");
                this.commentList = [];
                this.getComments()
                this.$emit('refresh')
            })
        },
        /**
         * 将内容中的表情符号转换为iconfont标签
         * @param {string} content - 原始内容
         * @returns {string} 转换后的HTML字符串
         */
        formatContent(content) {
            if (!content) return '';

            let result = '';
            let remainingContent = content;

            // 提取所有表情符号并按长度排序（长表情优先匹配）
            const emotionSymbols = Object.keys(this.emotionMap).sort((a, b) => b.length - a.length);

            while (remainingContent.length > 0) {
                let found = false;

                // 查找是否有表情符号
                for (const symbol of emotionSymbols) {
                    if (remainingContent.startsWith(symbol)) {
                        // 添加表情标签
                        result += `<i class="iconfont ${this.emotionMap[symbol]} emotion-icon"></i>`;
                        remainingContent = remainingContent.slice(symbol.length);
                        found = true;
                        break;
                    }
                }

                // 如果没有找到表情，提取普通文本
                if (!found) {
                    // 找到下一个表情的位置
                    let nextEmotionIndex = remainingContent.length;
                    for (const symbol of emotionSymbols) {
                        const index = remainingContent.indexOf(symbol);
                        if (index !== -1 && index < nextEmotionIndex) {
                            nextEmotionIndex = index;
                        }
                    }

                    // 提取文本并进行HTML转义，防止XSS
                    const text = this.escapeHtml(remainingContent.slice(0, nextEmotionIndex));
                    result += text;
                    remainingContent = remainingContent.slice(nextEmotionIndex);
                }
            }

            return result;
        },

        /**
         * HTML转义处理，防止XSS攻击
         * @param {string} str - 需要转义的字符串
         * @returns {string} 转义后的字符串
         */
        escapeHtml(str) {
            if (!str) return '';
            return str.replace(/[&<>"']/g, char => {
                const entities = {
                    '&': '&amp;',
                    '<': '&lt;',
                    '>': '&gt;',
                    '"': '&quot;',
                    "'": '&#39;'
                };
                return entities[char] || char;
            });
        }

    }
}
</script>
<style lang="scss">
.detail-dialog {
    .el-dialog__body {
        padding: 0 20px !important;
    }
}
</style>
<style lang="scss" scoped>
.topic-box-common {
    height: 26px;
    padding: 0 10px;
    background-color: rgba(0, 123, 255, 0.1);
    color: rgba(52, 132, 253, 1);
    border-radius: 13px;
    line-height: 26px;
    margin-right: 10px;
    margin-bottom: 5px;
}

.dynamic-item {
    background-color: white;
    width: 100%;
    min-height: 200px;
    margin-bottom: 10px;
    padding: 8px 17px 18px 17px;
    box-sizing: border-box;

    .user-info-box {
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
        }

        .user-name {
            width: calc(100% - 84px);
            color: rgba(16, 16, 16, 1);
        }

        .more-icon {
            width: 24px;
            height: 24px;
        }
    }

    .topics-box {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 5px;
    }

    .dynamic-content-box {
        margin-bottom: 10px;

        .text {
            color: rgba(16, 16, 16, 1);
            font-size: 16px;
            margin-bottom: 10px;
        }

        .imgs {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            grid-template-rows: auto;
            row-gap: 3px;
            column-gap: 3px;

            .item {
                width: 100%;
                height: 112px;
            }
        }
    }

    .datetime-box {
        color: rgba(187, 187, 187, 1);
        margin-bottom: 10px;
    }

    .operation-box {
        display: flex;
        align-items: center;
        justify-content: space-between;

        .favorite-box {
            width: 56px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid rgba(245, 245, 245, 1);

            .icon {
                width: 18px;
                height: 18px;
                margin-right: 6px;
            }

            .num {
                color: rgba(162, 170, 184, 1);
                font-size: 12px;
            }

            .active {
                color: rgba(245, 166, 35, 1);
            }
        }

        .comment-box {
            display: flex;
            align-items: center;

            .icon {
                width: 18px;
                height: 18px;
                margin-right: 6px;
            }

            .text {
                color: rgba(142, 153, 171, 1);
                font-size: 14px;
            }
        }
    }

    .pk-box {
        border-top: 1px solid #eee;
        margin-top: 16px;

        .pk-title-box {
            height: 52px;
            display: flex;
            align-items: center;

            .pk-icon {
                width: 20px;
                height: 20px;
                margin-right: 4px;
            }

            .pk-title-text {
                color: rgba(16, 16, 16, 1);
                font-size: 12px;
            }
        }

        .pk-imgs {
            display: flex;
            align-items: center;
            justify-content: center;

            .img {
                width: 80px;
                height: 80px;
                margin: 0 3px;
            }
        }

        .pk-btns {
            margin: 10px 0;
            display: flex;
            align-items: center;
            justify-content: center;

            .btns {
                width: 104px;
                height: 38px;
                line-height: 38px;
                color: rgba(255, 255, 255, 1);
                font-size: 12px;
                text-align: center;
            }

            .red-btn {
                border-radius: 34px 3px 3px 34px;
                background-color: rgba(255, 100, 95, 1);
            }

            .blue-btn {
                border-radius: 3px 34px 34px 3px;
                background-color: rgba(52, 132, 253, 1);
            }

            .img {
                width: 36px;
                height: 36px;
                margin: 0 13px;
            }

        }

        .pk-tips {
            margin-top: 6px;
            color: rgba(153, 153, 153, 1);
            font-size: 12px;
        }
    }

    .comment-box {
        border-top: 1px solid #eee;
        margin-top: 16px;

        .comment-display-box {
            background-color: rgba(245, 245, 247, 1);
            min-height: 40px;
            margin-top: 16px;
            padding: 12px 10px;
            box-sizing: border-box;

            .comment-item {
                .user-info {
                    display: flex;
                    justify-content: space-between;
                    font-size: 12px;

                    .username {
                        width: calc(100% - 300rpx);
                        color: black;
                        color: #0058B6;
                    }

                    .datetime {
                        width: 145px;
                        text-align: right;
                        color: #999999;
                    }
                }

                .content {
                    color: black;
                    margin: 5px 0;
                    display: flex;

                    .text {
                        width: calc(100% - 90px);
                    }

                    .operation-text {
                        width: 90px;
                        text-align: right;
                        font-size: 12px;
                        display: flex;
                        align-items: center;
                        justify-content: flex-end;
                        cursor: pointer;
                    }

                    .mr10 {
                        margin-right: 6px;
                    }

                    .add-text {
                        color: #0058B6;
                    }
                }

                .tips {
                    font-size: 12px;
                    color: #F5A623;
                }
            }
        }
    }
}

.show-more-box {
    height: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #BBBBBB;
    font-size: 12px;
    cursor: pointer;

    .icon {
        width: 16px;
        height: 16px;
    }
}
</style>
