<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  getProjectDetail,
  getDailyReportAnalysisSuggestions,
  applyDailyReportAnalysisSuggestions,
  createTask,
  updateTask,
  deleteTask,
  createMilestone,
  updateMilestone,
  deleteMilestone,
  createResource,
  updateResource,
  deleteResource,
  type ProjectDetail,
  type ProjectMember,
  type ProjectMilestone,
  type ProjectTask,
  type ProjectResource,
  type ProjectRisk,
  type DailyReportAnalysisSuggestionsVO,
  type DailyReportUpdateSuggestionVO,
  type Resource,
  type ResourceUpdateRequest
} from "@/api/project";
import { hasPerms } from "@/utils/auth";
import { GGanttChart, GGanttRow } from "@infectoone/vue-ganttastic";
import { message } from "@/utils/message";
import dayjs from "dayjs";
import isoWeek from "dayjs/plugin/isoWeek";

// 启用 isoWeek 插件，vue-ganttastic 周精度需要
dayjs.extend(isoWeek);

import ArrowLeftIcon from "~icons/ri/arrow-left-line";
import DownloadIcon from "~icons/ri/download-line";
import EditIcon from "~icons/ri/edit-line";
import UserIcon from "~icons/ri/user-line";
import AlertIcon from "~icons/ri/alert-line";
import RobotIcon from "~icons/ri/robot-2-line";
import RefreshIcon from "~icons/ri/refresh-line";
import FullscreenIcon from "~icons/ri/fullscreen-line";
import FileListIcon from "~icons/ri/file-list-line";
import ArrowRightIcon from "~icons/ri/arrow-right-s-line";
import CheckIcon from "~icons/ri/check-line";

defineOptions({
  name: "ProjectDetail"
});

const route = useRoute();
const router = useRouter();
const projectId = ref<string>(route.params.id as string);

// 权限控制 - 任务（基础权限）
const canCreateTask = computed(() => hasPerms("project:task:create"));
const canUpdateTask = computed(() => hasPerms("project:task:update"));
const canDeleteTask = computed(() => hasPerms("project:task:delete"));

// 权限控制 - 里程碑（基础权限）
const canCreateMilestone = computed(() => hasPerms("project:milestone:create"));
const canUpdateMilestone = computed(() => hasPerms("project:milestone:update"));
const canDeleteMilestone = computed(() => hasPerms("project:milestone:delete"));

// 权限控制 - 资源（基础权限）
const canCreateResource = computed(() => hasPerms("project:resource:create"));
const canUpdateResource = computed(() => hasPerms("project:resource:update"));
const canDeleteResource = computed(() => hasPerms("project:resource:delete"));
const canViewResource = computed(() => hasPerms("project:resource:view"));
const canStatsResource = computed(() => hasPerms("project:resource:stats"));

// 加载状态
const loading = ref(false);
const ganttLoading = ref(false);

// 边距设置
const marginSettings = ref({
  top: 16,
  right: 80,
  bottom: 16,
  left: 16
});

// 计算边距样式
const marginStyle = computed(() => ({
  padding: `${marginSettings.value.top}px ${marginSettings.value.right}px ${marginSettings.value.bottom}px ${marginSettings.value.left}px`
}));

// 项目详情数据
const projectDetail = ref<ProjectDetail | null>(null);

const suggestionsLoading = ref(false);
const suggestionsApplying = ref(false);
const dailyReportSuggestions = ref<DailyReportAnalysisSuggestionsVO | null>(
  null
);
const selectedSuggestionIds = ref<string[]>([]);

// 成员详情模态框
const memberDetailModal = ref(false);
const selectedMember = ref<ProjectMember | null>(null);

// 任务编辑模态框
const taskEditModal = ref(false);
const taskEditForm = ref<ProjectTask>({
  id: "",
  taskName: "",
  description: "",
  taskType: "",
  milestoneId: "",
  assigneeId: "",
  assigneeName: "",
  planStartDate: "",
  planEndDate: "",
  actualStartDate: "",
  actualEndDate: "",
  planHours: 0,
  actualHours: 0,
  progress: 0,
  priority: "medium",
  status: "pending",
  sortOrder: 0
});
const taskEditLoading = ref(false);
const isTaskEdit = ref(false); // true=编辑, false=新增

// 里程碑编辑模态框
const milestoneEditModal = ref(false);
const milestoneEditForm = ref<ProjectMilestone>({
  id: "",
  milestoneName: "",
  description: "",
  planDate: "",
  actualDate: "",
  status: "pending",
  progress: 0,
  isKey: 0,
  deliverables: "",
  sortOrder: 0
});
const milestoneEditLoading = ref(false);
const isMilestoneEdit = ref(false); // true=编辑, false=新增

// 资源编辑模态框
const resourceEditModal = ref(false);
const resourceEditForm = ref<Resource>({
  id: "",
  resourceCode: "",
  resourceType: "material",
  resourceName: "",
  description: "",
  specification: "",
  unit: "",
  planQuantity: 0,
  actualQuantity: 0,
  unitPrice: 0,
  currency: "CNY",
  supplier: "",
  status: "planned",
  planArriveDate: "",
  actualArriveDate: "",
  responsibleId: "",
  responsibleName: "",
  location: "",
  tags: []
});
const resourceEditLoading = ref(false);
const isResourceEdit = ref(false); // true=编辑, false=新增

// 权限控制 - 派生权限（需要放在 isTaskEdit/isMilestoneEdit 定义之后）
// 任务编辑权限：新增或编辑任一即可显示按钮
const canEditTask = computed(() => canCreateTask.value || canUpdateTask.value);
// 任务保存权限：新增时需要create权限，编辑时需要update权限
const canSaveTask = computed(() => {
  return isTaskEdit.value ? canUpdateTask.value : canCreateTask.value;
});
// 里程碑编辑权限：新增或编辑任一即可显示按钮
const canEditMilestone = computed(
  () => canCreateMilestone.value || canUpdateMilestone.value
);
// 里程碑保存权限：新增时需要create权限，编辑时需要update权限
const canSaveMilestone = computed(() => {
  return isMilestoneEdit.value
    ? canUpdateMilestone.value
    : canCreateMilestone.value;
});
// 资源编辑权限：新增或编辑任一即可显示按钮
const canEditResource = computed(
  () => canCreateResource.value || canUpdateResource.value
);
// 资源保存权限：新增时需要create权限，编辑时需要update权限
const canSaveResource = computed(() => {
  return isResourceEdit.value
    ? canUpdateResource.value
    : canCreateResource.value;
});

// 项目基本信息（计算属性）
const projectInfo = computed(() => {
  const data = projectDetail.value;
  return {
    id: data?.id || projectId.value,
    projectName: data?.projectName || "",
    projectCode: data?.projectCode || "",
    status: data?.status || "ongoing",
    statusText: getStatusText(data?.status),
    startDate: data?.planStartDate || "",
    endDate: data?.planEndDate || "",
    progress: data?.progress || 0,
    progressChange: 0,
    budget: data?.budget || 0,
    cost: data?.cost || 0,
    teamSize: data?.memberCount || 0,
    riskLevel: data?.riskLevel || "low",
    riskText: getRiskText(data?.riskLevel),
    riskCount: data?.riskCount || 0,
    description: data?.description || "",
    objectives: data?.objectives || ""
  };
});

// 甘特图数据（使用任务列表）

// AI助手消息
const aiMessages = ref([
  {
    type: "ai",
    content:
      "您好！我是项目AI助手，我可以帮您分析项目进度和流程卡点。请问有什么可以帮助您的？",
    time: "上午 9:30"
  },
  {
    type: "user",
    content: "当前项目进度如何？有没有什么风险点需要注意？",
    time: "上午 9:32"
  },
  {
    type: "ai",
    content: `**项目进度分析：** 当前项目整体进度为68%，比计划进度超前5%。

**关键风险点：**
• 玻璃幕墙材料尚未发货，可能影响后续安装工序
• 水电安装工序存在资源调配问题，可能导致延期
• 室内装修团队人力不足，建议增加2名熟练工人

**建议措施：** 优先跟进玻璃幕墙供应商发货情况，协调水电安装资源，考虑从其他项目临时调配装修工人。`,
    time: "上午 9:33"
  }
]);

