<template>
  <div class="my-tasks-view">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>我的任务</span>
        </div>
      </template>

      <!-- 筛选区域 -->
      <div class="filter-container">
        <el-radio-group v-model="selectedStatus" @change="fetchTasks">
          <el-radio-button value="">全部</el-radio-button>
          <el-radio-button value="ASSIGNED">待接受</el-radio-button>
          <el-radio-button value="IN_PROGRESS">进行中</el-radio-button>
          <el-radio-button value="SUBMITTED">已提交</el-radio-button>
          <el-radio-button value="COMPLETED">已完成</el-radio-button>
        </el-radio-group>
      </div>

      <!-- 任务列表 -->
      <el-table :data="tasks" v-loading="loading" stripe class="task-table" @row-click="handleRowClick">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ formatStatus(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="textAddress" label="地址" min-width="250" show-overflow-tooltip />
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="{ row }">
            <el-tag :type="getSeverityTagType(row.severity)">{{ formatSeverity(row.severity) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="分配时间" width="180">
          <template #default="{ row }">
            <span>{{ new Date(row.createdAt).toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="viewTaskDetails(row.id)">查看详情</el-button>
            <el-button v-if="row.status === 'ASSIGNED'" type="success" link size="small" @click="acceptTask(row.id)">接受</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>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue';
import apiClient from '@/api';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { Page } from '@/api/types';
import { useRouter } from 'vue-router';

// --- 类型定义 ---
interface TaskSummary {
  id: number;
  title: string;
  description: string;
  status: string;
  assigneeName: string | null;
  createdAt: string;
  textAddress: string;
  imageUrl: string;
  severity: string;
}

// --- 响应式状态 ---
const tasks = ref<TaskSummary[]>([]);
const loading = ref(false);
const selectedStatus = ref<string | null>(null);
const total = ref(0);
const pagination = reactive({
  page: 1,
  size: 10,
});
const router = useRouter();

// --- API 调用 ---
const fetchTasks = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.page - 1,
      size: pagination.size,
      sort: 'createdAt,desc'
    };
    if (selectedStatus.value) {
      params.status = selectedStatus.value;
    }
    const response = await apiClient.get<Page<TaskSummary>>('/worker', { params });
    tasks.value = response.content;
    total.value = response.totalElements;
  } catch (error) {
    console.error('获取任务列表失败:', error);
    ElMessage.error('获取任务列表失败');
    tasks.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

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


// --- 辅助函数 ---
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 viewTaskDetails = (taskId: number) => {
  router.push(`/my-tasks/${taskId}`);
};

const handleRowClick = (row: TaskSummary) => {
  viewTaskDetails(row.id);
};

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

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

// --- 生命周期钩子 ---
onMounted(() => {
  fetchTasks();
});
</script>

<style scoped>
.my-tasks-view {
  padding: 20px;
}
.page-card {
  border-radius: 8px;
}
.card-header {
  font-size: 18px;
  font-weight: 600;
}
.filter-container {
  margin-bottom: 20px;
}
.task-table {
  width: 100%;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 