<template>
  <div class="task-list-card">
    <div v-if="showFilterBar" class="filters-section">
      <div class="filter-row">
        <el-select
          v-model="localFilters.status"
          placeholder="任务状态"
          clearable
          size="small"
        >
          <el-option label="已下达" value="published" />
          <el-option label="执行中" value="in_progress" />
          <el-option label="已关闭" value="closed" />
          <el-option label="已取消" value="cancelled" />
        </el-select>

        <el-select
          v-model="localFilters.eventLevel"
          placeholder="事件级别"
          clearable
          size="small"
        >
          <el-option label="一级" value="level1" />
          <el-option label="二级" value="level2" />
          <el-option label="三级" value="level3" />
          <el-option label="四级" value="level4" />
        </el-select>

        <el-input
          v-model="localFilters.keyword"
          placeholder="关键字"
          clearable
          size="small"
          @keyup.enter.native="handleManualSearch"
        />
      </div>

      <div class="filter-actions">
        <el-button size="mini" @click="resetFilters">重置</el-button>
        <el-button type="primary" size="mini" @click="handleManualSearch">
          查询
        </el-button>
      </div>
    </div>

    <div v-if="loading" class="loading-container">
      <i class="el-icon-loading"></i>
      <span>加载中...</span>
    </div>
    
    <div v-else-if="tasks.length === 0" class="empty-container">
      <i class="el-icon-document"></i>
      <p>暂无任务</p>
      <p class="empty-hint">请检查筛选条件或联系调度员</p>
    </div>
    
    <div v-else class="task-list">
      <TaskCard
        v-for="task in tasks"
        :key="task.id"
        :task="task"
        @view="handleView"
      />
    </div>
  </div>
</template>

<script>
import TaskCard from './TaskCard.vue'
import { listMyDispatchTasks, addDispatchDisposal } from '@/api/emergency/dispatchTask'
import { listEvents } from '@/api/emergency/event'

const createDefaultFilters = () => ({
  status: '',
  eventLevel: '',
  keyword: '',
  dateRange: null
})