const aiInput = ref("");

// 资源清单数据（从API获取）
const resourceList = computed(() => {
  return projectDetail.value?.resources || [];
});

// 风险列表数据（从API获取）
const riskList = computed(() => {
  return projectDetail.value?.risks || [];
});

// 成员列表数据（从API获取）
const memberList = computed(() => {
  return projectDetail.value?.members || [];
});

// 里程碑列表数据（从API获取）
const milestoneList = computed(() => {
  return projectDetail.value?.milestones || [];
});

// 任务列表数据（从API获取，用于甘特图）
const taskList = computed(() => {
  return projectDetail.value?.tasks || [];
});

// 返回上一页
function goBack() {
  router.push("/project");
}

// 打开成员详情模态框
function openMemberDetail(member: ProjectMember) {
  selectedMember.value = member;
  memberDetailModal.value = true;
}

// 获取甘特图数据（现在使用项目详情中的任务数据）
async function fetchGanttData() {
  // 任务数据已从项目详情API获取，无需单独请求
  ganttLoading.value = true;
  try {
    // 模拟加载延迟
    await new Promise(resolve => setTimeout(resolve, 300));
  } catch (error) {
    console.error("获取甘特图数据失败:", error);
  } finally {
    ganttLoading.value = false;
  }
}

// 发送AI消息
function sendAiMessage() {
  if (!aiInput.value.trim()) return;
  const userMsg = aiInput.value.trim();
  aiMessages.value.push({
    type: "user",
    content: userMsg,
    time: dayjs().format("HH:mm")
  });
  aiInput.value = "";

  // 模拟AI回复
  setTimeout(() => {
    aiMessages.value.push({
      type: "ai",
      content: "收到您的问题，我正在分析项目数据，请稍候...",
      time: dayjs().format("HH:mm")
    });
  }, 500);
}

// 获取状态标签类型
function getStatusType(
  status?: string
): "success" | "warning" | "info" | "primary" | "danger" {
  switch (status) {
    case "completed":
      return "success";
    case "ongoing":
      return "primary";
    case "paused":
      return "warning";
    case "cancelled":
      return "danger";
    default:
      return "info";
  }
}

// 获取物料状态类型
function getMaterialStatusType(
  status: string
): "success" | "warning" | "info" | "primary" | "danger" {
  switch (status) {
    case "arrived":
      return "success";
    case "pending":
      return "info";
    case "delayed":
      return "danger";
    default:
      return "info";
  }
}

// 将任务数据转换为 vue-ganttastic 格式
const ganttTasks = computed(() => {
  return taskList.value.map(task => {
    const assigneeText = task.assigneeName ? `【${task.assigneeName}】` : "";
    return {
      id: task.id,
      // 左侧标签显示：任务名 + 负责人
      label: `${task.taskName} ${assigneeText}`,
      startDate: task.planStartDate || "",
      endDate: task.planEndDate || "",
      progress: task.progress || 0,
      assignee: task.assigneeName || "未分配",
      status: task.status || "pending",
      ganttBarConfig: {
        id: task.id,
        // 任务条上显示任务名
        label: task.taskName,
        hasHandles: false,
        style: {
          backgroundColor: getTaskColor(task.status, task.progress),
          color: "#fff"
        }
      }
    };
  });
});

// 获取任务颜色
function getTaskColor(status?: string, progress?: number): string {
  if (progress === 100) return "#67c23a"; // 已完成 - 绿色
  if (status === "completed") return "#67c23a"; // 已完成 - 绿色
  if (status === "in_progress" || status === "ongoing") return "#409eff"; // 进行中 - 蓝色
  if (status === "pending") return "#e6a23c"; // 待开始 - 橙色
  if (status === "delayed") return "#f56c6c"; // 延期 - 红色
  if (status === "paused") return "#909399"; // 暂停 - 灰色
  if (status === "cancelled") return "#909399"; // 已取消 - 灰色
  return "#409eff"; // 默认 - 蓝色
}

// 获取任务状态标签类型
function getTaskStatusType(
  status?: string
): "success" | "warning" | "info" | "primary" | "danger" {
  switch (status) {
    case "completed":
      return "success";
    case "in_progress":
    case "ongoing":
      return "primary";
    case "pending":
      return "warning";
    case "delayed":
      return "danger";
    case "paused":
    case "cancelled":
      return "info";
    default:
      return "info";
  }
}

// 获取任务状态文本
function getTaskStatusText(status?: string): string {
  const statusMap: Record<string, string> = {
    completed: "已完成",
    in_progress: "进行中",
    ongoing: "进行中",
    pending: "待开始",
    delayed: "延期",
    paused: "暂停",
    cancelled: "已取消"
  };
  return statusMap[status || ""] || "待开始";
}

// 将里程碑数据转换为 vue-ganttastic 格式
const ganttMilestones = computed(() => {
  return milestoneList.value.map(milestone => ({
    id: milestone.id,
    label: milestone.milestoneName,
    startDate: milestone.planDate || "",
    endDate: milestone.planDate || "",
    status: milestone.status || "pending",
    isKey: milestone.isKey === 1,
    ganttBarConfig: {
      id: milestone.id,
      label: `${milestone.milestoneName} ${milestone.isKey === 1 ? "【关键】" : ""}`,
      hasHandles: false,
      style: {
        backgroundColor: getMilestoneColor(milestone.status, milestone.isKey),
        color: "#fff",
        borderRadius: "50%",
        width: "16px",
        height: "16px",
        minWidth: "16px"
      }
    }
  }));
});

// 获取里程碑颜色
function getMilestoneColor(status?: string, isKey?: number): string {
  if (status === "completed") return "#67c23a"; // 已完成 - 绿色
  if (status === "in_progress") return "#409eff"; // 进行中 - 蓝色
  if (isKey === 1) return "#f56c6c"; // 关键里程碑 - 红色
  return "#e6a23c"; // 默认 - 橙色
}

// 获取里程碑状态文本
function getMilestoneStatusText(status?: string): string {
  const statusMap: Record<string, string> = {
    completed: "已完成",
    in_progress: "进行中",
    pending: "待开始",
    delayed: "已延期"
  };
  return statusMap[status || ""] || "待开始";
}

// 按日期排序的里程碑列表
const sortedMilestones = computed(() => {
  return [...milestoneList.value].sort((a, b) => {
    const dateA = new Date(a.planDate || "").getTime();
    const dateB = new Date(b.planDate || "").getTime();
    return dateA - dateB;
  });
});

// 计算甘特图日期范围（根据任务实际日期动态计算）
const ganttDateRange = computed(() => {
  // 1. 优先从任务列表获取日期范围
  if (taskList.value.length > 0) {
    const taskDates = taskList.value
      .filter(t => t.planStartDate || t.planEndDate)
      .flatMap(t => [t.planStartDate, t.planEndDate].filter(d => d));

    if (taskDates.length > 0) {
      const validDates = taskDates.filter(d => d);
      const minDate = validDates.reduce(
        (min, d) => (d < min ? d : min),
        validDates[0]
      );
      const maxDate = validDates.reduce(
        (max, d) => (d > max ? d : max),
        validDates[0]
      );

      // 添加前后边距（各7天）
      const start = dayjs(minDate).subtract(7, "day").format("YYYY-MM-DD");
      const end = dayjs(maxDate).add(7, "day").format("YYYY-MM-DD");
      return { start, end };
    }
  }

  // 2. 使用项目日期（添加前后边距）
  const projectStart =
    projectInfo.value.startDate || dayjs().format("YYYY-MM-DD");
  const projectEnd = projectInfo.value.endDate;

  if (projectEnd) {
    const start = dayjs(projectStart).subtract(7, "day").format("YYYY-MM-DD");
    const end = dayjs(projectEnd).add(7, "day").format("YYYY-MM-DD");
    return { start, end };
  }

  // 3. 无结束日期时，默认显示30天
  const start = dayjs(projectStart).subtract(7, "day").format("YYYY-MM-DD");
  const end = dayjs(projectStart).add(23, "day").format("YYYY-MM-DD");
  return { start, end };
});

