<template>
  <el-card shadow="never" class="info-card stats-card">
    <div class="card-header">
      <span>今日调度概览</span>
    </div>
    <div class="stats-grid">
      <div class="stat-item" v-for="item in stats" :key="item.title">
        <div class="label">{{ item.title }}</div>
        <div class="value" :style="{ color: item.color }">{{ item.value }}</div>
      </div>
    </div>
  </el-card>
</template>

<script>
import { listEvents } from '@/api/emergency/event'
import { listDispatchTasks } from '@/api/emergency/dispatchTask'
import { formatDateTime, getTodayDateRange } from '@/views/duty/alert/utils/dateHelpers'

export default {
  name: 'DispatchStatsCard',
  props: {
    initialStats: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: true,
      stats: this.initialStats.length ? this.initialStats : this.buildDefaultStats(),
      refreshTimer: null
    }
  },
  mounted() {
    this.loadStats()
    this.refreshTimer = setInterval(() => {
      if (!this.loading) {
        this.loadStats()
      }
    }, 60000)
  },
  beforeDestroy() {
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer)
      this.refreshTimer = null
    }
  },
  methods: {
    buildDefaultStats() {
      return [
        { title: '今日事件', value: 0, color: '#409EFF' },
        { title: '今日任务', value: 0, color: '#E6A23C' },
        { title: '执行中任务', value: 0, color: '#F56C6C' },
        { title: '今日完结', value: 0, color: '#67C23A' }
      ]
    },
    reload() {
      this.loadStats()
    },
    async loadStats() {
      this.loading = true
      try {
        const [eventCount, taskStats] = await Promise.all([
          this.fetchEventCount(),
          this.fetchDispatchStats()
        ])
        const stats = this.buildDefaultStats()
        stats[0].value = eventCount
        stats[1].value = taskStats.todayTasks
        stats[2].value = taskStats.runningTasks
        stats[3].value = taskStats.closedToday
        this.stats = stats
      } catch (error) {
        console.error('加载调度统计失败:', error)
        this.stats = this.buildDefaultStats()
      } finally {
        this.loading = false
      }
    },
    async fetchEventCount() {
      const { startOfDay, endOfDay } = getTodayDateRange()
      const params = {
        pageNum: 1,
        pageSize: 500,
        beginOccurredAt: formatDateTime(startOfDay),
        endOccurredAt: formatDateTime(endOfDay)
      }
      const res = await listEvents(params)
      if (res && res.code === 200) {
        return Array.isArray(res.rows) ? res.rows.length : 0
      }
      return 0
    },
    async fetchDispatchStats() {
      const { startOfDay, endOfDay } = getTodayDateRange()
      const formatStart = formatDateTime(startOfDay)
      const formatEnd = formatDateTime(endOfDay)
      const todayParams = {
        pageNum: 1,
        pageSize: 1000,
        beginCreateTime: formatStart,
        endCreateTime: formatEnd
      }
      const runningParams = {
        pageNum: 1,
        pageSize: 1000,
        status: 'in_progress'
      }
      const closedParams = {
        pageNum: 1,
        pageSize: 1000,
        status: 'closed'
      }
      const [todayRes, runningRes, closedRes] = await Promise.all([
        listDispatchTasks(todayParams),
        listDispatchTasks(runningParams),
        listDispatchTasks(closedParams)
      ])
      const todayTasks = this.extractTotal(todayRes)
      const runningTasks = this.extractTotal(runningRes)
      const closedToday = this.filterByUpdateTime(closedRes, startOfDay, endOfDay)
      return {
        todayTasks,
        runningTasks,
        closedToday
      }
    },
    extractTotal(res) {
      if (res && res.code === 200) {
        if (typeof res.total === 'number') {
          return res.total
        }
        return Array.isArray(res.rows) ? res.rows.length : 0
      }
      return 0
    },
    filterByUpdateTime(res, start, end) {
      if (!res || res.code !== 200 || !Array.isArray(res.rows)) {
        return 0
      }
      return res.rows.filter((item) => this.isWithinDay(item.updateTime, start, end)).length
    },
    isWithinDay(dateInput, start, end) {
      if (!dateInput) return false
      const candidate = new Date(dateInput)
      return candidate >= start && candidate <= end
    }
  }
}
</script>

<style lang="scss" scoped>
.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 12px;
}

.stat-item {
  background: #f7f8fa;
  border-radius: 6px;
  padding: 12px;
}

.stat-item .label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-item .value {
  font-size: 24px;
  font-weight: 600;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 12px;
}
</style>