<template>
  <div class="feedback-management-page">
    <!-- 统计面板 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="4">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-item">
            <div class="stats-value">{{ stats.total }}</div>
            <div class="stats-label">总反馈</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="stats-card pending">
          <div class="stats-item">
            <div class="stats-value">{{ stats.pending }}</div>
            <div class="stats-label">待处理</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="stats-card confirmed">
          <div class="stats-item">
            <div class="stats-value">{{ stats.confirmed }}</div>
            <div class="stats-label">已确认</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="stats-card assigned">
          <div class="stats-item">
            <div class="stats-value">{{ stats.assigned }}</div>
            <div class="stats-label">已分配</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="stats-card resolved">
          <div class="stats-item">
            <div class="stats-value">{{ stats.resolved }}</div>
            <div class="stats-label">已解决</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card shadow="hover" class="stats-card rejected">
          <div class="stats-item">
            <div class="stats-value">{{ stats.rejected }}</div>
            <div class="stats-label">已拒绝</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>反馈管理</span>
        </div>
      </template>

      <!-- 筛选区域 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="状态">
            <el-select v-model="filters.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="item in filterOptions.status"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="污染类型">
            <el-select v-model="filters.pollutionType" placeholder="请选择污染类型" clearable>
              <el-option
                v-for="item in filterOptions.pollutionType"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="严重程度">
            <el-select 
              v-model="filters.severityLevel" 
              placeholder="所有程度" 
              clearable
              :popper-append-to-body="false"
            >
              <template #default>
                <el-option 
                  v-for="(text, key) in severityLevelMap" 
                  :key="key" 
                  :label="text" 
                  :value="key" 
                />
              </template>
              <template #prefix>{{ selectedSeverityLabel }}</template>
            </el-select>
          </el-form-item>
          <el-form-item label="提交时间">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input v-model="filters.keyword" placeholder="标题、描述、报告人" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 反馈列表 -->
      <el-table :data="feedbackList" v-loading="loading" stripe class="feedback-table">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-tag :type="statusTagMap[scope.row.status] || 'info'">
              {{ statusMap[scope.row.status] || '未知状态' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="pollutionType" label="污染类型" width="120">
          <template #default="{ row }: { row: FeedbackResponse }">
            <span>{{ pollutionTypeMap[row.pollutionType] }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="severityLevel" label="严重程度" width="100">
          <template #default="{ row }: { row: FeedbackResponse }">
            <el-tag :type="severityTagMap[row.severityLevel]">{{ severityLevelMap[row.severityLevel] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="网格坐标" width="120">
          <template #default="{ row }: { row: FeedbackResponse }">
            <span v-if="row.gridX !== null && row.gridY !== null">
              {{ `X: ${row.gridX}, Y: ${row.gridY}` }}
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column label="处理人" width="120">
          <template #default="{ row }: { row: FeedbackResponse }">
            <span v-if="row.task && row.task.assignee">
              {{ row.task.assignee.name }}
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="user.name" label="报告人" width="120">
          <template #default="{ row }: { row: FeedbackResponse }">
            <div>
              <span>{{ row.user ? row.user.name : '未知' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="提交时间" width="180">
          <template #default="{ row }">
            <span>{{ formatDate(row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleViewDetails(row)">查看详情</el-button>
            <!-- 其他操作按钮，如处理、分配等 -->
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-if="total > 0"
        class="pagination-container"
        :current-page="pagination.page"
        :page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 详情对话框 -->
    <FeedbackDetailDialog 
      :visible="detailDialogVisible" 
      :feedback-id="selectedFeedbackId"
      @close="detailDialogVisible = false"
      @refresh="fetchFeedbackList"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useFeedbackStore } from '@/store/feedback';
import { storeToRefs } from 'pinia';
import { FeedbackStatus, SeverityLevel } from '@/api/feedback';
import { PollutionType } from '@/api/types';
import type { FeedbackResponse, FeedbackFilters } from '@/api/feedback';
import FeedbackDetailDialog from '@/components/FeedbackDetailDialog.vue';
import { useAuthStore } from '@/stores/auth';

const authStore = useAuthStore();
const feedbackStore = useFeedbackStore();
const { feedbackList, total, loading, stats } = storeToRefs(feedbackStore);

// 使用 reactive 创建过滤条件对象
const filters = reactive<Omit<FeedbackFilters, 'page' | 'size'>>({
  status: undefined,
  pollutionType: undefined,
  severityLevel: undefined,
  startDate: undefined,
  endDate: undefined,
  keyword: undefined,
});

// 用于筛选器的状态子集
const filterableStatusMap: Partial<Record<FeedbackStatus, string>> = {
  [FeedbackStatus.AI_REVIEWING]: 'AI审核中',
  [FeedbackStatus.IN_PROGRESS]: '处理中',
  [FeedbackStatus.PENDING_ASSIGNMENT]: '待分配',
  [FeedbackStatus.PROCESSED]: '已处理',
};

// 使用计算属性来确保状态的显示名称
const selectedStatusLabel = computed(() => {
  return filters.status ? statusMap[filters.status] : '全部状态';
});

const selectedPollutionTypeLabel = computed(() => {
  return filters.pollutionType ? pollutionTypeMap[filters.pollutionType] : '所有类型';
});

const selectedSeverityLabel = computed(() => {
  return filters.severityLevel ? severityLevelMap[filters.severityLevel] : '所有程度';
});

// 日期范围
const dateRange = ref<[string, string] | null>(null);

const pagination = reactive({
  page: 1,
  size: 10,
});

const detailDialogVisible = ref(false);
const selectedFeedbackId = ref<number | null>(null);

// 映射关系
const statusMap: Record<string, string> = {
  'AI_REVIEWING': 'AI审核中',
  'AI_REVIEW_FAILED': 'AI审核失败',
  'PENDING_REVIEW': '待人工审核',
  'PENDING_ASSIGNMENT': '待分配',
  'ASSIGNED': '已分配',
  'CONFIRMED': '已确认',
  'CLOSED_INVALID': '无效关闭',
  'PROCESSED': '已处理',
  'IN_PROGRESS': '处理中',
  'RESOLVED': '已处理',
  'COMPLETED': '已处理'
};
const statusTagMap: Record<string, 'info' | 'warning' | 'danger' | 'success'> = {
  'AI_REVIEWING': 'info',
  'AI_REVIEW_FAILED': 'danger',
  'PENDING_REVIEW': 'warning',
  'PENDING_ASSIGNMENT': 'warning',
  'ASSIGNED': 'warning',
  'CONFIRMED': 'success',
  'CLOSED_INVALID': 'info',
  'PROCESSED': 'success',
  'IN_PROGRESS': 'warning',
  'RESOLVED': 'success',
  'COMPLETED': 'success'
};
const pollutionTypeMap: Record<PollutionType, string> = {

  [PollutionType.PM25]: 'PM2.5',
  [PollutionType.O3]: '臭氧',
  [PollutionType.SO2]: '二氧化硫',
  [PollutionType.NO2]: '二氧化氮',
  [PollutionType.OTHER]: '其他'
};
const severityLevelMap: Record<SeverityLevel, string> = {
  [SeverityLevel.LOW]: '低',
  [SeverityLevel.MEDIUM]: '中',
  [SeverityLevel.HIGH]: '高',
};
const severityTagMap: Record<SeverityLevel, 'info' | 'warning' | 'danger'> = {
  [SeverityLevel.LOW]: 'info',
  [SeverityLevel.MEDIUM]: 'warning',
  [SeverityLevel.HIGH]: 'danger',
};

const formatDate = (date: string | null) => {
  if (!date) return 'N/A';
  return new Date(date).toLocaleString();
};

const fetchFeedbackList = () => {
  const params = {
    ...filters,
    page: pagination.page - 1, // 后端分页从0开始
    size: pagination.size,
  };
  feedbackStore.fetchFeedbackList(params);
};

const handleSearch = () => {
  pagination.page = 1;
  fetchFeedbackList();
};

const handleReset = () => {
  Object.assign(filters, {
    status: undefined,
    pollutionType: undefined,
    severityLevel: undefined,
    startDate: undefined,
    endDate: undefined,
    keyword: undefined,
  });
  dateRange.value = null;
  fetchFeedbackList();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  fetchFeedbackList();
};

const handleCurrentChange = (page: number) => {
  pagination.page = page;
  fetchFeedbackList();
};

const handleViewDetails = (row: FeedbackResponse) => {
  selectedFeedbackId.value = row.id;
  detailDialogVisible.value = true;
};

const fetchFeedbackStats = () => {
  feedbackStore.fetchFeedbackStats();
};

const filterOptions = {
  status: [
    { value: 'PENDING_REVIEW', label: '待人工审核' },
    { value: 'PENDING_ASSIGNMENT', label: '待分配' },
    { value: 'ASSIGNED', label: '已分配' },
    { value: 'IN_PROGRESS', label: '处理中' },
    { value: 'PROCESSED', label: '已处理' },
    { value: 'CLOSED_INVALID', label: '无效关闭' }
  ],
  pollutionType: Object.entries(pollutionTypeMap).map(([value, label]) => ({ value, label })),
  // ... more filter options
};

onMounted(() => {
  fetchFeedbackList();
  fetchFeedbackStats();
});
</script>

<style scoped>
.feedback-management-page {
  padding: 20px;
}
.stats-row {
  margin-bottom: 20px;
}
.stats-card {
  border-radius: 8px;
  transition: all 0.3s;
  cursor: pointer;
}
.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0,0,0,0.1);
}
.stats-item {
  text-align: center;
  padding: 10px;
}
.stats-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 5px;
}
.stats-label {
  font-size: 14px;
  color: #606266;
}
.pending .stats-value {
  color: #e6a23c;
}
.confirmed .stats-value {
  color: #409eff;
}
.assigned .stats-value {
  color: #67c23a;
}
.resolved .stats-value {
  color: #67c23a;
}
.rejected .stats-value {
  color: #f56c6c;
}
.page-card {
  border-radius: 8px;
}
.card-header {
  font-size: 18px;
  font-weight: 600;
}
.filter-container {
  margin-bottom: 20px;
}
.filter-form .el-form-item {
  margin-bottom: 10px;
}
.feedback-table {
  width: 100%;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 选中的过滤器样式 */
:deep(.el-select) .el-input__prefix {
  font-weight: bold;
  color: #409eff !important;
}
:deep(.el-input--prefix .el-input__inner) {
  color: #409eff;
  font-weight: bold;
}
:deep(.el-date-editor.is-active) {
  color: #409eff;
  font-weight: bold;
}
:deep(.el-input.is-active .el-input__inner) {
  color: #409eff;
  font-weight: bold;
}
</style> 