<template>
  <div>
    <!-- History Popup (non-modal, bottom-right) -->
    <div 
      v-if="visible" 
      class="history-popup"
      @click.stop
    >
      <div class="history-popup-header">
        <span class="history-popup-title">历史记录</span>
        <el-button 
          type="text" 
          icon="el-icon-close" 
          size="mini"
          @click="handleClose"
          class="history-popup-close"
        ></el-button>
      </div>
      
      <!-- 筛选区域 -->
      <div class="history-popup-filters">
        <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
          <el-radio-button label="today">今天</el-radio-button>
          <el-radio-button label="24h">最近24小时</el-radio-button>
          <el-radio-button label="7d">最近7天</el-radio-button>
        </el-radio-group>
      </div>
      
      <!-- 内容区域 -->
      <div class="history-popup-body">
        <div v-loading="loading" class="history-list">
          <div 
            v-for="alert in historyAlerts" 
            :key="alert.id"
            class="history-item"
            @click="handleSelect(alert)"
          >
            <div class="history-header">
              <span class="history-no">{{ alert.alertNo }}</span>
              <el-tag size="mini" :type="alert.statusTag">{{ alert.status }}</el-tag>
            </div>
            <div class="history-summary">{{ alert.summary || '暂无摘要' }}</div>
            <div class="history-meta">
              <el-tag size="mini" effect="plain">{{ alert.channel }}</el-tag>
              <span class="history-time">{{ alert.time }}</span>
            </div>
          </div>
          <el-empty v-if="!loading && historyAlerts.length === 0" description="暂无历史记录" :image-size="80"></el-empty>
        </div>
        
        <!-- 分页 -->
        <div v-if="total >= pageSize" class="history-pagination">
          <el-pagination
            small
            :current-page="currentPage"
            :page-size="pageSize"
            :total="total"
            layout="prev, pager, next"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- Click outside backdrop (invisible, non-blocking) -->
    <div 
      v-if="visible"
      class="history-popup-backdrop"
      @click="handleClose"
    ></div>
  </div>
</template>

<script>
import { listAlerts } from '@/api/duty/alert'
import { formatDateTime } from '../utils/dateHelpers'
import { transformAlertData } from '../utils/alertTransformers'

export default {
  name: 'HistoryPopup',
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      historyAlerts: [],
      loading: false,
      timeRange: 'today', // 'today' | '24h' | '7d'
      currentPage: 1,
      pageSize: 20,
      total: 0
    }
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.loadHistoryAlerts()
      } else {
        // 关闭时重置
        this.currentPage = 1
        this.timeRange = 'today'
      }
    }
  },
  methods: {
    /**
     * 获取时间范围
     */
    getTimeRange() {
      const now = new Date()
      let startTime, endTime
      
      switch (this.timeRange) {
        case 'today': {
          // 今天
          const startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
          startTime = startOfDay
          endTime = now
          break
        }
        case '24h': {
          // 最近24小时
          startTime = new Date(now.getTime() - 24 * 60 * 60 * 1000)
          endTime = now
          break
        }
        case '7d': {
          // 最近7天
          startTime = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000)
          endTime = now
          break
        }
        default:
          startTime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)
          endTime = now
      }
      
      return {
        beginOccurredAt: formatDateTime(startTime),
        endOccurredAt: formatDateTime(endTime)
      }
    },
    
    /**
     * 加载历史记录
     */
    async loadHistoryAlerts() {
      this.loading = true
      try {
        const timeRange = this.getTimeRange()
        const res = await listAlerts({
          ...timeRange,
          pageNum: this.currentPage,
          pageSize: this.pageSize
        })
        
        if (res.code === 200) {
          const alerts = res.rows || []
          // 过滤掉草稿状态，只显示已处理的警情（已接警、已转警、已转事件、已关闭）
          const processedAlerts = alerts.filter(alert => 
            ['received', 'transferred', 'converted', 'closed'].includes(alert.status)
          )
          // 转换数据格式
          this.historyAlerts = processedAlerts.map(alert => transformAlertData(alert))
          // 使用后端返回的 total（虽然可能包含草稿，但用于分页参考）
          // 如果过滤后的数据少于 pageSize，说明当前页可能没有更多数据了
          this.total = res.total || 0
        }
      } catch (error) {
        console.error('获取历史记录失败:', error)
        this.$message.error('获取历史记录失败，请稍后重试')
        this.historyAlerts = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    
    /**
     * 处理时间范围变化
     */
    handleTimeRangeChange() {
      this.currentPage = 1
      this.loadHistoryAlerts()
    },
    
    /**
     * 处理分页变化
     */
    handlePageChange(page) {
      this.currentPage = page
      this.loadHistoryAlerts()
    },
    
    /**
     * 关闭弹窗
     */
    handleClose() {
      this.$emit('close')
    },
    
    /**
     * 选择警情（打开详情抽屉）
     */
    handleSelect(alert) {
      this.$emit('select', alert)
    }
  }
}
</script>

<style lang="scss" scoped>
.history-popup {
  position: fixed;
  bottom: 100px;
  right: 30px;
  width: 400px;
  height: 500px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 2001;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.history-popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
  background: #f5f7fa;
  flex-shrink: 0;
}

.history-popup-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
}

.history-popup-close {
  padding: 0;
  color: #909399;
}

.history-popup-filters {
  padding: 12px 16px;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
  
  ::v-deep .el-radio-group {
    width: 100%;
    display: flex;
    
    .el-radio-button {
      flex: 1;
      
      .el-radio-button__inner {
        width: 100%;
      }
    }
  }
}

.history-popup-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 8px;
}

.history-item {
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 8px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  &:hover {
    border-color: #409eff;
    background: #f0f9ff;
  }
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.history-no {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
}

.history-summary {
  color: #606266;
  font-size: 13px;
  margin-bottom: 8px;
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.history-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}

.history-time {
  color: #909399;
  font-size: 12px;
  white-space: nowrap;
}

.history-pagination {
  padding: 12px 16px;
  border-top: 1px solid #ebeef5;
  flex-shrink: 0;
  display: flex;
  justify-content: center;
}

.history-popup-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 2000;
  background: transparent;
}
</style>