<template>
  <div class="task-detail-view" v-if="task">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>任务详情: {{ task.title }}</span>
          <el-tag :type="getStatusTagType(task.status)">{{ formatStatus(task.status) }}</el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务ID">{{ task.id }}</el-descriptions-item>
        <el-descriptions-item label="严重程度">
          <el-tag :type="getSeverityTagType(task.severityLevel)">{{ formatSeverity(task.severityLevel) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="污染类型">{{ task.pollutionType || '未指定' }}</el-descriptions-item>
        <el-descriptions-item label="网格坐标">X: {{ task.gridX }}, Y: {{ task.gridY }}</el-descriptions-item>
        <el-descriptions-item label="分配时间">{{ task.assignedAt ? new Date(task.assignedAt).toLocaleString() : 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="完成时间">{{ task.completedAt ? new Date(task.completedAt).toLocaleString() : 'N/A' }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ task.textAddress || '未提供' }}</el-descriptions-item>
        <el-descriptions-item label="任务描述" :span="2">{{ task.description }}</el-descriptions-item>
      </el-descriptions>

      <div v-if="task.feedback">
        <el-divider />
        <h3>关联反馈信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="反馈ID">{{ task.feedback.feedbackId }}</el-descriptions-item>
          <el-descriptions-item label="提交人">{{ task.feedback.submitterName }}</el-descriptions-item>
          <el-descriptions-item label="反馈时间">{{ new Date(task.feedback.createdAt).toLocaleString() }}</el-descriptions-item>
          <el-descriptions-item label="反馈标题">{{ task.feedback.title }}</el-descriptions-item>
          <el-descriptions-item label="反馈描述" :span="2">{{ task.feedback.description }}</el-descriptions-item>
          <el-descriptions-item label="现场图片" :span="2" v-if="task.feedback.imageUrls && task.feedback.imageUrls.length > 0">
            <el-image
                v-for="url in task.feedback.imageUrls"
                :key="url"
                :src="url"
                :preview-src-list="task.feedback.imageUrls"
                style="width: 100px; height: 100px; margin-right: 10px;"
                fit="cover"
              />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <el-divider />

      <h3>任务历史</h3>
      <div v-if="task.history && task.history.length > 0">
        <el-timeline>
          <el-timeline-item
            v-for="item in task.history"
            :key="item.id"
            :timestamp="new Date(item.changedAt).toLocaleString()"
            :type="getHistoryType(item.newStatus)"
          >
            <strong>{{ formatStatus(item.newStatus) }}</strong>
            <p>{{ item.comments }}</p>
          </el-timeline-item>
        </el-timeline>
      </div>
      <el-empty v-else description="暂无历史记录" />

      <div v-if="task.submissionInfo">
        <el-divider />
        <h3>任务提交详情</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="提交说明">{{ task.submissionInfo.comments }}</el-descriptions-item>
          <el-descriptions-item label="提交附件" v-if="task.submissionInfo.attachments && task.submissionInfo.attachments.length > 0">
            <div v-for="att in task.submissionInfo.attachments" :key="att.id">
              <el-link :href="att.url" type="primary" target="_blank">{{ att.fileName }}</el-link>
            </div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <div class="action-buttons">
        <el-button v-if="task.status === 'ASSIGNED'" type="success" @click="acceptTask" :loading="actionLoading">接受任务</el-button>
        <el-button v-if="task.status === 'IN_PROGRESS'" type="primary" @click="openSubmitDialog" :loading="actionLoading">提交进度</el-button>
        <el-button @click="$router.back()">返回列表</el-button>
      </div>

    </el-card>
  </div>
  <div v-else-if="loading">
    <el-card class="page-card" v-loading="true" style="min-height: 400px;"></el-card>
  </div>
  <div v-else>
     <el-card class="page-card">
       <el-empty description="无法加载任务详情" />
     </el-card>
  </div>

  <SubmitProgressDialog
    v-if="task"
    v-model:visible="isSubmitDialogVisible"
    :task-id="task.id"
    @submitted="handleSubmitted"
  />
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import apiClient from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import SubmitProgressDialog from '@/components/SubmitProgressDialog.vue';

// --- 类型定义 ---
interface TaskHistoryDTO {
  id: number;
  changedAt: string;
  newStatus: string;
  comments: string;
}
interface FeedbackDTO {
  feedbackId: number;
  eventId: string;
  title: string;
  description: string;
  severityLevel: string;
  textAddress: string;
  submitterId: number;
  submitterName: string;
  createdAt: string;
  imageUrls: string[];
}
interface AssigneeDTO {
  id: number;
  name: string;
  phone: string;
}
interface AttachmentDTO {
  id: number;
  fileName: string;
  fileType: string;
  url: string;
}
interface SubmissionInfoDTO {
  comments: string;
  attachments: AttachmentDTO[];
}
interface TaskDetail {
  id: number;
  feedback: FeedbackDTO;
  title: string;
  description: string;
  severityLevel: string;
  pollutionType: string;
  textAddress: string;
  gridX: number;
  gridY: number;
  status: string;
  assignee: AssigneeDTO;
  assignedAt: string | null;
  completedAt: string | null;
  history: TaskHistoryDTO[];
  submissionInfo: SubmissionInfoDTO | null;
}

// --- 响应式状态 ---
const route = useRoute();
const router = useRouter();
const taskId = ref(route.params.id as string);
const task = ref<TaskDetail | null>(null);
const loading = ref(false);
const actionLoading = ref(false);
const isSubmitDialogVisible = ref(false);

// --- API 调用 ---
const fetchTaskDetails = async () => {
  loading.value = true;
  try {
    const response = await apiClient.get<TaskDetail>(`/worker/${taskId.value}`);
    task.value = response;
  } catch (error) {
    console.error(`获取任务详情失败 (ID: ${taskId.value}):`, error);
    ElMessage.error('获取任务详情失败');
  } finally {
    loading.value = false;
  }
};

const acceptTask = async () => {
  actionLoading.value = true;
  try {
    await ElMessageBox.confirm('确定要接受这个任务吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info',
    });
    await apiClient.post(`/worker/${taskId.value}/accept`);
    ElMessage.success('任务已接受');
    fetchTaskDetails(); // Refresh details
  } catch (error) {
    if (error !== 'cancel') {
      console.error('接受任务失败:', error);
      ElMessage.error('接受任务失败');
    }
  } finally {
    actionLoading.value = false;
  }
};

const openSubmitDialog = () => {
  isSubmitDialogVisible.value = true;
};

const handleSubmitted = () => {
  fetchTaskDetails();
};

// --- 辅助函数 ---
const formatStatus = (status: string) => {
  const map: Record<string, string> = {
    'ASSIGNED': '待接受',
    'IN_PROGRESS': '进行中',
    'SUBMITTED': '已提交',
    'COMPLETED': '已完成',
    'REJECTED': '已拒绝',
  };
  return map[status] || status;
};

const getStatusTagType = (status: string): 'primary' | 'warning' | 'info' | 'success' | 'danger' => {
  const map: Record<string, 'primary' | 'warning' | 'info' | 'success' | 'danger'> = {
    'ASSIGNED': 'primary',
    'IN_PROGRESS': 'warning',
    'SUBMITTED': 'info',
    'COMPLETED': 'success',
    'REJECTED': 'danger',
  };
  return map[status] || 'info';
};

const formatSeverity = (severity: string) => {
  const map: Record<string, string> = {
    'LOW': '低',
    'MEDIUM': '中',
    'HIGH': '高',
  };
  return map[severity] || severity;
};

const getSeverityTagType = (severity: string): 'info' | 'warning' | 'danger' => {
  const map: Record<string, 'info' | 'warning' | 'danger'> = {
    'LOW': 'info',
    'MEDIUM': 'warning',
    'HIGH': 'danger',
  };
  return map[severity] || 'info';
};

const getHistoryType = (status: string): 'primary' | 'success' | 'info' => {
    switch (status) {
        case 'ASSIGNED':
        case 'IN_PROGRESS':
            return 'primary';
        case 'COMPLETED':
            return 'success';
        default:
            return 'info';
    }
};

onMounted(() => {
  fetchTaskDetails();
});
</script>

<style scoped>
.task-detail-view {
  padding: 20px;
}
.page-card {
  border-radius: 8px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
}
.action-buttons {
  margin-top: 20px;
  text-align: right;
}
</style> 
