<template>
  <div class="province-report-page">
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="queryParams" size="small">
        <el-form-item label="事件编号">
          <el-input
            v-model="queryParams.eventCode"
            placeholder="请输入事件编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="上报状态">
          <el-select v-model="queryParams.status" placeholder="全部" clearable>
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上报时间">
          <el-date-picker
            v-model="queryParams.reportRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <el-table
        :data="tableData"
        v-loading="loading"
        border
        stripe
      >
        <el-table-column type="index" width="60" label="序号" />
        <el-table-column prop="eventCode" label="事件编号" width="160" />
        <el-table-column prop="eventTitle" label="事件标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="eventLevel" label="事件级别" width="110">
          <template slot-scope="scope">
            <el-tag 
              :type="getEventLevelTagType(scope.row.eventLevel)"
              size="mini"
            >
              {{ getEventLevelLabel(scope.row.eventLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="statusLabel" label="上报状态" width="110">
          <template slot-scope="scope">
            <el-tag :type="statusTagType(scope.row.status)">
              {{ scope.row.statusLabel }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reportedAt" label="上报时间" width="160" />
        <el-table-column prop="operator" label="操作人" width="120" />
        <el-table-column label="操作" width="160" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              icon="el-icon-upload"
              @click="openReportDialog(scope.row)"
            >
              {{ scope.row.hasProvinceReports ? '续报' : '上报' }}
            </el-button>
            <el-button
              type="text"
              size="mini"
              icon="el-icon-document"
              @click="viewHistory(scope.row)"
            >
              记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="fetchList"
      />
    </el-card>

    <ProvinceReportDialog
      :visible.sync="reportDialogVisible"
      :event-info="currentEvent"
      :template-options="templateOptions"
      @submitted="handleReportSubmitted"
    />
    <ProvinceReportHistoryDialog
      :visible.sync="historyDialogVisible"
      :event-info="currentEvent"
    />
  </div>
</template>

<script>
import ProvinceReportDialog from './ProvinceReportDialog.vue'
import ProvinceReportHistoryDialog from './ProvinceReportHistoryDialog.vue'
import { getLevelLabel, getLevelTagType } from '@/views/duty/alert/utils/alertFormatters'
import { listEvents } from '@/api/emergency/event'
import { listTemplates } from '@/api/emergency/reportTemplate'

export default {
  name: 'ProvinceReportingPage',
  components: {
    ProvinceReportDialog,
    ProvinceReportHistoryDialog
  },
  data() {
    return {
      loading: false,
      total: 0,
      tableData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        eventCode: '',
        status: '',
        reportRange: []
      },
      statusOptions: [
        { label: '待上报', value: 'pending' },
        { label: '上报中', value: 'submitting' },
        { label: '已上报', value: 'success' },
        { label: '上报失败', value: 'failed' },
        { label: '重试中', value: 'retry' }
      ],
      reportDialogVisible: false,
      historyDialogVisible: false,
      currentEvent: null,
      templateOptions: []
    }
  },
  created() {
    this.fetchList()
    this.fetchTemplates()
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = 1
      this.fetchList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        eventCode: '',
        status: '',
        reportRange: []
      }
      this.fetchList()
    },
    async fetchList() {
      this.loading = true
      try {
        // Build query parameters for events
        const params = {
          pageNum: this.queryParams.pageNum,
          pageSize: this.queryParams.pageSize
        }
        
        // Add event number filter
        if (this.queryParams.eventCode) {
          params.eventNo = this.queryParams.eventCode
        }
        
        // Add report status filter (events are enriched with provinceReportStatus)
        if (this.queryParams.status) {
          params.provinceReportStatusFilter = this.queryParams.status
        }
        
        // Add date range filter (filter by report time)
        if (this.queryParams.reportRange && this.queryParams.reportRange.length === 2) {
          params.beginProvinceReportTime = this.queryParams.reportRange[0] + ' 00:00:00'
          params.endProvinceReportTime = this.queryParams.reportRange[1] + ' 23:59:59'
        }
        
        const response = await listEvents(params)
        if (response.code === 200) {
          const rows = response.rows || response.data || []
          // Map backend response to frontend display format
          // Events are already enriched with report status fields!
          this.tableData = rows.map(event => ({
            id: event.id,
            eventId: event.id,
            eventCode: event.eventNo || '-',
            eventTitle: event.title || '-',
            eventLevel: event.level || '',
            status: event.provinceReportStatus || 'pending',
            statusLabel: this.getStatusLabel(event.provinceReportStatus || 'pending'),
            reportedAt: event.provinceReportTime || '-',
            operator: event.provinceReportOperator || '-',
            hasProvinceReports: event.hasProvinceReports || false,
            statusHistory: []
          }))
          this.total = response.total || 0
        } else {
          this.$message.error(response.msg || '加载事件列表失败')
          this.tableData = []
          this.total = 0
        }
      } catch (error) {
        console.error('加载事件列表失败:', error)
        this.$message.error('加载事件列表失败')
        this.tableData = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },
    async fetchTemplates() {
      try {
        const response = await listTemplates({ pageNum: 1, pageSize: 100 })
        if (response.code === 200) {
          this.templateOptions = response.rows || response.data || []
        } else {
          this.$message.error(response.msg || '加载模板列表失败')
        }
      } catch (error) {
        console.error('加载模板列表失败:', error)
        this.$message.error('加载模板列表失败')
      }
    },
    getStatusLabel(status) {
      const statusMap = {
        pending: '待上报',
        submitting: '上报中',
        success: '已上报',
        failed: '上报失败',
        retry: '重试中'
      }
      return statusMap[status] || status || '未知'
    },
    statusTagType(status) {
      const tagMap = {
        success: 'success',
        failed: 'danger',
        submitting: 'warning',
        retry: 'warning',
        pending: 'info'
      }
      return tagMap[status] || 'info'
    },
    getEventLevelLabel(level) {
      if (!level) return '-'
      if (['I', 'II', 'III', 'IV'].includes(level)) {
        return `${level}级`
      }
      if (level.startsWith('level')) {
        return getLevelLabel(level)?.replace(/[（(].*/, '') || level
      }
      // Handle already formatted levels like 'Ⅰ级', 'Ⅱ级', etc.
      if (level.includes('级')) {
        return level
      }
      return level
    },
    getEventLevelTagType(level) {
      if (!level) return 'info'
      if (['I', 'II', 'III', 'IV'].includes(level)) {
        const tagMap = {
          I: 'danger',
          II: 'warning',
          III: 'info',
          IV: 'success'
        }
        return tagMap[level] || 'info'
      }
      if (level.startsWith('level')) {
        return getLevelTagType(level) || 'info'
      }
      return 'info'
    },
    openReportDialog(row) {
      // Map row data to event info format expected by dialog
      this.currentEvent = {
        id: row.eventId,
        eventCode: row.eventCode,
        eventTitle: row.eventTitle,
        eventLevel: row.eventLevel,
        status: row.status,
        statusLabel: row.statusLabel,
        hasProvinceReports: row.hasProvinceReports || false
      }
      this.reportDialogVisible = true
    },
    viewHistory(row) {
      this.currentEvent = {
        id: row.eventId,
        eventCode: row.eventCode,
        eventTitle: row.eventTitle
      }
      this.historyDialogVisible = true
    },
    handleReportSubmitted() {
      this.fetchList()
    }
  }
}
</script>

<style scoped>
.province-report-page {
  padding: 16px;
}
.filter-card {
  margin-bottom: 16px;
}
</style>