<!--
  * 用户评论-临床病例-文章
  *
  * @Author:    xing
  * @Date:      2025-08-12 09:11:31
  * @Copyright  gdxz
-->
<template>
    <!---------- 查询表单form begin ----------->
    <a-form class="smart-query-form">
        <a-row class="smart-query-form-row">
            <a-form-item label="关键词" class="smart-query-form-item">
                <a-input style="width: 200px" v-model:value="queryForm.keywords" placeholder="评论内容、文章标题" />
            </a-form-item>
            <a-form-item label="是否置顶" class="smart-query-form-item">
                <a-select style="width: 120px" v-model:value="queryForm.isTop" placeholder="请选择" allowClear>
                    <a-select-option :value="0">否</a-select-option>
                    <a-select-option :value="1">是</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="是否敏感词" class="smart-query-form-item">
                <a-select style="width: 120px" v-model:value="queryForm.isSensitive" placeholder="请选择" allowClear>
                    <a-select-option :value="0">否</a-select-option>
                    <a-select-option :value="1">是</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="onSearch">
                    <template #icon>
                        <SearchOutlined />
                    </template>
                    查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                    <template #icon>
                        <ReloadOutlined />
                    </template>
                    重置
                </a-button>
            </a-form-item>
        </a-row>
    </a-form>
    <!---------- 查询表单form end ----------->

    <a-card size="small" :bordered="false" :hoverable="true">
        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block">
            <div class="smart-table-operate-block">
                <a-button @click="confirmBatchDelete" type="primary" danger size="small" :disabled="selectedRowKeyList.length == 0">
                    <template #icon>
                        <DeleteOutlined />
                    </template>
                    批量删除
                </a-button>
            </div>
            <div class="smart-table-setting-block">
                <!-- 移除TableOperator组件 -->
            </div>
        </a-row>
        <!---------- 表格操作行 end ----------->

        <!---------- 表格 begin ----------->
        <a-table
            :columns="columns"
            :data-source="tableData"
            :loading="tableLoading"
            :pagination="false"
            :scroll="{ x: 1700 }"
            size="small"
            bordered
            :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
        >
            <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'commentType'">
                    <a-tag :color="record.parentId ? 'blue' : 'green'">
                        {{ record.parentId ? '回复' : '评论' }}
                    </a-tag>
                </template>
                <template v-if="column.dataIndex === 'action'">
                    <div class="smart-table-operate">
                        <a-button @click="updateTopStatus(record.commentId, record.isTop === 1 ? 0 : 1)" type="link">
                            {{ record.isTop === 1 ? '取消置顶' : '置顶' }}
                        </a-button>
                        <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                    </div>
                </template>
            </template>
        </a-table>
        <!---------- 表格 end ----------->

        <div class="smart-query-table-page">
            <a-pagination
                showSizeChanger
                showQuickJumper
                show-less-items
                :pageSizeOptions="PAGE_SIZE_OPTIONS"
                :defaultPageSize="queryForm.pageSize"
                v-model:current="queryForm.pageNum"
                v-model:pageSize="queryForm.pageSize"
                :total="total"
                @change="queryData"
                @showSizeChange="queryData"
                :show-total="(total) => `共${total}条`"
            />
        </div>

        <!-- 图片预览Modal -->
        <a-modal
            v-model:open="imageModalVisible"
            :footer="null"
            :width="800"
            :title="'图片预览'"
            centered
        >
            <div style="text-align: center;">
                <img 
                    :src="currentImageUrl" 
                    style="max-width: 100%; max-height: 600px; object-fit: contain;"
                    alt="图片预览"
                />
            </div>
        </a-modal>
    </a-card>
