<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="类别" prop="type">
        <el-input
          v-model="queryParams.type"
          placeholder="请输入类别"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="子类别" prop="subType">
        <el-input
          v-model="queryParams.subType"
          placeholder="请输入子类别"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="引用资讯ID" prop="refIds">
        <el-input
          v-model="queryParams.refIds"
          placeholder="请输入引用资讯ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="地区" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入地区"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:bWwwNewsRef:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:bWwwNewsRef:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:bWwwNewsRef:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:bWwwNewsRef:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bWwwNewsRefList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="类别" align="center" prop="type" />
      <el-table-column label="子类别" align="center" prop="subType" />
      <el-table-column label="内容" align="center" prop="description" />
      <el-table-column label="引用资讯ID" align="center" prop="refIds">
        <template #default="scope">
          <el-tooltip
            :content="getRefNewsTooltip(scope.row)"
            placement="top"
            :disabled="!scope.row.refIds"
            :show-after="200"
          >
            <el-link type="primary" @click="handlePreviewRefNews(scope.row)" :underline="false">
              {{ scope.row.refIds }}
            </el-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="地区" align="center" prop="location" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:bWwwNewsRef:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:bWwwNewsRef:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改通关指南对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="bWwwNewsRefRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类别" prop="type">
          <el-input v-model="form.type" placeholder="请输入类别" />
        </el-form-item>
        <el-form-item label="子类别" prop="subType">
          <el-input v-model="form.subType" placeholder="请输入子类别" />
        </el-form-item>
        <el-form-item label="内容" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="引用资讯ID" prop="refIds">
          <el-input v-model="form.refIds" placeholder="请输入引用资讯ID" />
        </el-form-item>
        <el-form-item label="地区" prop="location">
          <el-input v-model="form.location" placeholder="请输入地区" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 内容预览弹窗 -->
    <el-dialog v-model="previewOpen" title="引用资讯内容预览" width="80%" append-to-body>
      <div class="preview-content-wrapper">
        <div v-if="previewNewsList.length === 0" class="preview-loading">
          <el-icon class="is-loading"><Loading /></el-icon>
          <span>加载中...</span>
        </div>
        <div v-else>
          <div v-for="(news, index) in previewNewsList" :key="news.id || index" class="preview-news-item">
            <div class="preview-header" v-if="news.title">
              <h3>{{ news.title }}</h3>
              <div class="preview-meta" v-if="news.sendDate">
                <span>发布时间：{{ parseTime(news.sendDate, '{y}-{m}-{d}') }}</span>
              </div>
            </div>
            <div class="preview-content" v-html="formatContentWithImages(news.content)"></div>
            <el-divider v-if="index < previewNewsList.length - 1" />
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BWwwNewsRef">
import { listBWwwNewsRef, getBWwwNewsRef, delBWwwNewsRef, addBWwwNewsRef, updateBWwwNewsRef } from "@/api/system/bWwwNewsRef"
import { getBWwwNews } from "@/api/system/bWwwNews"
import { formatContentWithImages } from '@/utils/imageHelper'
import { Loading } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const { bool_values, news_type } = proxy.useDict('bool_values', 'news_type')

const bWwwNewsRefList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const previewOpen = ref(false)
const previewNewsList = ref([])
// 缓存资讯标题，避免重复请求
const newsTitleCache = reactive(new Map())
// 正在加载的ID集合，避免重复请求
const loadingIds = ref(new Set())

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    subType: null,
    description: null,
    refIds: null,
    location: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询通关指南列表 */
