<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-select v-model="queryParams.type" placeholder="请选择类别" clearable style="width: 160px">
          <el-option
            v-for="dict in news_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="来源" prop="f">-->
<!--        <el-input-->
<!--          v-model="queryParams.f"-->
<!--          placeholder="请输入来源"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="日期" prop="sendDate">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.sendDate"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择日期">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="点击数" prop="clicked">-->
<!--        <el-input-->
<!--          v-model="queryParams.clicked"-->
<!--          placeholder="请输入点击数"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="状态" prop="status">-->
<!--        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>-->
<!--          <el-option-->
<!--            v-for="dict in bool_values"-->
<!--            :key="dict.value"-->
<!--            :label="dict.label"-->
<!--            :value="dict.value"-->
<!--          />-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item label="关键词" prop="keywords">-->
<!--        <el-input-->
<!--          v-model="queryParams.keywords"-->
<!--          placeholder="请输入关键词"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="置顶显示" prop="isTop">
        <el-select v-model="queryParams.isTop" placeholder="请选择置顶显示"  clearable style="width: 160px">
          <el-option
            v-for="dict in bool_values"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="创建时间" prop="createTime">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.createTime"-->
<!--          type="date"-->
<!--          value-format="YYYY-MM-DD"-->
<!--          placeholder="请选择创建时间">-->
<!--        </el-date-picker>-->
<!--      </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 label="原id" prop="originId">-->
<!--        <el-input-->
<!--          v-model="queryParams.originId"-->
<!--          placeholder="请输入原id"-->
<!--          clearable-->
<!--          @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="source" prop="source">-->
<!--        <el-input-->
<!--          v-model="queryParams.source"-->
<!--          placeholder="请输入source"-->
<!--          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:bWwwNews:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:bWwwNews:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:bWwwNews:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:bWwwNews:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bWwwNewsList" @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">
        <template #default="scope">
          <dict-tag :options="news_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="标题" align="center" prop="title" />
      <el-table-column label="内容(可点击)" align="center" prop="content" show-overflow-tooltip>
        <template #default="scope">
          <el-link type="primary" @click="handlePreviewContent(scope.row)" :underline="false">
            <div class="table-cell-content" v-html="formatContentWithImages(scope.row.content)"></div>
          </el-link>
        </template>
      </el-table-column>
<!--      <el-table-column label="来源" align="center" prop="f" />-->
      <el-table-column label="日期" align="center" prop="sendDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.sendDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="点击数" align="center" prop="clicked" />
<!--      <el-table-column label="状态" align="center" prop="status">-->
<!--        <template #default="scope">-->
<!--          <dict-tag :options="bool_values" :value="scope.row.status"/>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="关键词" align="center" prop="keywords" />-->
<!--      <el-table-column label="描述" align="center" prop="description" />-->
      <el-table-column label="置顶显示" align="center" prop="isTop">
        <template #default="scope">
          <dict-tag :options="bool_values" :value="scope.row.isTop"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="省份" align="center" prop="location" />
      <el-table-column label="链接" align="center" prop="url" width="60">
        <template #default="scope">
          <el-tooltip v-if="scope.row.url" :content="scope.row.url" placement="top" effect="dark">
            <el-link 
              type="primary" 
              :underline="false" 
              @click="handleUrlClick(scope.row.url)"
              style="cursor: pointer;"
            >
              {{ scope.row.url.length > 30 ? scope.row.url.substring(0, 30) + '...' : scope.row.url }}
            </el-link>
          </el-tooltip>
          <span v-else>-</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="原id" align="center" prop="originId" />-->
<!--      <el-table-column label="source" align="center" prop="source" />-->
      <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:bWwwNews:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:bWwwNews: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="800px" append-to-body>
      <el-form ref="bWwwNewsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类别" prop="type">
          <el-select v-model="form.type" placeholder="请选择类别">
            <el-option
              v-for="dict in news_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" type="url"/>
          <!-- 预览内容（只读模式，用于查看已保存的内容） -->
<!--          <div v-if="form.content && form.id" class="readonly-content-preview" style="margin-top: 10px; padding: 10px; background-color: #f5f7fa; border-radius: 4px;">-->
            <!-- <div style="font-size: 12px; color: #909399; margin-bottom: 5px;">内容预览：</div> -->
<!--            <div class="readonly-content" v-html="formatContentWithImages(form.content)"></div>-->
<!--          </div>-->
        </el-form-item>