</template>
<script setup>
    import { reactive, ref, onMounted, h } from 'vue';
    import { message, Modal } from 'ant-design-vue';
    import { SmartLoading } from '/@/components/framework/smart-loading';
    import { userCommentClinicalArticleApi } from '/@/api/business/user-comment-clinical-article/user-comment-clinical-article-api';
    import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
    import { smartSentry } from '/@/lib/smart-sentry';

    // ---------------------------- 表格列 ----------------------------

    const columns = ref([
        { title: '用户名称', dataIndex: 'userName', ellipsis: true, width: 120 },
        { title: '医院名称', dataIndex: 'hospitalName', width: 200, customRender: ({ text }) => text || '-', 
          customCell: () => ({
            style: {
              whiteSpace: 'pre-wrap',
              wordBreak: 'break-word',
              maxWidth: '200px'
            }
          })
        },
        { title: '类型', dataIndex: 'commentType', ellipsis: true, width: 80 },
        { title: '文章标题', dataIndex: 'articleTitle', ellipsis: false, width: 200, customRender: ({ text }) => h('div', { style: { 'white-space': 'pre-wrap', 'word-break': 'break-all', 'line-height': '1.4' } }, text || '-') },
        { title: '评论状态', dataIndex: 'status', ellipsis: true, width: 80, customRender: ({ text }) => h('a-tag', { 
            color: text === 1 ? 'success' : 'error'
        }, text === 1 ? '正常' : '禁用') },
        { title: '是否置顶', dataIndex: 'isTop', ellipsis: true, width: 80, customRender: ({ text }) => h('a-tag', { 
            color: text === 1 ? 'processing' : 'default'
        }, text === 1 ? '是' : '否') },
        { title: '评论内容', dataIndex: 'content', ellipsis: false, width: 200, customRender: ({ text }) => h('div', { style: { 'white-space': 'pre-wrap', 'word-break': 'break-all', 'line-height': '1.4' } }, text || '-') },
        { title: '评论图片', dataIndex: 'commentImage', ellipsis: false, width: 150, customRender: ({ text }) => {
            if (!text) return h('span', '-');
            const images = text.split(',').filter(img => img.trim());
            if (images.length === 0) return h('span', '-');
            
            return h('div', { style: { display: 'flex', gap: '5px', flexWrap: 'wrap' } }, 
                images.map((img, index) => 
                    h('img', {
                        src: img.trim(),
                        style: { width: '50px', height: '50px', objectFit: 'cover', cursor: 'pointer' },
                        onClick: () => showImageModal(img.trim())
                    })
                )
            );
        }},
        { title: '创建时间', dataIndex: 'createdAt', ellipsis: true, width: 120 },
        { title: '操作', dataIndex: 'action', fixed: 'right', width: 200 },
    ]);

    // ---------------------------- 查询数据表单和方法 ----------------------------

    const queryFormState = {
        keywords: undefined, //关键词
        isTop: undefined, //是否置顶
        isSensitive: undefined, //是否存在敏感词
        pageNum: 1,
        pageSize: 10,
    };
    // 查询表单form
    const queryForm = reactive({ ...queryFormState });
    // 表格加载loading
    const tableLoading = ref(false);
    // 表格数据
    const tableData = ref([]);
    // 总数
    const total = ref(0);
    // 选中的行
    const selectedRowKeyList = ref([]);

    // 重置查询条件
    function resetQuery() {
        let pageSize = queryForm.pageSize;
        Object.assign(queryForm, queryFormState);
        queryForm.pageSize = pageSize;
        queryData();
    }

    // 搜索
    function onSearch(){
      queryForm.pageNum = 1;
      queryData();
    }

    // 查询数据
    async function queryData() {
        tableLoading.value = true;
        try {
            let queryResult = await userCommentClinicalArticleApi.queryPage(queryForm);
            tableData.value = queryResult.data.list;
            total.value = queryResult.data.total;
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            tableLoading.value = false;
        }
    }

    onMounted(queryData);

    // ---------------------------- 添加/修改 ----------------------------
    // 修改状态
    async function updateStatus(commentId, status) {
        const statusText = status === 1 ? '启用' : '禁用';
        
        Modal.confirm({
            title: '提示',
            content: `确定要${statusText}这条评论吗?`,
            okText: '确定',
            onOk() {
                requestUpdateStatus(commentId, status);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    async function requestUpdateStatus(commentId, status) {
        SmartLoading.show();
        try {
            await userCommentClinicalArticleApi.updateStatus(commentId, status);
            message.success('操作成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 修改置顶状态 ----------------------------
    async function updateTopStatus(commentId, isTop) {
        const topText = isTop === 1 ? '取消置顶' : '置顶';
        
        Modal.confirm({
            title: '提示',
            content: `确定要${topText}这条评论吗?`,
            okText: '确定',
            onOk() {
                requestUpdateTopStatus(commentId, isTop);
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    async function requestUpdateTopStatus(commentId, isTop) {
        SmartLoading.show();
        try {
            await userCommentClinicalArticleApi.updateTopStatus(commentId, isTop);
            message.success('操作成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 单个删除 ----------------------------
    // 批量删除
    function batchDelete() {
        if (selectedRowKeyList.value.length === 0) {
            message.warning('请选择要删除的评论');
            return;
        }
        
        Modal.confirm({
            title: '批量删除',
            content: `确定要删除选中的 ${selectedRowKeyList.value.length} 条评论吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk() {
                // 这里可以调用批量删除API
                message.success('批量删除功能待实现');
                selectedRowKeyList.value = [];
            }
        });
    }

    // 删除单条评论
    function onDelete(record) {
        Modal.confirm({
            title: '删除评论',
            content: `确定要删除这条评论吗？`,
            okText: '确定',
            cancelText: '取消',
            onOk() {
                requestDelete(record.commentId);
            }
        });
    }

    // 请求删除评论
    async function requestDelete(commentId) {
        try {
            SmartLoading.show();
            await userCommentClinicalArticleApi.delete(commentId);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
            message.error('删除失败');
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 批量删除 ----------------------------

    // 选择表格行
    function onSelectChange(selectedRowKeys) {
        selectedRowKeyList.value = selectedRowKeys;
    }

    // 批量删除
    function confirmBatchDelete() {
        Modal.confirm({
            title: '提示',
            content: '确定要批量删除这些数据吗?',
            okText: '删除',
            okType: 'danger',
            onOk() {
                requestBatchDelete();
            },
            cancelText: '取消',
            onCancel() {},
        });
    }

    //请求批量删除
    async function requestBatchDelete() {
        try {
            SmartLoading.show();
            await userCommentClinicalArticleApi.batchDelete(selectedRowKeyList.value);
            message.success('删除成功');
            queryData();
        } catch (e) {
            smartSentry.captureError(e);
        } finally {
            SmartLoading.hide();
        }
    }

    // ---------------------------- 图片预览 ----------------------------
    const imageModalVisible = ref(false);
    const currentImageUrl = ref('');

    function showImageModal(url) {
        currentImageUrl.value = url;
        imageModalVisible.value = true;
    }
</script>
