<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from "vue";
import { message } from "@/utils/message";
import { confirmProjectInit, type ProjectInitTaskVO } from "@/api/project";
import type { ProjectInitResult } from "@/api/project";
import {
  WizardStep,
  PriorityOptions,
  ProjectTypeOptions
} from "../utils/types";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { useSseStoreHook } from "@/store/modules/sse";
import UploadIcon from "~icons/ri/upload-cloud-line";
import FileIcon from "~icons/ri/file-line";
import CheckIcon from "~icons/ri/check-line";
import DeleteIcon from "~icons/ri/delete-bin-line";
import AddIcon from "~icons/ri/add-line";
import LoadingIcon from "~icons/ri/loader-4-line";
import TimeIcon from "~icons/ri/time-line";

const props = defineProps<{
  visible: boolean;
}>();

const emit = defineEmits<{
  (e: "update:visible", value: boolean): void;
  (e: "success"): void;
}>();

const dialogVisible = computed({
  get: () => props.visible,
  set: val => emit("update:visible", val)
});

const currentStep = ref<WizardStep>(WizardStep.Upload);
const uploading = ref(false);
const saving = ref(false);
const uploadRef = ref();
const fileList = ref<File[]>([]);

// SSE Store
const sseStore = useSseStoreHook();
const taskProgress = computed(() => sseStore.taskProgress);
const taskStatus = computed(() => sseStore.taskStatus);
const currentTask = computed(() => sseStore.currentTask);
const myTasks = computed(() => sseStore.getMyTasks);
const hasProcessingTask = computed(() => sseStore.getHasProcessingTask);

// 对话框打开时查询任务列表
watch(
  () => props.visible,
  visible => {
    if (visible) {
      sseStore.fetchMyTasks();
    }
  }
);

// 监听任务完成
watch(
  () => sseStore.taskStatus,
  newStatus => {
    if (newStatus === "completed" && currentTask.value?.result) {
      Object.assign(projectData, currentTask.value.result);
      currentStep.value = WizardStep.Preview;
      uploading.value = false;
      message("文件解析成功", { type: "success" });
      sseStore.resetTaskStatus();
    } else if (newStatus === "error") {
      uploading.value = false;
      message(sseStore.errorMessage || "文件解析失败", { type: "error" });
      sseStore.resetTaskStatus();
    }
  },
  { immediate: false }
);

// 项目初始化数据
const projectData = reactive<ProjectInitResult>({
  project: {
    project_name: "",
    project_type: "",
    description: "",
    objectives: "",
    plan_start_date: "",
    plan_end_date: "",
    budget: 0,
    currency: "CNY",
    priority: "medium",
    tags: []
  },
  milestones: [],
  tasks: [],
  members: [],
  resources: [],
  risks: [],
  timeline_nodes: []
});

// 步骤标题
const stepTitles = ["上传项目资料", "预览项目数据", "确认保存"];

// 关闭对话框
function handleClose() {
  dialogVisible.value = false;
  resetData();
}

// 重置数据
function resetData() {
  currentStep.value = WizardStep.Upload;
  fileList.value = [];
  Object.assign(projectData, {
    project: {
      project_name: "",
      project_type: "",
      description: "",
      objectives: "",
      plan_start_date: "",
      plan_end_date: "",
      budget: 0,
      currency: "CNY",
      priority: "medium",
      tags: []
    },
    milestones: [],
    tasks: [],
    members: [],
    resources: [],
    risks: [],
    timeline_nodes: []
  });
}

// 文件上传前
function beforeUpload(file: File) {
  const validTypes = [
    "application/pdf",
    "application/msword",
    "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
    "text/plain"
  ];
  const isValidType = validTypes.includes(file.type);
  if (!isValidType) {
    message("请上传 PDF、Word 或文本文件", { type: "warning" });
  }
  return isValidType;
}

// 文件变化
function handleFileChange(file: any) {
  fileList.value = [file.raw];
}

// 移除文件
function handleRemove() {
  fileList.value = [];
}