<!--        <el-form-item label="来源" prop="f">-->
<!--          <el-input v-model="form.f" placeholder="请输入来源" />-->
<!--        </el-form-item>-->
        <el-form-item label="日期" prop="sendDate">
          <el-date-picker clearable
            v-model="form.sendDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
<!--        <el-form-item label="点击数" prop="clicked">-->
<!--          <el-input v-model="form.clicked" placeholder="请输入点击数" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="状态" prop="status">-->
<!--          <el-select v-model="form.status" placeholder="请选择状态">-->
<!--            <el-option-->
<!--              v-for="dict in bool_values"-->
<!--              :key="dict.value"-->
<!--              :label="dict.label"-->
<!--              :value="parseInt(dict.value)"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="关键词" prop="keywords">-->
<!--          <el-input v-model="form.keywords" 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="置顶显示" prop="isTop">
          <el-select v-model="form.isTop" placeholder="请选择置顶显示">
            <el-option
              v-for="dict in bool_values"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="省份" prop="location">
          <el-input v-model="form.location" placeholder="请输入省份" />
        </el-form-item>
        <el-form-item label="链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接" />
        </el-form-item>
<!--        <el-form-item label="原id" prop="originId">-->
<!--          <el-input v-model="form.originId" placeholder="请输入原id" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="source" prop="source">-->
<!--          <el-input v-model="form.source" placeholder="请输入source" />-->
<!--        </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 class="preview-header" v-if="previewData.title">
          <h3>{{ previewData.title }}</h3>
          <div class="preview-meta" v-if="previewData.sendDate">
            <span>发布时间：{{ parseTime(previewData.sendDate, '{y}-{m}-{d}') }}</span>
          </div>
        </div>
        <div class="preview-content" v-html="formatContentWithImages(previewData.content)"></div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="previewOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="BWwwNews">
import { listBWwwNews, getBWwwNews, delBWwwNews, addBWwwNews, updateBWwwNews } from "@/api/system/bWwwNews"
import { getImageProxyUrl, formatContentWithImages } from '@/utils/imageHelper'

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

const bWwwNewsList = 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 previewData = ref({
  title: '',
  content: '',
  sendDate: null
})

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    type: null,
    title: null,
    content: null,
    f: null,
    sendDate: null,
    clicked: null,
    status: null,
    keywords: null,
    description: null,
    isTop: null,
    createTime: null,
    location: null,
    url: null,
    originId: null,
    source: null
  },
  rules: {
    clicked: [
      { required: true, message: "点击数不能为空", trigger: "blur" }
    ],
    isTop: [
      { required: true, message: "置顶显示不能为空", trigger: "change" }
    ],
    originId: [
      { required: true, message: "原id不能为空", trigger: "blur" }
    ],
  }
})

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

/** 查询资讯管理列表 */
function getList() {
  loading.value = true
  listBWwwNews(queryParams.value).then(response => {
    bWwwNewsList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

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

// 表单重置
function reset() {
  form.value = {
    id: null,
    type: null,
    title: null,
    content: null,
    f: null,
    sendDate: null,
    clicked: null,
    status: null,
    keywords: null,
    description: null,
    isTop: null,
    createTime: null,
    location: null,
    url: null,
    originId: null,
    source: null
  }
  proxy.resetForm("bWwwNewsRef")
}

/** 搜索按钮操作 */
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
  getBWwwNews(_id).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改资讯管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bWwwNewsRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBWwwNews(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addBWwwNews(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 delBWwwNews(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

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

/** 预览内容 */
function handlePreviewContent(row) {
  previewData.value = {
    title: row.title || '',
    content: row.content || '',
    sendDate: row.sendDate || null
  }
  previewOpen.value = true
}

/** 点击链接，直接在新窗口打开 */
function handleUrlClick(url) {
  if (url) {
    // 检查链接是否包含协议，如果没有则添加 https://
    let finalUrl = url
    if (!finalUrl.startsWith('http://') && !finalUrl.startsWith('https://')) {
      finalUrl = 'https://' + finalUrl
    }
    window.open(finalUrl, '_blank')
  }
}

getList()
</script>

<style scoped>
/* 表格单元格内容样式 */
.table-cell-content {
    word-break: break-word;
    line-height: 1.6;
    max-height: 100px;
    overflow: hidden;
}

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

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

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

/* 只读内容预览样式 */
.readonly-content {
    color: #606266;
    word-break: break-word;
    white-space: pre-wrap;
    line-height: 1.6;
    min-height: 20px;
}

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

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

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

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

.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>