function getList() {
  loading.value = true
  listBWwwNewsRef(queryParams.value).then(response => {
    bWwwNewsRefList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    subType: null,
    description: null,
    refIds: null,
    location: null
  }
  proxy.resetForm("bWwwNewsRefRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加通关指南"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getBWwwNewsRef(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改通关指南"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bWwwNewsRefRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBWwwNewsRef(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBWwwNewsRef(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除通关指南编号为"' + _ids + '"的数据项？').then(function() {
    return delBWwwNewsRef(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/bWwwNewsRef/export', {
    ...queryParams.value
  }, `bWwwNewsRef_${new Date().getTime()}.xlsx`)
}

/** 获取引用资讯的提示内容 */
function getRefNewsTooltip(row) {
  if (!row.refIds) {
    return '无引用资讯'
  }
  
  // 解析 refIds
  const ids = String(row.refIds).split(',').map(id => id.trim()).filter(id => id)
  
  if (ids.length === 0) {
    return '引用资讯ID格式错误'
  }
  
  // 尝试从缓存中获取标题
  const titles = ids.map(id => {
    const cached = newsTitleCache.get(id)
    return cached ? cached : `资讯ID: ${id}`
  })
  
  // 如果缓存中有部分标题缺失，异步加载缺失的标题
  const missingIds = ids.filter(id => !newsTitleCache.has(id) && !loadingIds.value.has(id))
  if (missingIds.length > 0) {
    // 标记为正在加载
    missingIds.forEach(id => loadingIds.value.add(id))
    // 异步加载标题（不阻塞显示）
    loadNewsTitles(missingIds)
  }
  
  const content = titles.join('\n')
  return content + '\n\n点击查看详情'
}

/** 异步加载资讯标题 */
async function loadNewsTitles(ids) {
  try {
    const promises = ids.map(id => {
      return getBWwwNews(id)
        .then(res => {
          if (res.data && res.data.title) {
            newsTitleCache.set(id, res.data.title)
          }
        })
        .catch(() => {
          // 加载失败，不缓存
        })
        .finally(() => {
          // 移除加载标记
          loadingIds.value.delete(id)
        })
    })
    
    await Promise.all(promises)
  } catch (error) {
    // 清除所有加载标记
    ids.forEach(id => loadingIds.value.delete(id))
  }
}

/** 预览引用资讯内容 */
async function handlePreviewRefNews(row) {
  if (!row.refIds) {
    proxy.$modal.msgWarning('引用资讯ID为空')
    return
  }
  
  // 解析 refIds（可能是逗号分隔的ID列表）
  const ids = String(row.refIds).split(',').map(id => id.trim()).filter(id => id)
  
  if (ids.length === 0) {
    proxy.$modal.msgWarning('引用资讯ID格式错误')
    return
  }
  
  // 打开预览弹窗
  previewOpen.value = true
  previewNewsList.value = []
  
  // 批量获取资讯内容
  try {
    const promises = ids.map(id => {
      return getBWwwNews(id).then(res => {
        // 更新标题缓存
        if (res.data && res.data.title) {
          newsTitleCache.set(id, res.data.title)
        }
        return res.data
      }).catch(err => {
        console.error(`获取资讯 ${id} 失败:`, err)
        return {
          id: id,
          title: `资讯ID: ${id} (获取失败)`,
          content: '获取内容失败，请检查资讯ID是否正确',
          sendDate: null
        }
      })
    })
    
    const newsList = await Promise.all(promises)
    previewNewsList.value = newsList
  } catch (error) {
    console.error('批量获取资讯失败:', error)
    proxy.$modal.msgError('获取资讯内容失败')
    previewOpen.value = false
  }
}

getList()
</script>

<style scoped>
/* 预览弹窗样式 */
.preview-content-wrapper {
    max-height: 70vh;
    overflow-y: auto;
}

.preview-loading {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
    color: #909399;
}

.preview-loading .el-icon {
    margin-right: 8px;
    font-size: 20px;
}

.preview-news-item {
    margin-bottom: 30px;
}

.preview-news-item:last-child {
    margin-bottom: 0;
}

.preview-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #e5e5e5;
}

.preview-header h3 {
    margin: 0 0 10px 0;
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.preview-meta {
    font-size: 14px;
    color: #909399;
}

.preview-content {
    color: #606266;
    word-break: break-word;
    white-space: pre-wrap;
    line-height: 1.8;
    font-size: 14px;
}

.preview-content :deep(img) {
    max-width: 100%;
    height: auto;
    display: block;
    margin: 15px 0;
    border-radius: 4px;
    object-fit: contain;
}

.preview-content :deep(img[src=""]) {
    display: none;
}

.preview-content :deep(img:not([src])) {
    display: none;
}

.preview-content :deep(p) {
    margin: 10px 0;
}

.preview-content :deep(div) {
    margin: 10px 0;
}
</style>