export default {
  name: 'TaskListCard',
  components: {
    TaskCard
  },
  props: {
    pageSize: {
      type: Number,
      default: 200
    },
    autoRefresh: {
      type: Boolean,
      default: true
    },
    refreshInterval: {
      type: Number,
      default: 30000
    },
    showFilterBar: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      loading: false,
      tasks: [],
      intervalId: null,
      localFilters: createDefaultFilters()
    }
  },
  created() {
    this.fetchTasks()
    if (this.autoRefresh) {
      this.startAutoRefresh()
    }
  },
  beforeDestroy() {
    this.stopAutoRefresh()
  },
  methods: {
    async fetchTasks() {
      this.loading = true
      try {
        const params = this.buildDefaultQuery()
        const { rows = [] } = await listMyDispatchTasks(params)
        
        // Batch fetch events for all tasks
        const eventMap = await this.fetchEventsForTasks(rows)
        
        // Normalize tasks and merge event data
        const processed = this.normalizeTasks(rows, eventMap)
        this.tasks = processed
      } catch (error) {
        this.$message?.error('任务加载失败')
      } finally {
        this.loading = false
      }
    },
    async fetchEventsForTasks(tasks) {
      // Extract unique event IDs from tasks
      const eventIds = [...new Set(
        tasks
          .map(task => task.eventId)
          .filter(id => id != null && id !== undefined)
      )]
      
      if (eventIds.length === 0) {
        return {}
      }
      
      try {
        // Batch fetch events using IN clause
        const res = await listEvents({ ids: eventIds })
        const events = res.rows || res.data || []
        
        // Create a map for quick lookup by event ID
        const eventMap = {}
        events.forEach(event => {
          if (event && event.id) {
            eventMap[event.id] = event
          }
        })
        
        return eventMap
      } catch (error) {
        console.error('Failed to fetch events:', error)
        return {}
      }
    },
    buildDefaultQuery() {
      const params = {
        pageNum: 1,
        pageSize: this.pageSize
      }
      const { status, eventLevel, keyword, dateRange } = this.localFilters
      if (status) {
        params.status = status
      } else {
        params.excludeDraft = true
      }
      if (eventLevel) {
        params.eventLevel = eventLevel
      }
      if (keyword) {
        params.keyword = keyword
      }
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        params.beginCreateTime = this.formatDateForQuery(dateRange[0])
        params.endCreateTime = this.formatDateForQuery(dateRange[1], true)
      }
      return params
    },
    formatDateForQuery(date, end = false) {
      if (!date) return null
      const d = new Date(date)
      if (end) {
        d.setHours(23, 59, 59, 999)
      } else {
        d.setHours(0, 0, 0, 0)
      }
      const pad = v => (v < 10 ? `0${v}` : v)
      return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
    },
    resetFilters() {
      this.localFilters = createDefaultFilters()
      this.fetchTasks()
    },
    handleManualSearch() {
      this.fetchTasks()
    },
    startAutoRefresh() {
      this.stopAutoRefresh()
      this.intervalId = setInterval(() => {
        this.fetchTasks()
      }, this.refreshInterval)
    },
    stopAutoRefresh() {
      if (this.intervalId) {
        clearInterval(this.intervalId)
        this.intervalId = null
      }
    },
    handleView(task) {
      this.$emit('view', task)
    },
    handleAddDisposal(task) {
      this.$message.info(`为任务"${task.name}"添加处置记录 (功能待实现)`)
      // TODO: Navigate to disposal form or open dialog
      // this.$router.push({
      //   name: 'AddDisposal',
      //   params: { taskId: task.id }
      // })
    },
    normalizeTasks(rows, eventMap = {}) {
      if (!Array.isArray(rows)) {
        return []
      }
      return rows.map(row => {
        const task = { ...row }
        task.participantConfirmed = this.isParticipantConfirmed(row)
        task.stepProgress = this.extractStepProgress(row)
        
        // Merge event data from batch-fetched events
        const event = eventMap[row.eventId] || row.event
        if (event) {
          task.eventLevel = event.level || row.eventLevel || row.event?.eventLevel
          task.eventName = event.title || event.eventName || event.name || row.eventName || row.event?.eventName || row.event?.name || ''
        } else {
          // Fallback to existing data if event not found
          task.eventLevel = row.eventLevel || row.event?.eventLevel
          task.eventName = this.getTaskEventName(row)
        }
        
        task.lastDisposalTime = row.lastDisposalTime || row.updateTime
        return task
      })
    },
    extractStepProgress(task) {
      if (task.stepProgress) {
        return task.stepProgress
      }
      if (Array.isArray(task.steps)) {
        const total = task.steps.length
        const completed = task.steps.filter(step => ['completed', 'done'].includes(step.status)).length
        return { total, completed }
      }
      return null
    },
    isParticipantConfirmed(task) {
      if (typeof task.participantConfirmed === 'boolean') {
        return task.participantConfirmed
      }
      if (task.status === 'in_progress' || task.status === 'closed') {
        return true
      }
      if (Array.isArray(task.participants)) {
        return task.participants.some(p => p.confirmedFlag === 1)
      }
      return false
    },
    getTaskEventName(task) {
      return task.eventName || task.event?.eventName || task.event?.name || ''
    }
  }
}
</script>

<style lang="scss" scoped>
.task-list-card {
  padding: 0 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  height: 100%;
}

.filters-section {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  
  .el-select,
  .el-input {
    width: 100% !important;
  }
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: #909399;
  
  i {
    font-size: 48px;
    margin-bottom: 16px;
  }
  
  p {
    margin: 8px 0;
    font-size: 14px;
  }
  
  .empty-hint {
    font-size: 12px;
    color: #c0c4cc;
  }
}

.task-list {
  padding-bottom: 16px;
  overflow-y: auto;
}
</style>