<template>
    <div class="app-container">
        <div class="page-container">
            <el-form :model="queryParams" :inline="true" label-width="80px">
                <el-form-item label="动态内容">
                    <el-input placeholder="请输入" v-model="queryParams.content" style="width: 240px;"></el-input>
                </el-form-item>
                <el-form-item label="话题">
                    <el-input placeholder="请输入" v-model="queryParams.topicNames" style="width: 240px;"></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input placeholder="请输入" v-model="queryParams.nickName" style="width: 240px;"></el-input>
                </el-form-item>
                <el-form-item label="学工号">
                    <el-input placeholder="请输入" v-model="queryParams.userName" style="width: 240px;"></el-input>
                </el-form-item>
                <el-form-item label="创建时间">
                    <el-date-picker placeholder="请选择" type="daterange" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                        v-model="dateRange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                        @change="dateChange"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="handleReset">重置</el-button>

                </el-form-item>
            </el-form>
            <el-row class="mb10">
                <el-button type="primary" @click="handleExport">导出</el-button>
            </el-row>
            <el-table :data="tableList">
              <el-table-column label="动态编号" align="center" prop="id" width="100"></el-table-column>
                <el-table-column label="动态内容" prop="content" align="center">
                    <template #default="{ row }">
                        <div v-html="formatContent(row.content)" class="content-container"></div>
                        <span v-if="row.type == 'IMAGE' && row.attachments && row.attachments.length > 0"
                            class="pic-box">
                            <span v-for="(img, idx) in row.attachments">[图片]</span>
                            <!-- <el-image :preview-src-list="row.previewList" class="img"
                                v-for="(img, idx) in row.attachments" :initial-index="idx" :key="idx"
                                :src="img.url"></el-image> -->
                        </span>
                        <span v-if="row.type == 'VIDEO' && row.attachments && row.attachments.length > 0"
                            class="pic-box">
                            <span v-for="(img, idx) in row.attachments">[视频]</span>
                            <!-- <video class="img" v-for="(img, idx) in row.attachments" :key="idx" :src="img.url"></video> -->
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="话题" align="center" prop="topicNames" width="200"></el-table-column>
                <el-table-column label="学工号" prop="userName" align="center" width="140"></el-table-column>
                <el-table-column label="姓名" prop="nickName" align="center" width="120"></el-table-column>
                <el-table-column label="部门(班级)" prop="deptName" align="center" width="120"></el-table-column>
                <el-table-column label="上级部门(学院)" prop="fullDeptName" align="center" width="160"></el-table-column>
                <el-table-column label="点赞数" prop="likeCount" align="center" width="80"></el-table-column>
                <el-table-column label="评论数" prop="commentCount" align="center" width="80"></el-table-column>
                <el-table-column label="创建时间" prop="createTime" align="center" width="160"></el-table-column>
                <el-table-column label="操作" align="center" width="160">
                    <template #default="{ row }">
                        <el-button type="text" @click="handleDetail(row)">详情</el-button>
                        <el-button type="text" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
        <!-- 动态详情 -->
        <detail-dialog ref="detailDialogRef" @refresh="getList"></detail-dialog>
    </div>
</template>

<script>
import { listData, delData } from '@/api/moments';
import DetailDialog from './DetailDialog.vue';
import emotions from '@/utils/emjo';
export default {
    name: 'Moments',
    data() {
        return {
            queryParams: {
                pageNum: 1,
                pageSize: 10
            },
            tableList: [],
            total: 0,
            dateRange: [],
            emotions,
            // 预创建表情符号到iconfont的映射表，提高性能
            emotionMap: {}
        }
    },
    components: {
        DetailDialog
    },
    created() {
        // 初始化表情映射表
        this.emotions.forEach(emotion => {
            this.emotionMap[emotion.symbol] = emotion.code;
        });
    },
    mounted() {
        this.getList()
    },
    methods: {
        // 列表数据
        getList() {
            listData(this.queryParams).then(res => {
                console.log(res)
                this.tableList = res.rows.map((item) => {
                    item.previewList = []
                    if (item.attachments && item.attachments.length > 0) {
                        item.previewList = item.attachments.map((img) => {
                            return img.url
                        })
                        return item;
                    }
                    return item;

                });
                this.total = res.total
            })
        },
        // 新增
        handleDetail(row) {
            this.$refs.detailDialogRef.openModal(row)
        },
        // 删除
        handleDelete(row) {
            this.$modal.confirm('确认要删除动态内容为：' + row.content + '的数据吗？').then(function () {
                return delData(row.id);
            }).then(() => {
                this.$modal.msgSuccess("删除成功");
                this.getList()
            })
        },
        dateChange(val) {
            if (val.length > 0) {
                this.queryParams['params[startTime]'] = val[0]
                this.queryParams['params[endTime]'] = val[1]
            }
        },
        // 查询
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList()
        },
        // 重置
        handleReset() {
            this.queryParams = {
                pageNum: 1,
                pageSize: 10
            }
            this.dateRange = []
            this.getList()
        },
        handleExport() {
            this.download('bbs/moment/list/export', {
                ...this.queryParams
            }, `动态_${new Date().getTime()}.xlsx`)
        },
        /**
         * 将内容中的表情符号转换为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" scoped>
.app-container {
    background-color: rgba(241, 242, 247, 1);
    height: calc(100vh - 50px);

    .page-container {
        background-color: white;
        height: 100%;
        border-radius: 6px;
        padding: 20px 30px;
        box-sizing: border-box;
        overflow: auto;
    }
}

.pic-box {
    display: flex;
    flex-wrap: wrap;
    justify-content: center;

    .img {
        color: #999;
        font-size: 12px;
    }
}
</style>