// 上传并预览（使用 SSE）
async function handleUploadAndPreview() {
  if (fileList.value.length === 0) {
    message("请先选择文件", { type: "warning" });
    return;
  }

  if (!sseStore.getIsConnected) {
    message("SSE 连接未建立，请刷新页面重试", { type: "warning" });
    return;
  }

  uploading.value = true;
  try {
    const result = await sseStore.submitProjectInitTask(fileList.value[0]);
    if (result.code !== 200) {
      message(result.message || "提交任务失败", { type: "error" });
      uploading.value = false;
    }
    // 进度和结果将通过 SSE 推送，由 watch 监听处理
  } catch (error) {
    message("文件上传失败，请检查文件格式", { type: "error" });
    uploading.value = false;
  }
}

// 上一步
function handlePrev() {
  if (currentStep.value > WizardStep.Upload) {
    currentStep.value--;
  }
}

// 下一步
function handleNext() {
  if (currentStep.value < WizardStep.Confirm) {
    currentStep.value++;
  }
}

// 确认保存
async function handleConfirm() {
  saving.value = true;
  try {
    const { code } = await confirmProjectInit(projectData);
    if (code === 200) {
      message("项目创建成功", { type: "success" });
      emit("success");
      handleClose();
    }
  } catch (error) {
    message("项目创建失败", { type: "error" });
  } finally {
    saving.value = false;
  }
}

// 添加里程碑
function addMilestone() {
  projectData.milestones.push({
    milestone_name: "",
    description: "",
    plan_date: "",
    deliverables: "",
    owner_role: ""
  });
}

// 删除里程碑
function removeMilestone(index: number) {
  projectData.milestones.splice(index, 1);
}

// 添加任务
function addTask() {
  projectData.tasks.push({
    task_id: `task_${Date.now()}`,
    task_name: "",
    parent_task_id: "",
    description: "",
    plan_start_date: "",
    plan_end_date: "",
    estimated_hours: 0,
    priority: "medium",
    assignee_role: "",
    dependencies: [],
    deliverables: ""
  });
}

// 删除任务
function removeTask(index: number) {
  projectData.tasks.splice(index, 1);
}

// 添加成员
function addMember() {
  projectData.members.push({
    name: "",
    role_code: "",
    responsibility: "",
    department: "",
    weekly_hours: 40
  });
}

// 删除成员
function removeMember(index: number) {
  projectData.members.splice(index, 1);
}

// 添加风险
function addRisk() {
  projectData.risks.push({
    risk_name: "",
    category: "",
    description: "",
    probability: 1,
    impact: 1,
    mitigation_plan: ""
  });
}

// 删除风险
function removeRisk(index: number) {
  projectData.risks.splice(index, 1);
}

// 使用已完成任务的结果
function handleUseTaskResult(task: ProjectInitTaskVO) {
  if (task.result) {
    Object.assign(projectData, task.result);
    currentStep.value = WizardStep.Preview;
    message("已加载任务结果", { type: "success" });
  }
}

// 标签输入
const tagInput = ref("");
function handleTagInput() {
  if (tagInput.value && !projectData.project.tags?.includes(tagInput.value)) {
    projectData.project.tags?.push(tagInput.value);
    tagInput.value = "";
  }
}