// 计算项目时间跨度（天数）
const projectDays = computed(() => {
  const start = dayjs(ganttDateRange.value.start);
  const end = dayjs(ganttDateRange.value.end);
  return end.diff(start, "day");
});

// 动态计算甘特图精度：超过两个月(60天)使用周精度，否则使用日精度
const ganttPrecision = computed(() => {
  return projectDays.value > 60 ? "week" : "day";
});

// 获取项目详情
async function fetchProjectDetail() {
  if (!projectId.value) return;
  loading.value = true;
  try {
    const res = await getProjectDetail(projectId.value);
    const result = res as any;
    if (result.code === 200 && result.data) {
      projectDetail.value = result.data;
    }
  } catch (error) {
    console.error("获取项目详情失败:", error);
    message("获取项目详情失败", { type: "error" });
  } finally {
    loading.value = false;
  }
}

async function fetchDailyReportSuggestions() {
  if (!projectId.value) return;
  suggestionsLoading.value = true;
  try {
    const res = await getDailyReportAnalysisSuggestions({
      projectId: projectId.value
    });
    const result = res as any;
    if (result.code === 200) {
      const data = result.data;
      dailyReportSuggestions.value = Array.isArray(data)
        ? { suggestions: data }
        : data || null;
      selectedSuggestionIds.value = [];
    }
  } catch (error) {
    console.error("获取进度更新建议失败:", error);
    message("获取进度更新建议失败", { type: "error" });
  } finally {
    suggestionsLoading.value = false;
  }
}

function handleSuggestionSelectionChange(
  rows: DailyReportUpdateSuggestionVO[]
) {
  selectedSuggestionIds.value = rows
    .map(r => String(r.suggestionId || ""))
    .filter(id => id.length > 0);
}

function getOverallAssessmentType(
  status?: string
): "success" | "warning" | "info" | "primary" | "danger" {
  switch (status) {
    case "ahead":
      return "success";
    case "on_track":
      return "primary";
    case "delayed":
      return "danger";
    default:
      return "info";
  }
}

function getOverallAssessmentText(status?: string) {
  switch (status) {
    case "ahead":
      return "提前";
    case "on_track":
      return "正常";
    case "delayed":
      return "滞后";
    default:
      return status || "未知";
  }
}

function formatDeviation(deviationPercentage?: number) {
  if (deviationPercentage === undefined || deviationPercentage === null)
    return "--";
  const value = Number(deviationPercentage);
  if (!Number.isFinite(value)) return "--";
  const sign = value > 0 ? "+" : "";
  return `${sign}${value}%`;
}

function isSuggestionApplied(status?: string) {
  const normalized = (status || "").toLowerCase();
  return (
    normalized === "applied" ||
    normalized === "accepted" ||
    normalized === "done" ||
    normalized === "completed"
  );
}

function getSuggestionStatusType(
  status?: string
): "success" | "warning" | "info" | "primary" | "danger" {
  if (isSuggestionApplied(status)) return "success";
  if (!status) return "info";
  const normalized = status.toLowerCase();
  if (normalized.includes("reject") || normalized.includes("fail"))
    return "danger";
  if (normalized.includes("pending") || normalized.includes("new"))
    return "warning";
  return "info";
}

function getSuggestionStatusText(status?: string) {
  if (isSuggestionApplied(status)) return "已应用";
  if (!status) return "待处理";
  const normalized = status.toLowerCase();
  if (normalized.includes("reject")) return "已拒绝";
  if (normalized.includes("fail")) return "失败";
  if (normalized.includes("pending") || normalized.includes("new"))
    return "待处理";
  return status;
}

async function handleApplySuggestions(
  ids: Array<string | number | undefined | null>
) {
  if (!projectId.value) return;
  const suggestionIds = Array.from(
    new Set(ids.map(i => String(i || "")).filter(Boolean))
  );
  if (suggestionIds.length === 0) return;
  if (suggestionsApplying.value) return;
  suggestionsApplying.value = true;
  try {
    const res = await applyDailyReportAnalysisSuggestions({
      projectId: projectId.value,
      suggestionIds
    });
    const result = res as any;
    if (result.code === 200) {
      message("已应用进度更新建议", { type: "success" });
      await fetchProjectDetail();
      await fetchDailyReportSuggestions();
    } else {
      message(result.message || "应用建议失败", { type: "error" });
    }
  } catch (error) {
    console.error("应用进度更新建议失败:", error);
    message("应用建议失败", { type: "error" });
  } finally {
    suggestionsApplying.value = false;
  }
}

async function handleApplySelectedSuggestions() {
  await handleApplySuggestions(selectedSuggestionIds.value);
}

// 获取状态文本
function getStatusText(status?: string): string {
  const statusMap: Record<string, string> = {
    ongoing: "进行中",
    completed: "已完成",
    paused: "已暂停",
    cancelled: "已取消",
    planning: "规划中",
    draft: "草稿"
  };
  return statusMap[status || ""] || "未知";
}

// 获取风险文本
function getRiskText(risk?: string): string {
  const riskMap: Record<string, string> = {
    low: "低",
    medium: "中等",
    high: "高"
  };
  return riskMap[risk || ""] || "低";
}

// 获取角色文本
function getRoleText(roleCode?: string): string {
  const roleMap: Record<string, string> = {
    manager: "项目经理",
    leader: "负责人",
    member: "成员",
    sponsor: "发起人"
  };
  return roleMap[roleCode || ""] || roleCode || "成员";
}

// 获取资源类型文本
function getResourceTypeText(type?: string): string {
  const typeMap: Record<string, string> = {
    equipment: "设备",
    material: "物料",
    human: "人力",
    software: "软件",
    finance: "资金",
    service: "服务",
    other: "其他"
  };
  return typeMap[type || ""] || type || "其他";
}

// 获取资源类型图标
function getResourceTypeIcon(type?: string): string {
  const iconMap: Record<string, string> = {
    equipment: "ri/server-line",
    material: "ri/archive-line",
    human: "ri/team-line",
    software: "ri/code-line",
    finance: "ri/money-cny-circle-line",
    service: "ri/service-line",
    other: "ri/file-list-line"
  };
  return iconMap[type || ""] || "ri/file-list-line";
}

// 获取资源类型颜色
function getResourceTypeColor(type?: string): string {
  const colorMap: Record<string, string> = {
    equipment: "#409eff", // 设备 - 蓝色
    material: "#67c23a", // 物料 - 绿色
    human: "#e6a23c", // 人力 - 橙色
    software: "#9b59b6", // 软件 - 紫色
    finance: "#f56c6c", // 资金 - 红色
    service: "#00bcd4", // 服务 - 青色
    other: "#909399" // 其他 - 灰色
  };
  return colorMap[type || ""] || "#909399";
}

// 获取资源状态类型
function getResourceStatusType(
  status?: string
): "success" | "warning" | "info" | "primary" | "danger" {
  switch (status) {
    case "arrived":
    case "actual":
      return "success";
    case "planned":
      return "info";
    case "delayed":
      return "danger";
    default:
      return "info";
  }
}

// 获取资源状态文本
function getResourceStatusText(status?: string): string {
  const statusMap: Record<string, string> = {
    arrived: "已到货",
    actual: "实际",
    planned: "计划中",
    delayed: "延期"
  };
  return statusMap[status || ""] || status || "计划中";
}

// 获取风险等级标签类型
function getRiskLevelType(
  level?: string
): "success" | "warning" | "danger" | "info" {
  switch (level) {
    case "low":
      return "success";
    case "medium":
      return "warning";
    case "high":
      return "danger";
    default:
      return "info";
  }
}

// ==================== 任务编辑功能 ====================

/** 打开新增任务对话框 */
function openAddTaskModal() {
  isTaskEdit.value = false;
  taskEditForm.value = {
    id: "",
    taskName: "",
    description: "",
    taskType: "",
    milestoneId: "",
    assigneeId: "",
    assigneeName: "",
    planStartDate: "",
    planEndDate: "",
    actualStartDate: "",
    actualEndDate: "",
    planHours: 0,
    actualHours: 0,
    progress: 0,
    priority: "medium",
    status: "pending",
    sortOrder: taskList.value.length
  };
  taskEditModal.value = true;
}

