<template>
  <!-- 弹窗组件 -->
  <el-dialog v-model="dialogVisible" :title="`数据信息（${pagination.total}）`" width="860px" @close="onClose">
    <!-- 弹窗头部：搜索区域 -->
    <div class="dialog-header">
      <el-form :inline="true" :model="searchForm" @keyup.enter="handleSearch">
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyWord" 
            placeholder="请输入关键词查找" 
          />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="searchForm.timeRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSearch">
            查询
          </el-button>
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 弹窗内容：富文本信息列表 -->
    <div class="dialog-content">
      <div v-loading="loading">
        <div 
          v-for="(item, index) in dataList" 
          :key="item.id" 
          class="data-item"
          :class="{ 'even': index % 2 === 0, 'odd': index % 2 === 1 }"
          title="点击查看数据详情"
          @click="handleOpenDialog(item)"
        >
          <div class="rich-content" v-html="highlightKeyword(item.msgData, searchForm.keyWord)"></div>
          <div class="item-time">{{ formatTime(item.reportTime) }}</div>
        </div>
        
        <!-- 无数据提示 -->
        <el-empty v-if="dataList.length === 0" description="暂无数据" />
      </div>
    </div>

    <!-- 弹窗页脚：分页器 -->
    <div class="dialog-footer">
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        :current-page="pagination.current"
        :page-size="pagination.size"
        :total="pagination.total"
        layout="total, prev, pager, next, jumper"
        background
      />
    </div>
  </el-dialog>
  <dataInfoModal ref="richContentDialogRef"></dataInfoModal>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { getDataPage } from '/@/api/marketing/data';

// 使用国际化
const { t } = useI18n()

// 详情弹窗
const dataInfoModal = defineAsyncComponent(() => import('./dataInfoModal.vue'))
const richContentDialogRef = ref()
const handleOpenDialog = (item: any) => {
  richContentDialogRef.value.openDialog(
  item.msgData, 
  {
    createTime: item.reportTime
  }
)
}
const highlightKeyword = (content: string, keyword: string) => {
  if (!keyword) return content;
  
  const regex = new RegExp(`(${keyword})`, 'gi');
  return content.replace(regex, '<span style="color: red">$1</span>');
}
// 弹窗可见性
const dialogVisible = ref(false)

// 加载状态
const loading = ref(false)

// 搜索表单
const searchForm = reactive({
  keyWord: '',
  timeRange: null as null | [Date, Date]
})

// 清空搜索条件
const resetQuery = () => {
  searchForm.keyWord = ''
  searchForm.timeRange = null
  pagination.current = 1
  dataList.value = []
  fetchData();
}

const clientID = ref('')

// 数据列表
const dataList = ref<any[]>([])

// 分页信息
const pagination = reactive({
  current: 1,
  size: 5, // 每页5条信息
  total: 0
})

// 打开弹窗方法
const openDialog = (id: string) => {
  dialogVisible.value = true
  clientID.value = id
  fetchData()
}

// 关闭弹窗
const onClose = () => {
  // 重置表单
  searchForm.keyWord = ''
  searchForm.timeRange = null
  pagination.current = 1
  dataList.value = []
}

// 格式化时间
const formatTime = (time: string | Date) => {
  if (!time) return '--'
  const date = new Date(time)
  return date.toLocaleString()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchData()
}

// 获取数据方法（需要根据实际API调整）
const fetchData = async () => {
  loading.value = true
  try {
    // 这里需要替换为实际的API调用
    // 示例数据结构，根据实际API调整
    const params = {
      keyWord: searchForm.keyWord,
      startTime: searchForm.timeRange ? searchForm.timeRange[0] : null,
      endTime: searchForm.timeRange ? searchForm.timeRange[1] : null,
      current: pagination.current,
      size: pagination.size,
      clientID: clientID.value
    }
    
    // 模拟API调用
    const res = await getDataPage(params)
    dataList.value = res.data.records
    pagination.total = res.data.total
    
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 分页变化处理
const handleCurrentChange = (val: number) => {
  pagination.current = val
  fetchData()
}

// 每页大小变化处理
const handleSizeChange = (val: number) => {
  pagination.size = val
  pagination.current = 1
  fetchData()
}

// 暴露方法给父组件
defineExpose({
  openDialog
})
</script>

<style scoped lang="scss">
.dialog-header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.dialog-content {
  min-height: 300px;
  max-height: 400px;
  overflow-y: auto;
}

.data-item {
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
  position: relative;
  cursor: pointer;
  
  &.even {
    background-color: #fafafa;
  }
  
  &.odd {
    background-color: #fff;
  }
  
  &:last-child {
    margin-bottom: 0;
  }
}

.rich-content {
  margin-bottom: 10px;
  line-height: 1.6;
  max-height: 150px;
  overflow-y: hidden;
  
  :deep(h4) {
    margin: 0 0 10px 0;
    color: #333;
  }
  
  :deep(p) {
    margin: 0;
    color: #666;
  }
}

.item-time {
  text-align: right;
  font-size: 12px;
  color: #999;
}

.dialog-footer {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: center;
}

:deep(.el-pagination) {
  margin: 0;
}
.highlight-keyword {
  background-color: #ffff00;
  color: #000;
  font-weight: bold;
  padding: 1px 2px;
}
</style>