function removeTag(tag: string) {
  const index = projectData.project.tags?.indexOf(tag);
  if (index !== undefined && index > -1) {
    projectData.project.tags?.splice(index, 1);
  }
}
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="新建项目"
    width="900px"
    :close-on-click-modal="false"
    :before-close="handleClose"
    destroy-on-close
  >
    <!-- 步骤条 -->
    <el-steps :active="currentStep" finish-status="success" class="mb-6">
      <el-step
        v-for="(title, index) in stepTitles"
        :key="index"
        :title="title"
      />
    </el-steps>

    <!-- 步骤 1: 上传文件 -->
    <div v-if="currentStep === WizardStep.Upload" class="upload-step">
      <el-upload
        ref="uploadRef"
        drag
        :auto-upload="false"
        :show-file-list="true"
        :limit="1"
        :before-upload="beforeUpload"
        :on-change="handleFileChange"
        :on-remove="handleRemove"
        class="upload-area"
      >
        <el-icon class="el-icon--upload">
          <component :is="useRenderIcon(UploadIcon)" />
        </el-icon>
        <div class="el-upload__text">拖拽文件到此处或 <em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            支持 PDF、Word、TXT 格式的项目资料文件
          </div>
        </template>
      </el-upload>

      <!-- 待处理任务列表 -->
      <div v-if="myTasks.length > 0" class="task-list-container mt-4">
        <div class="flex items-center gap-2 mb-3">
          <el-icon class="text-blue-500">
            <component :is="useRenderIcon(TimeIcon)" />
          </el-icon>
          <span class="text-sm font-medium">我的任务</span>
        </div>
        <div class="task-list">
          <div
            v-for="task in myTasks"
            :key="task.taskId"
            class="task-item"
            :class="{
              'task-processing': task.status === 'processing',
              'task-completed': task.status === 'completed',
              'task-failed': task.status === 'failed'
            }"
          >
            <div class="task-info">
              <span class="task-filename">{{ task.originalFilename }}</span>
              <el-tag
                :type="
                  task.status === 'completed'
                    ? 'success'
                    : task.status === 'processing'
                      ? 'warning'
                      : task.status === 'failed'
                        ? 'danger'
                        : 'info'
                "
                size="small"
              >
                {{ task.statusDesc }}
              </el-tag>
            </div>
            <div v-if="task.status === 'processing'" class="task-progress">
              <el-progress
                :percentage="task.progress"
                :stroke-width="4"
                :show-text="false"
              />
              <span class="text-xs text-gray-500 ml-2"
                >{{ task.progress }}%</span
              >
            </div>
            <div v-if="task.status === 'completed'" class="task-actions">
              <el-button
                type="primary"
                size="small"
                link
                @click="handleUseTaskResult(task)"
              >
                使用此结果
              </el-button>
            </div>
            <div v-if="task.status === 'failed'" class="task-error">
              <span class="text-xs text-red-500">{{ task.errorMessage }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 进度显示 -->
      <div v-if="uploading" class="progress-container mt-6">
        <div class="flex-c gap-2 mb-2">
          <el-icon class="is-loading">
            <component :is="useRenderIcon(LoadingIcon)" />
          </el-icon>
          <span class="text-sm text-gray-600">
            {{
              taskStatus === "submitted"
                ? "任务已提交，等待处理..."
                : currentTask?.progressMessage || "正在解析..."
            }}
          </span>
        </div>
        <el-progress
          :percentage="taskProgress"
          :stroke-width="8"
          :status="taskStatus === 'error' ? 'exception' : undefined"
          class="w-full max-w-md mx-auto"
        />
        <div class="text-center mt-2 text-xs text-gray-400">
          进度: {{ taskProgress }}%
        </div>
      </div>

      <div class="flex justify-center mt-6">
        <el-button
          type="primary"
          :loading="uploading"
          :disabled="fileList.length === 0 || uploading"
          @click="handleUploadAndPreview"
        >
          {{ uploading ? "解析中..." : "解析文件" }}
        </el-button>
      </div>
    </div>

    <!-- 步骤 2: 预览和编辑 -->
    <div v-if="currentStep === WizardStep.Preview" class="preview-step">
      <el-scrollbar height="500px">
        <el-form label-width="100px" class="project-form">
          <!-- 项目基本信息 -->
          <el-divider content-position="left">项目基本信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="项目名称">
                <el-input v-model="projectData.project.project_name" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目类型">
                <el-select
                  v-model="projectData.project.project_type"
                  style="width: 100%"
                >
                  <el-option
                    v-for="opt in ProjectTypeOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="开始日期">
                <el-date-picker
                  v-model="projectData.project.plan_start_date"
                  type="date"
                  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="projectData.project.plan_end_date"
                  type="date"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预算">
                <el-input-number
                  v-model="projectData.project.budget"
                  :min="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级">
                <el-select
                  v-model="projectData.project.priority"
                  style="width: 100%"
                >
                  <el-option
                    v-for="opt in PriorityOptions"
                    :key="opt.value"
                    :label="opt.label"
                    :value="opt.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="标签">
            <div class="flex flex-wrap gap-2">
              <el-tag
                v-for="tag in projectData.project.tags"
                :key="tag"
                closable
                @close="removeTag(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-model="tagInput"
                size="small"
                style="width: 100px"
                @keyup.enter="handleTagInput"
                @blur="handleTagInput"
              />
            </div>
          </el-form-item>
          <el-form-item label="项目描述">
            <el-input
              v-model="projectData.project.description"
              type="textarea"
              :rows="3"
            />
          </el-form-item>
          <el-form-item label="项目目标">
            <el-input
              v-model="projectData.project.objectives"
              type="textarea"
              :rows="3"
            />
          </el-form-item>

          <!-- 里程碑 -->
          <el-divider content-position="left">
            里程碑
            <el-button
              type="primary"
              link
              :icon="useRenderIcon(AddIcon)"
              @click="addMilestone"
            >
              添加
            </el-button>
          </el-divider>
          <div
            v-for="(milestone, index) in projectData.milestones"
            :key="index"
            class="sub-form-item"
          >
            <el-row :gutter="10">
              <el-col :span="7">
                <el-input
                  v-model="milestone.milestone_name"
                  placeholder="里程碑名称"
                />
              </el-col>
              <el-col :span="7">
                <el-date-picker
                  v-model="milestone.plan_date"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="计划日期"
                  style="width: 100%"
                />
              </el-col>
              <el-col :span="7">
                <el-input
                  v-model="milestone.owner_role"
                  placeholder="负责人角色"
                />
              </el-col>
              <el-col :span="3">
                <el-button
                  type="danger"
                  link
                  :icon="useRenderIcon(DeleteIcon)"
                  @click="removeMilestone(index)"
                />
              </el-col>
            </el-row>
          </div>

          <!-- 任务清单 -->
          <el-divider content-position="left">
            任务清单
            <el-button
              type="primary"
              link
              :icon="useRenderIcon(AddIcon)"
              @click="addTask"
            >
              添加
            </el-button>
          </el-divider>
          <div
            v-for="(task, index) in projectData.tasks"
            :key="index"
            class="sub-form-item"
          >
            <el-row :gutter="10">
              <el-col :span="8">
                <el-input v-model="task.task_name" placeholder="任务名称" />
              </el-col>
              <el-col :span="6">
                <el-date-picker
                  v-model="task.plan_start_date"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="开始日期"
                  style="width: 100%"
                />
              </el-col>
              <el-col :span="6">
                <el-date-picker
                  v-model="task.plan_end_date"
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="结束日期"
                  style="width: 100%"
                />
              </el-col>
              <el-col :span="4">
                <el-button
                  type="danger"
                  link
                  :icon="useRenderIcon(DeleteIcon)"
                  @click="removeTask(index)"
                />
              </el-col>
            </el-row>
          </div>

          <!-- 项目成员 -->
          <el-divider content-position="left">
            项目成员
            <el-button
              type="primary"
              link
              :icon="useRenderIcon(AddIcon)"
              @click="addMember"
            >
              添加
            </el-button>
          </el-divider>
          <div
            v-for="(member, index) in projectData.members"
            :key="index"
            class="sub-form-item"
          >
            <el-row :gutter="10">
              <el-col :span="6">
                <el-input v-model="member.name" placeholder="姓名" />
              </el-col>
              <el-col :span="6">
                <el-input v-model="member.role_code" placeholder="角色" />
              </el-col>
              <el-col :span="6">
                <el-input v-model="member.department" placeholder="部门" />
              </el-col>
              <el-col :span="6">
                <el-button
                  type="danger"
                  link
                  :icon="useRenderIcon(DeleteIcon)"
                  @click="removeMember(index)"
                />
              </el-col>
            </el-row>
          </div>

          <!-- 风险识别 -->
          <el-divider content-position="left">
            风险识别
            <el-button
              type="primary"
              link
              :icon="useRenderIcon(AddIcon)"
              @click="addRisk"
            >
              添加
            </el-button>
          </el-divider>
          <div
            v-for="(risk, index) in projectData.risks"
            :key="index"
            class="sub-form-item"
          >
            <el-row :gutter="10">
              <el-col :span="8">
                <el-input v-model="risk.risk_name" placeholder="风险名称" />
              </el-col>
              <el-col :span="6">
                <el-select v-model="risk.category" placeholder="类别">
                  <el-option label="技术风险" value="technical" />
                  <el-option label="进度风险" value="schedule" />
                  <el-option label="成本风险" value="cost" />
                  <el-option label="人员风险" value="personnel" />
                  <el-option label="其他" value="other" />
                </el-select>
              </el-col>
              <el-col :span="4">
                <el-rate v-model="risk.probability" :max="5" />
              </el-col>
              <el-col :span="6">
                <el-button
                  type="danger"
                  link
                  :icon="useRenderIcon(DeleteIcon)"
                  @click="removeRisk(index)"
                />
              </el-col>
            </el-row>
          </div>
        </el-form>
      </el-scrollbar>
    </div>

    <!-- 步骤 3: 确认保存 -->
    <div v-if="currentStep === WizardStep.Confirm" class="confirm-step">
      <el-alert
        title="请确认以下项目信息"
        type="info"
        :closable="false"
        class="mb-4"
      />
      <el-descriptions :column="2" border>
        <el-descriptions-item label="项目名称">
          {{ projectData.project.project_name }}
        </el-descriptions-item>
        <el-descriptions-item label="项目类型">
          {{ projectData.project.project_type }}
        </el-descriptions-item>
        <el-descriptions-item label="开始日期">
          {{ projectData.project.plan_start_date }}
        </el-descriptions-item>
        <el-descriptions-item label="结束日期">
          {{ projectData.project.plan_end_date }}
        </el-descriptions-item>
        <el-descriptions-item label="预算">
          {{ projectData.project.budget }} {{ projectData.project.currency }}
        </el-descriptions-item>
        <el-descriptions-item label="优先级">
          {{ projectData.project.priority }}
        </el-descriptions-item>
      </el-descriptions>

      <el-row :gutter="20" class="mt-4">
        <el-col :span="6">
          <el-statistic
            title="里程碑数量"
            :value="projectData.milestones.length"
          />
        </el-col>
        <el-col :span="6">
          <el-statistic title="任务数量" :value="projectData.tasks.length" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="成员数量" :value="projectData.members.length" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="风险数量" :value="projectData.risks.length" />
        </el-col>
      </el-row>
    </div>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="currentStep > 0" @click="handlePrev">
          上一步
        </el-button>
        <el-button
          v-if="currentStep < WizardStep.Confirm"
          type="primary"
          @click="handleNext"
        >
          下一步
        </el-button>
        <el-button
          v-if="currentStep === WizardStep.Confirm"
          type="primary"
          :loading="saving"
          @click="handleConfirm"
        >
          确认创建
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.upload-step {
  padding: 20px;

  .upload-area {
    :deep(.el-upload) {
      width: 100%;
    }

    :deep(.el-upload-dragger) {
      width: 100%;
      height: 200px;
    }
  }
}

.preview-step {
  .project-form {
    padding-right: 10px;
  }

  .sub-form-item {
    padding: 10px;
    margin-bottom: 10px;
    background: var(--el-fill-color-light);
    border-radius: 4px;
  }
}

.confirm-step {
  padding: 20px;
}

.task-list-container {
  padding: 12px 16px;
  background: var(--el-fill-color-lighter);
  border-radius: 8px;

  .task-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .task-item {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    padding: 10px 12px;
    background: white;
    border-left: 3px solid var(--el-color-info);
    border-radius: 6px;

    &.task-processing {
      background: var(--el-color-warning-light-9);
      border-left-color: var(--el-color-warning);
    }

    &.task-completed {
      border-left-color: var(--el-color-success);
    }

    &.task-failed {
      background: var(--el-color-danger-light-9);
      border-left-color: var(--el-color-danger);
    }

    .task-info {
      display: flex;
      flex: 1;
      gap: 10px;
      align-items: center;
      min-width: 0;
    }

    .task-filename {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      font-size: 13px;
      white-space: nowrap;
    }

    .task-progress {
      display: flex;
      align-items: center;
      width: 120px;
      margin-left: auto;
    }

    .task-actions {
      margin-left: auto;
    }

    .task-error {
      width: 100%;
      margin-top: 4px;
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}
</style>