/** 打开编辑任务对话框 */
function openEditTaskModal(task: ProjectTask) {
  isTaskEdit.value = true;
  taskEditForm.value = { ...task };
  taskEditModal.value = true;
}

/** 保存任务 */
async function saveTask() {
  if (!taskEditForm.value.taskName) {
    message("请输入任务名称", { type: "warning" });
    return;
  }
  taskEditLoading.value = true;
  try {
    const data = {
      ...taskEditForm.value,
      projectId: projectId.value
    };
    if (isTaskEdit.value) {
      await updateTask(data);
      message("任务更新成功", { type: "success" });
    } else {
      await createTask(data);
      message("任务创建成功", { type: "success" });
    }
    taskEditModal.value = false;
    await fetchProjectDetail();
  } catch (error) {
    console.error("保存任务失败:", error);
    message("保存任务失败", { type: "error" });
  } finally {
    taskEditLoading.value = false;
  }
}

/** 删除任务 */
async function handleDeleteTask(taskId: string) {
  try {
    await deleteTask(taskId);
    message("任务删除成功", { type: "success" });
    await fetchProjectDetail();
  } catch (error) {
    console.error("删除任务失败:", error);
    message("删除任务失败", { type: "error" });
  }
}

// ==================== 里程碑编辑功能 ====================

/** 打开新增里程碑对话框 */
function openAddMilestoneModal() {
  isMilestoneEdit.value = false;
  milestoneEditForm.value = {
    id: "",
    milestoneName: "",
    description: "",
    planDate: "",
    actualDate: "",
    status: "pending",
    progress: 0,
    isKey: 0,
    deliverables: "",
    sortOrder: milestoneList.value.length
  };
  milestoneEditModal.value = true;
}

/** 打开编辑里程碑对话框 */
function openEditMilestoneModal(milestone: ProjectMilestone) {
  isMilestoneEdit.value = true;
  milestoneEditForm.value = { ...milestone };
  milestoneEditModal.value = true;
}

/** 保存里程碑 */
async function saveMilestone() {
  if (!milestoneEditForm.value.milestoneName) {
    message("请输入里程碑名称", { type: "warning" });
    return;
  }
  if (!milestoneEditForm.value.planDate) {
    message("请选择计划日期", { type: "warning" });
    return;
  }
  milestoneEditLoading.value = true;
  try {
    const data = {
      ...milestoneEditForm.value,
      projectId: projectId.value
    };
    if (isMilestoneEdit.value) {
      await updateMilestone(data);
      message("里程碑更新成功", { type: "success" });
    } else {
      await createMilestone(data);
      message("里程碑创建成功", { type: "success" });
    }
    milestoneEditModal.value = false;
    await fetchProjectDetail();
  } catch (error) {
    console.error("保存里程碑失败:", error);
    message("保存里程碑失败", { type: "error" });
  } finally {
    milestoneEditLoading.value = false;
  }
}

/** 删除里程碑 */
async function handleDeleteMilestone(milestoneId: string) {
  try {
    await deleteMilestone(milestoneId);
    message("里程碑删除成功", { type: "success" });
    await fetchProjectDetail();
  } catch (error) {
    console.error("删除里程碑失败:", error);
    message("删除里程碑失败", { type: "error" });
  }
}

// ==================== 资源编辑功能 ====================

/** 打开新增资源对话框 */
function openAddResourceModal() {
  isResourceEdit.value = false;
  resourceEditForm.value = {
    id: "",
    resourceCode: "",
    resourceType: "material",
    resourceName: "",
    description: "",
    specification: "",
    unit: "",
    planQuantity: 0,
    actualQuantity: 0,
    unitPrice: 0,
    currency: "CNY",
    supplier: "",
    status: "planned",
    planArriveDate: "",
    actualArriveDate: "",
    responsibleId: "",
    responsibleName: "",
    location: "",
    tags: []
  };
  resourceEditModal.value = true;
}

/** 打开编辑资源对话框 */
function openEditResourceModal(resource: Resource) {
  isResourceEdit.value = true;
  resourceEditForm.value = { ...resource };
  resourceEditModal.value = true;
}

/** 保存资源 */
async function saveResource() {
  if (!resourceEditForm.value.resourceName) {
    message("请输入资源名称", { type: "warning" });
    return;
  }
  resourceEditLoading.value = true;
  try {
    if (isResourceEdit.value) {
      const updateData: ResourceUpdateRequest = {
        id: resourceEditForm.value.id!,
        resourceType: resourceEditForm.value.resourceType,
        resourceName: resourceEditForm.value.resourceName,
        description: resourceEditForm.value.description,
        specification: resourceEditForm.value.specification,
        unit: resourceEditForm.value.unit,
        planQuantity: resourceEditForm.value.planQuantity,
        actualQuantity: resourceEditForm.value.actualQuantity,
        unitPrice: resourceEditForm.value.unitPrice,
        currency: resourceEditForm.value.currency,
        supplier: resourceEditForm.value.supplier,
        status: resourceEditForm.value.status,
        planArriveDate: resourceEditForm.value.planArriveDate,
        actualArriveDate: resourceEditForm.value.actualArriveDate,
        responsibleId: resourceEditForm.value.responsibleId,
        responsibleName: resourceEditForm.value.responsibleName,
        location: resourceEditForm.value.location,
        tags: resourceEditForm.value.tags
      };
      await updateResource(updateData);
      message("资源更新成功", { type: "success" });
    } else {
      const createData = {
        ...resourceEditForm.value,
        projectId: projectId.value
      };
      await createResource(createData);
      message("资源创建成功", { type: "success" });
    }
    resourceEditModal.value = false;
    await fetchProjectDetail();
  } catch (error) {
    console.error("保存资源失败:", error);
    message("保存资源失败", { type: "error" });
  } finally {
    resourceEditLoading.value = false;
  }
}

/** 删除资源 */
async function handleDeleteResource(resourceId: string) {
  try {
    await deleteResource(resourceId);
    message("资源删除成功", { type: "success" });
    await fetchProjectDetail();
  } catch (error) {
    console.error("删除资源失败:", error);
    message("删除资源失败", { type: "error" });
  }
}

onMounted(() => {
  fetchProjectDetail();
  fetchDailyReportSuggestions();
  fetchGanttData();
});
</script>

<template>
  <div class="project-detail-wrapper">
    <div class="project-detail w-full" :style="marginStyle">
      <!-- 顶部导航 -->
      <div class="flex-bc mb-4">
        <div class="flex items-center gap-3">
          <el-button link @click="goBack">
            <component :is="useRenderIcon(ArrowLeftIcon)" />
          </el-button>
          <div>
            <div class="flex items-center gap-2">
              <h2 class="text-xl font-bold">{{ projectInfo.projectName }}</h2>
              <el-tag :type="getStatusType(projectInfo.status)" size="small">
                {{ projectInfo.statusText }}
              </el-tag>
            </div>
            <p class="text-gray-500 text-sm mt-1">
              项目编号: {{ projectInfo.projectCode }} | 开始日期:
              {{ projectInfo.startDate }} | 预计结束日期:
              {{ projectInfo.endDate }}
            </p>
          </div>
        </div>
        <div class="flex gap-2">
          <el-button>
            <template #icon>
              <component :is="useRenderIcon(DownloadIcon)" />
            </template>
            导出报告
          </el-button>
          <el-button type="primary">
            <template #icon>
              <component :is="useRenderIcon(EditIcon)" />
            </template>
            编辑项目
          </el-button>
        </div>
      </div>

      <!-- 统计卡片 -->
      <el-row :gutter="16" class="mb-4">
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="stat-card">
            <div class="flex-bc">
              <div>
                <p class="text-gray-500 text-sm">项目进度</p>
                <p class="text-2xl font-bold mt-1">
                  {{ projectInfo.progress }}%
                </p>
                <p class="text-xs text-green-500 mt-1">
                  <el-icon
                    ><component :is="useRenderIcon('ri/arrow-up-line')"
                  /></el-icon>
                  {{ projectInfo.progressChange }}%
                </p>
              </div>
              <div class="stat-icon bg-blue-100">
                <el-icon :size="24" color="#409eff">
                  <component :is="useRenderIcon('ri/bar-chart-line')" />
                </el-icon>
              </div>
            </div>
            <el-progress
              :percentage="projectInfo.progress"
              :status="projectInfo.progress === 100 ? 'success' : ''"
              class="mt-3"
            />
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="stat-card">
            <div class="flex-bc">
              <div>
                <p class="text-gray-500 text-sm">项目预算</p>
                <p class="text-2xl font-bold mt-1">¥{{ projectInfo.cost }}万</p>
                <p class="text-xs text-gray-400 mt-1">
                  / ¥{{ projectInfo.budget }}万
                </p>
              </div>
              <div class="stat-icon bg-orange-100">
                <el-icon :size="24" color="#e6a23c">
                  <component :is="useRenderIcon('ri/money-cny-circle-line')" />
                </el-icon>
              </div>
            </div>
            <el-progress
              :percentage="
                projectInfo.budget > 0
                  ? Math.round((projectInfo.cost / projectInfo.budget) * 100)
                  : 0
              "
              status="warning"
              class="mt-3"
            />
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="stat-card">
            <div class="flex-bc">
              <div>
                <p class="text-gray-500 text-sm">团队成员</p>
                <p class="text-2xl font-bold mt-1">
                  {{ projectInfo.teamSize }}人
                </p>
                <p class="text-xs text-gray-400 mt-1">项目参与人员</p>
              </div>
              <div class="stat-icon bg-green-100">
                <el-icon :size="24" color="#67c23a">
                  <component :is="useRenderIcon(UserIcon)" />
                </el-icon>
              </div>
            </div>
            <div class="flex -space-x-2 mt-3">
              <el-avatar
                v-for="member in memberList.slice(0, 4)"
                :key="member.id"
                :size="28"
                :src="
                  member.avatar ||
                  `https://api.dicebear.com/7.x/avataaars/svg?seed=${member.id}`
                "
                :title="getRoleText(member.roleCode)"
                class="cursor-pointer"
                @click="openMemberDetail(member)"
              />
              <el-avatar
                v-if="memberList.length > 4"
                :size="28"
                class="bg-gray-200 cursor-pointer"
              >
                +{{ memberList.length - 4 }}
              </el-avatar>
            </div>
          </el-card>
        </el-col>
        <el-col :xs="24" :sm="12" :md="6">
          <el-card shadow="hover" class="stat-card">
            <div class="flex-bc">
              <div>
                <p class="text-gray-500 text-sm">风险等级</p>
                <p class="text-2xl font-bold mt-1 text-orange-500">
                  {{ projectInfo.riskText }}
                </p>
                <p class="text-xs text-orange-400 mt-1">
                  <component :is="useRenderIcon(AlertIcon)" class="inline" />
                  {{ projectInfo.riskCount }}个潜在风险需要关注
                </p>
              </div>
              <div class="stat-icon bg-orange-100">
                <el-icon :size="24" color="#e6a23c">
                  <component :is="useRenderIcon(AlertIcon)" />
                </el-icon>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="16">
        <!-- 左侧：甘特图 -->
        <el-col :xs="24" :lg="24">
          <!-- 甘特图 -->
          <el-card shadow="hover" class="mb-4">
            <template #header>
              <div class="flex-bc">
                <span class="font-medium">项目进度甘特图</span>
                <div class="flex gap-2">
                  <el-button
                    v-if="canCreateTask"
                    type="primary"
                    size="small"
                    @click="openAddTaskModal"
                  >
                    <template #icon>
                      <component :is="useRenderIcon('ri/add-line')" />
                    </template>
                    新增任务
                  </el-button>
                  <el-button link @click="fetchGanttData">
                    <component :is="useRenderIcon(RefreshIcon)" />
                  </el-button>
                  <el-button link>
                    <component :is="useRenderIcon(FullscreenIcon)" />
                  </el-button>
                </div>
              </div>
            </template>
            <div v-loading="ganttLoading" class="gantt-container">
              <!-- 图例 -->
              <div class="flex flex-wrap gap-4 mb-4 text-sm">
                <div class="flex items-center gap-1">
                  <div class="w-4 h-3 bg-[#409eff] rounded-sm" />
                  <span>进行中</span>
                </div>
                <div class="flex items-center gap-1">
                  <div class="w-4 h-3 bg-[#67c23a] rounded-sm" />
                  <span>已完成</span>
                </div>
                <div class="flex items-center gap-1">
                  <div class="w-4 h-3 bg-[#e6a23c] rounded-sm" />
                  <span>待开始</span>
                </div>
                <div class="flex items-center gap-1">
                  <div class="w-4 h-3 bg-[#f56c6c] rounded-sm" />
                  <span>延期</span>
                </div>
                <div class="flex items-center gap-1">
                  <div class="w-4 h-3 bg-[#909399] rounded-sm" />
                  <span>已取消</span>
                </div>
              </div>

              <!-- 任务甘特图主体 - 使用 vue-ganttastic -->
              <div
                v-if="taskList.length > 0"
                class="gantt-chart-container mb-6"
              >
                <g-gantt-chart
                  :chart-start="ganttDateRange.start"
                  :chart-end="ganttDateRange.end"
                  :precision="ganttPrecision"
                  date-format="YYYY-MM-DD"
                  bar-start="startDate"
                  bar-end="endDate"
                  grid
                  highlight-on-hover
                >
                  <g-gantt-row
                    v-for="task in ganttTasks"
                    :key="task.id"
                    :bars="[task]"
                    :label="task.label"
                  />
                </g-gantt-chart>
              </div>
              <el-empty v-else description="暂无任务数据" class="mb-6" />

              <!-- 任务列表 -->
              <div v-if="taskList.length > 0" class="task-list-section">
                <div class="flex-bc mb-3">
                  <div class="flex items-center gap-2">
                    <el-icon :size="18" color="#409eff">
                      <component :is="useRenderIcon('ri/task-line')" />
                    </el-icon>
                    <span class="font-medium text-base">任务列表</span>
                    <el-tag size="small" type="info"
                      >{{ taskList.length }} 个</el-tag
                    >
                  </div>
                </div>
                <el-table :data="taskList" size="small" stripe>
                  <el-table-column label="任务名称" min-width="150">
                    <template #default="{ row }">
                      <div class="flex items-center gap-2">
                        <div
                          class="size-2 rounded-full"
                          :style="{
                            backgroundColor: getTaskColor(
                              row.status,
                              row.progress
                            )
                          }"
                        />
                        <span class="font-medium">{{ row.taskName }}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="负责人" width="100">
                    <template #default="{ row }">
                      {{ row.assigneeName || "未分配" }}
                    </template>
                  </el-table-column>
                  <el-table-column label="计划日期" width="180">
                    <template #default="{ row }">
                      <div class="text-xs">
                        {{ row.planStartDate || "-" }} ~
                        {{ row.planEndDate || "-" }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="进度" width="120">
                    <template #default="{ row }">
                      <el-progress
                        :percentage="row.progress || 0"
                        :status="row.progress === 100 ? 'success' : ''"
                        :stroke-width="6"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column label="状态" width="90">
                    <template #default="{ row }">
                      <el-tag
                        :type="getTaskStatusType(row.status)"
                        size="small"
                      >
                        {{ getTaskStatusText(row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100" fixed="right">
                    <template #default="{ row }">
                      <el-button
                        v-if="canUpdateTask"
                        link
                        type="primary"
                        size="small"
                        @click="openEditTaskModal(row)"
                      >
                        编辑
                      </el-button>
                      <el-popconfirm
                        v-if="canDeleteTask"
                        title="确定要删除该任务吗？"
                        @confirm="handleDeleteTask(row.id)"
                      >
                        <template #reference>
                          <el-button link type="danger" size="small">
                            删除
                          </el-button>
                        </template>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="16" class="mb-4">
        <el-col :xs="24" :lg="12" class="mb-4 lg:mb-0">
          <el-card shadow="hover">
            <template #header>
              <div class="flex-bc">
                <div class="flex items-center gap-2">
                  <el-icon :size="18" color="#f56c6c">
                    <component :is="useRenderIcon('ri/flag-line')" />
                  </el-icon>
                  <span class="font-medium">项目里程碑</span>
                  <el-tag size="small" type="info"
                    >{{ milestoneList.length }} 个</el-tag
                  >
                </div>
                <el-button
                  v-if="canCreateMilestone"
                  type="primary"
                  size="small"
                  @click="openAddMilestoneModal"
                >
                  <template #icon>
                    <component :is="useRenderIcon('ri/add-line')" />
                  </template>
                  新增里程碑
                </el-button>
              </div>
            </template>

            <el-empty
              v-if="milestoneList.length === 0"
              description="暂无里程碑"
            />
            <div v-else class="milestone-timeline">
              <div
                v-for="(milestone, index) in sortedMilestones"
                :key="milestone.id"
                class="milestone-item"
                :class="{
                  'is-completed': milestone.status === 'completed',
                  'is-key': milestone.isKey === 1
                }"
              >
                <div class="milestone-marker">
                  <div
                    class="milestone-dot"
                    :style="{
                      backgroundColor: getMilestoneColor(
                        milestone.status,
                        milestone.isKey
                      )
                    }"
                  >
                    <el-icon
                      v-if="milestone.status === 'completed'"
                      :size="12"
                      color="#fff"
                    >
                      <component :is="useRenderIcon('ri/check-line')" />
                    </el-icon>
                    <el-icon
                      v-else-if="milestone.isKey === 1"
                      :size="12"
                      color="#fff"
                    >
                      <component :is="useRenderIcon('ri/star-fill')" />
                    </el-icon>
                  </div>
                  <div
                    v-if="index < sortedMilestones.length - 1"
                    class="milestone-line"
                  />
                </div>
                <div class="milestone-content">
                  <div class="milestone-header">
                    <span class="milestone-name">{{
                      milestone.milestoneName
                    }}</span>
                    <el-tag
                      size="small"
                      :type="
                        milestone.status === 'completed'
                          ? 'success'
                          : milestone.status === 'in_progress'
                            ? 'primary'
                            : 'info'
                      "
                    >
                      {{ getMilestoneStatusText(milestone.status) }}
                    </el-tag>
                    <el-tag
                      v-if="milestone.isKey === 1"
                      size="small"
                      type="danger"
                      effect="dark"
                    >
                      关键
                    </el-tag>
                  </div>
                  <div class="milestone-date">
                    <el-icon :size="12">
                      <component :is="useRenderIcon('ri/calendar-line')" />
                    </el-icon>
                    <span>计划日期: {{ milestone.planDate }}</span>
                    <span v-if="milestone.actualDate" class="actual-date">
                      (实际: {{ milestone.actualDate }})
                    </span>
                  </div>
                  <div v-if="milestone.description" class="milestone-desc">
                    {{ milestone.description }}
                  </div>
                  <div
                    v-if="canUpdateMilestone || canDeleteMilestone"
                    class="milestone-actions"
                  >
                    <el-button
                      v-if="canUpdateMilestone"
                      link
                      type="primary"
                      size="small"
                      @click="openEditMilestoneModal(milestone)"
                    >
                      编辑
                    </el-button>
                    <el-popconfirm
                      v-if="canDeleteMilestone"
                      title="确定要删除该里程碑吗？"
                      @confirm="handleDeleteMilestone(milestone.id)"
                    >
                      <template #reference>
                        <el-button link type="danger" size="small"
                          >删除</el-button
                        >
                      </template>
                    </el-popconfirm>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <el-col :xs="24" :lg="12">
          <el-card shadow="hover">
            <template #header>
              <div class="flex-bc">
                <div class="flex items-center gap-2">
                  <component :is="useRenderIcon(RobotIcon)" />
                  <span class="font-medium">进度更新建议</span>
                  <el-tag
                    v-if="dailyReportSuggestions?.suggestions?.length"
                    size="small"
                    type="info"
                  >
                    {{ dailyReportSuggestions.suggestions.length }} 条
                  </el-tag>
                </div>
                <div class="flex gap-2">
                  <el-popconfirm
                    title="确认同意并应用所选建议吗？"
                    @confirm="handleApplySelectedSuggestions"
                  >
                    <template #reference>
                      <el-button
                        type="primary"
                        size="small"
                        :disabled="selectedSuggestionIds.length === 0"
                        :loading="suggestionsApplying"
                      >
                        同意所选
                      </el-button>
                    </template>
                  </el-popconfirm>
                  <el-button
                    link
                    :disabled="suggestionsLoading"
                    @click="fetchDailyReportSuggestions"
                  >
                    <component :is="useRenderIcon(RefreshIcon)" />
                  </el-button>
                </div>
              </div>
            </template>
            <div v-loading="suggestionsLoading">
              <el-empty
                v-if="!dailyReportSuggestions?.suggestions?.length"
                description="暂无进度更新建议"
              />
              <div v-else>
                <div
                  v-if="dailyReportSuggestions.overallProgressAssessment"
                  class="mb-4"
                >
                  <div class="flex items-center gap-2 mb-2">
                    <span class="font-medium">总体评估</span>
                    <el-tag
                      size="small"
                      :type="
                        getOverallAssessmentType(
                          dailyReportSuggestions.overallProgressAssessment
                            .status
                        )
                      "
                    >
                      {{
                        getOverallAssessmentText(
                          dailyReportSuggestions.overallProgressAssessment
                            .status
                        )
                      }}
                    </el-tag>
                    <span class="text-sm text-gray-500">
                      偏差
                      {{
                        formatDeviation(
                          dailyReportSuggestions.overallProgressAssessment
                            .deviationPercentage
                        )
                      }}
                    </span>
                  </div>
                  <div
                    v-if="
                      dailyReportSuggestions.overallProgressAssessment
                        .description
                    "
                    class="text-sm text-gray-600"
                  >
                    {{
                      dailyReportSuggestions.overallProgressAssessment
                        .description
                    }}
                  </div>
                  <div
                    v-if="
                      dailyReportSuggestions.overallProgressAssessment.keyIssues
                        ?.length
                    "
                    class="mt-2 flex flex-wrap gap-2"
                  >
                    <el-tag
                      v-for="(issue, index) in dailyReportSuggestions
                        .overallProgressAssessment.keyIssues"
                      :key="index"
                      size="small"
                      type="warning"
                    >
                      {{ issue }}
                    </el-tag>
                  </div>
                </div>

                <el-table
                  :data="dailyReportSuggestions.suggestions || []"
                  style="width: 100%"
                  @selection-change="handleSuggestionSelectionChange"
                >
                  <el-table-column type="selection" width="50" />
                  <el-table-column label="目标" min-width="220">
                    <template #default="{ row }">
                      <div class="font-medium">
                        {{ row.targetName || "--" }}
                      </div>
                      <div class="text-xs text-gray-400">
                        {{ row.targetType || "--" }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="当前" width="140">
                    <template #default="{ row }">
                      <div class="text-sm">{{ row.currentStatus || "--" }}</div>
                      <div class="text-xs text-gray-400">
                        {{ row.currentProgress ?? "--" }}%
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="建议" width="140">
                    <template #default="{ row }">
                      <div class="text-sm">
                        {{ row.suggestedStatus || "--" }}
                      </div>
                      <div class="text-xs text-gray-400">
                        {{ row.suggestedProgress ?? "--" }}%
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column label="原因" min-width="260" prop="reason" />
                  <el-table-column label="置信度" width="100">
                    <template #default="{ row }">
                      <span
                        v-if="
                          row.confidence !== undefined &&
                          row.confidence !== null
                        "
                      >
                        {{ Math.round(Number(row.confidence) * 100) }}%
                      </span>
                      <span v-else>--</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="状态" width="100">
                    <template #default="{ row }">
                      <el-tag
                        size="small"
                        :type="getSuggestionStatusType(row.status)"
                      >
                        {{ getSuggestionStatusText(row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                      <el-popconfirm
                        title="确认同意并应用该建议吗？"
                        @confirm="handleApplySuggestions([row.suggestionId])"
                      >
                        <template #reference>
                          <el-button
                            link
                            type="primary"
                            size="small"
                            :disabled="
                              !row.suggestionId ||
                              isSuggestionApplied(row.status)
                            "
                            :loading="suggestionsApplying"
                          >
                            同意
                          </el-button>
                        </template>
                      </el-popconfirm>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 主要内容区 -->
      <el-row :gutter="16">
        <!-- 左侧：物料清单 -->
        <el-col :xs="24" :lg="24">
          <!-- 物料清单 -->
          <el-card shadow="hover">
            <template #header>
              <div class="flex-bc">
                <div class="flex items-center gap-2">
                  <component :is="useRenderIcon(FileListIcon)" />
                  <span class="font-medium">项目物料清单</span>
                  <el-tag size="small" type="info"
                    >{{ resourceList.length }} 个</el-tag
                  >
                </div>
                <div class="flex gap-2">
                  <el-button
                    v-if="canCreateResource"
                    type="primary"
                    size="small"
                    @click="openAddResourceModal"
                  >
                    <template #icon>
                      <component :is="useRenderIcon('ri/add-line')" />
                    </template>
                    新增资源
                  </el-button>
                  <el-button link type="primary">
                    查看全部
                    <component :is="useRenderIcon(ArrowRightIcon)" />
                  </el-button>
                </div>
              </div>
            </template>
            <el-table :data="resourceList" style="width: 100%">
              <el-table-column label="资源名称" min-width="200">
                <template #default="{ row }">
                  <div class="flex items-center gap-2">
                    <div
                      class="resource-icon-wrapper"
                      :style="{
                        backgroundColor:
                          getResourceTypeColor(row.resourceType) + '20'
                      }"
                    >
                      <el-icon
                        :size="18"
                        :color="getResourceTypeColor(row.resourceType)"
                      >
                        <component
                          :is="
                            useRenderIcon(getResourceTypeIcon(row.resourceType))
                          "
                        />
                      </el-icon>
                    </div>
                    <div>
                      <div class="font-medium">{{ row.resourceName }}</div>
                      <div class="text-xs text-gray-400">
                        {{ getResourceTypeText(row.resourceType) }}
                      </div>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="specification" width="120" />
              <el-table-column label="数量" width="100">
                <template #default="{ row }">
                  {{ row.planQuantity }} {{ row.unit }}
                </template>
              </el-table-column>
              <el-table-column label="状态" width="100">
                <template #default="{ row }">
                  <el-tag
                    :type="getResourceStatusType(row.status)"
                    size="small"
                  >
                    {{ getResourceStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="预计到货" width="120">
                <template #default="{ row }">
                  <div class="flex items-center gap-1">
                    <span>{{ row.planArriveDate || "--" }}</span>
                    <el-icon
                      v-if="row.status === 'arrived' || row.status === 'actual'"
                      color="#67c23a"
                      class="ml-1"
                    >
                      <component :is="useRenderIcon(CheckIcon)" />
                    </el-icon>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="130" fixed="right">
                <template #default="{ row }">
                  <el-button
                    v-if="canUpdateResource"
                    link
                    type="primary"
                    size="small"
                    @click="openEditResourceModal(row)"
                  >
                    编辑
                  </el-button>
                  <el-popconfirm
                    v-if="canDeleteResource"
                    title="确定要删除该资源吗？"
                    @confirm="handleDeleteResource(row.id)"
                  >
                    <template #reference>
                      <el-button link type="danger" size="small">
                        删除
                      </el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 成员详情模态框 -->
    <el-dialog
      v-model="memberDetailModal"
      title="成员详情"
      width="500px"
      destroy-on-close
    >
      <div v-if="selectedMember" class="member-detail-content">
        <div class="flex items-center gap-4 mb-6">
          <el-avatar
            :size="80"
            :src="
              selectedMember.avatar ||
              `https://api.dicebear.com/7.x/avataaars/svg?seed=${selectedMember.id}`
            "
          />
          <div>
            <h3 class="text-xl font-bold">{{ selectedMember.realName }}</h3>
            <p class="text-gray-500">{{ selectedMember.userName }}</p>
            <el-tag
              size="small"
              :type="
                selectedMember.roleCode === 'manager'
                  ? 'primary'
                  : selectedMember.roleCode === 'leader'
                    ? 'success'
                    : 'info'
              "
              class="mt-2"
            >
              {{ getRoleText(selectedMember.roleCode) }}
            </el-tag>
          </div>
        </div>

        <el-divider />

        <div class="member-info-grid">
          <div class="info-item">
            <span class="info-label">所属部门</span>
            <span class="info-value">{{
              selectedMember.department || "未设置"
            }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">职责</span>
            <span class="info-value">{{
              selectedMember.responsibility || "未设置"
            }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">每周工时</span>
            <span class="info-value"
              >{{ selectedMember.weeklyHours }} 小时</span
            >
          </div>
          <div class="info-item">
            <span class="info-label">加入日期</span>
            <span class="info-value">{{
              selectedMember.joinDate || "未设置"
            }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">状态</span>
            <span class="info-value">
              <el-tag
                size="small"
                :type="selectedMember.status === 1 ? 'success' : 'danger'"
              >
                {{ selectedMember.status === 1 ? "活跃" : "非活跃" }}
              </el-tag>
            </span>
          </div>
        </div>
      </div>
      <div v-else class="text-center py-10">
        <el-empty description="暂无成员信息" />
      </div>
    </el-dialog>

    <!-- 任务编辑模态框 -->
    <el-dialog
      v-model="taskEditModal"
      :title="isTaskEdit ? '编辑任务' : '新增任务'"
      width="600px"
      destroy-on-close
    >
      <el-form
        ref="taskFormRef"
        :model="taskEditForm"
        label-width="100px"
        class="task-edit-form"
      >
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="任务名称" prop="taskName" required>
              <el-input
                v-model="taskEditForm.taskName"
                placeholder="请输入任务名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务类型">
              <el-select
                v-model="taskEditForm.taskType"
                placeholder="请选择任务类型"
                clearable
              >
                <el-option label="设计" value="design" />
                <el-option label="开发" value="development" />
                <el-option label="测试" value="testing" />
                <el-option label="部署" value="deployment" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属里程碑">
              <el-select
                v-model="taskEditForm.milestoneId"
                placeholder="请选择所属里程碑"
                clearable
              >
                <el-option
                  v-for="ms in milestoneList"
                  :key="ms.id"
                  :label="ms.milestoneName"
                  :value="ms.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划开始">
              <el-date-picker
                v-model="taskEditForm.planStartDate"
                type="date"
                placeholder="选择开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结束">
              <el-date-picker
                v-model="taskEditForm.planEndDate"
                type="date"
                placeholder="选择结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-input
                v-model="taskEditForm.assigneeName"
                placeholder="请输入负责人姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="优先级">
              <el-select
                v-model="taskEditForm.priority"
                placeholder="请选择优先级"
              >
                <el-option label="关键" value="critical" />
                <el-option label="高" value="high" />
                <el-option label="中" value="medium" />
                <el-option label="低" value="low" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select v-model="taskEditForm.status" placeholder="请选择状态">
                <el-option label="待开始" value="pending" />
                <el-option label="进行中" value="in_progress" />
                <el-option label="已完成" value="completed" />
                <el-option label="已取消" value="cancelled" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进度">
              <el-slider
                v-model="taskEditForm.progress"
                :max="100"
                show-input
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划工时">
              <el-input-number
                v-model="taskEditForm.planHours"
                :min="0"
                placeholder="小时"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际工时">
              <el-input-number
                v-model="taskEditForm.actualHours"
                :min="0"
                placeholder="小时"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input
                v-model="taskEditForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入任务描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="taskEditModal = false">取消</el-button>
        <el-button
          v-if="canSaveTask"
          type="primary"
          :loading="taskEditLoading"
          @click="saveTask"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 里程碑编辑模态框 -->
    <el-dialog
      v-model="milestoneEditModal"
      :title="isMilestoneEdit ? '编辑里程碑' : '新增里程碑'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="milestoneFormRef"
        :model="milestoneEditForm"
        label-width="100px"
        class="milestone-edit-form"
      >
        <el-form-item label="里程碑名称" prop="milestoneName" required>
          <el-input
            v-model="milestoneEditForm.milestoneName"
            placeholder="请输入里程碑名称"
          />
        </el-form-item>
        <el-form-item label="计划日期" prop="planDate" required>
          <el-date-picker
            v-model="milestoneEditForm.planDate"
            type="date"
            placeholder="选择计划日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="实际日期">
          <el-date-picker
            v-model="milestoneEditForm.actualDate"
            type="date"
            placeholder="选择实际日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="milestoneEditForm.status"
            placeholder="请选择状态"
          >
            <el-option label="待开始" value="pending" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="延期" value="delayed" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度">
          <el-slider
            v-model="milestoneEditForm.progress"
            :max="100"
            show-input
          />
        </el-form-item>
        <el-form-item label="关键里程碑">
          <el-switch
            v-model="milestoneEditForm.isKey"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="交付物">
          <el-input
            v-model="milestoneEditForm.deliverables"
            placeholder="请输入交付物"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="milestoneEditForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="milestoneEditModal = false">取消</el-button>
        <el-button
          v-if="canSaveMilestone"
          type="primary"
          :loading="milestoneEditLoading"
          @click="saveMilestone"
        >
          保存
        </el-button>
      </template>
    </el-dialog>

    <!-- 资源编辑模态框 -->
    <el-dialog
      v-model="resourceEditModal"
      :title="isResourceEdit ? '编辑资源' : '新增资源'"
      width="650px"
      destroy-on-close
    >
      <el-form
        ref="resourceFormRef"
        :model="resourceEditForm"
        label-width="100px"
        class="resource-edit-form"
      >
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="资源名称" prop="resourceName" required>
              <el-input
                v-model="resourceEditForm.resourceName"
                placeholder="请输入资源名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资源类型">
              <el-select
                v-model="resourceEditForm.resourceType"
                placeholder="请选择资源类型"
                style="width: 100%"
              >
                <el-option label="人力" value="human" />
                <el-option label="物料" value="material" />
                <el-option label="设备" value="equipment" />
                <el-option label="软件" value="software" />
                <el-option label="资金" value="finance" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号">
              <el-input
                v-model="resourceEditForm.specification"
                placeholder="请输入规格型号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划数量">
              <el-input-number
                v-model="resourceEditForm.planQuantity"
                :min="0"
                :precision="2"
                placeholder="数量"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位">
              <el-input
                v-model="resourceEditForm.unit"
                placeholder="如：个、台、套"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单价">
              <el-input-number
                v-model="resourceEditForm.unitPrice"
                :min="0"
                :precision="2"
                placeholder="单价"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种">
              <el-select
                v-model="resourceEditForm.currency"
                placeholder="请选择币种"
                style="width: 100%"
              >
                <el-option label="人民币 (CNY)" value="CNY" />
                <el-option label="美元 (USD)" value="USD" />
                <el-option label="欧元 (EUR)" value="EUR" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商">
              <el-input
                v-model="resourceEditForm.supplier"
                placeholder="请输入供应商"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-select
                v-model="resourceEditForm.status"
                placeholder="请选择状态"
                style="width: 100%"
              >
                <el-option label="计划中" value="planned" />
                <el-option label="已申请" value="requested" />
                <el-option label="已批准" value="approved" />
                <el-option label="采购中" value="procuring" />
                <el-option label="已到货" value="arrived" />
                <el-option label="使用中" value="in_use" />
                <el-option label="已完成" value="completed" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划到位日期">
              <el-date-picker
                v-model="resourceEditForm.planArriveDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际到位日期">
              <el-date-picker
                v-model="resourceEditForm.actualArriveDate"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人">
              <el-input
                v-model="resourceEditForm.responsibleName"
                placeholder="请输入负责人姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="存放位置">
              <el-input
                v-model="resourceEditForm.location"
                placeholder="请输入存放位置"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述">
              <el-input
                v-model="resourceEditForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入资源描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button @click="resourceEditModal = false">取消</el-button>
        <el-button
          v-if="canSaveResource"
          type="primary"
          :loading="resourceEditLoading"
          @click="saveResource"
        >
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.project-detail-wrapper {
  width: 100%;
}

.project-detail {
  padding: 16px;
}

.stat-card {
  .stat-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 48px;
    height: 48px;
    border-radius: 8px;
  }
}

// 甘特图样式
.gantt-container {
  min-height: 300px;
}

.gantt-chart-container {
  :deep(.g-gantt-chart) {
    background-color: #fafafa;
    border-radius: 8px;
  }

  :deep(.g-gantt-row) {
    &:hover {
      background-color: #f0f2f5;
    }
  }

  :deep(.g-gantt-bar) {
    border-radius: 4px;
    box-shadow: 0 2px 4px rgb(0 0 0 / 10%);
  }
}

.quick-questions {
  padding: 8px 16px;
  border-top: 1px solid #e4e7ed;

  .el-button {
    font-size: 12px;
  }
}

.ai-input-area {
  padding: 12px 16px;
  border-top: 1px solid #e4e7ed;
}

// 里程碑区域样式
.milestone-section {
  padding-top: 16px;
  border-top: 1px dashed #e4e7ed;
}

// 任务列表区域样式
.task-list-section {
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px dashed #e4e7ed;
}

// 里程碑时间线样式
.milestone-timeline {
  padding: 8px 0;
}

.milestone-item {
  display: flex;
  gap: 16px;
  padding: 12px 0;

  &.is-completed {
    .milestone-content {
      opacity: 0.8;
    }
  }
}

.milestone-marker {
  display: flex;
  flex-shrink: 0;
  flex-direction: column;
  align-items: center;
}

.milestone-dot {
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  box-shadow: 0 2px 8px rgb(0 0 0 / 15%);
}

.milestone-line {
  flex: 1;
  width: 2px;
  min-height: 40px;
  margin-top: 4px;
  background: linear-gradient(to bottom, #dcdfe6, #e4e7ed);
}

.milestone-content {
  flex: 1;
  padding-bottom: 8px;
}

.milestone-actions {
  display: flex;
  gap: 8px;
  margin-top: 8px;
}

.milestone-header {
  display: flex;
  gap: 8px;
  align-items: center;
  margin-bottom: 6px;
}

.milestone-name {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.milestone-date {
  display: flex;
  gap: 4px;
  align-items: center;
  margin-bottom: 4px;
  font-size: 12px;
  color: #606266;

  .actual-date {
    font-weight: 500;
    color: #67c23a;
  }
}

.milestone-desc {
  margin-top: 4px;
  font-size: 12px;
  line-height: 1.5;
  color: #909399;
}

// 边距设置按钮
.margin-setting-btn {
  position: fixed;
  top: 80px;
  right: 20px;
  z-index: 100;
  width: 36px;
  height: 36px;
  background-color: #fff;
  border-radius: 50%;
  box-shadow: 0 2px 12px rgb(0 0 0 / 10%);

  &:hover {
    background-color: #f5f7fa;
  }
}

// 边距设置面板
.margin-setting-panel {
  padding: 8px;

  .setting-title {
    margin-bottom: 12px;
    font-size: 14px;
    font-weight: 600;
    color: #303133;
    text-align: center;
  }

  .setting-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;

    span {
      font-size: 13px;
      color: #606266;
    }
  }

  .el-button {
    width: 100%;
    margin-top: 8px;
  }
}

// 成员详情模态框样式
.member-detail-content {
  .member-info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
  }

  .info-item {
    display: flex;
    flex-direction: column;
    gap: 4px;

    .info-label {
      font-size: 13px;
      color: #909399;
    }

    .info-value {
      font-size: 14px;
      color: #303133;
    }
  }
}

// 资源图标包装器
.resource-icon-wrapper {
  display: flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 8px;
}

// 鼠标悬停效果
.cursor-pointer {
  cursor: pointer;
  transition: transform 0.2s ease;

  &:hover {
    transform: scale(1.05);
  }
}
</style>
