import { message } from "@/utils/message";
import type { PaginationProps } from "@pureadmin/table";
import type { ProjectItem, ProjectStatistics } from "@/api/project";
import {
  getProjectList,
  getProjectStatistics,
  deleteProject
} from "@/api/project";
import { ref, reactive, onMounted } from "vue";

export function useProject() {
  const form = reactive({
    keyword: "",
    status: ""
  });

  const formRef = ref();
  const dataList = ref<ProjectItem[]>([]);
  const loading = ref(true);
  const statistics = ref<ProjectStatistics>({
    totalCount: 0,
    ongoingCount: 0,
    completedCount: 0,
    pausedCount: 0,
    planningCount: 0,
    cancelledCount: 0,
    draftCount: 0,
    statusCountMap: {},
    newThisMonth: 0,
    aboutToExpireCount: 0,
    averageProgress: 0,
    highRiskCount: 0
  });

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 12,
    currentPage: 1,
    background: true
  });

  // 搜索
  async function onSearch() {
    loading.value = true;
    try {
      const { code, data } = await getProjectList({
        pageNum: pagination.currentPage,
        pageSize: pagination.pageSize,
        keyword: form.keyword || undefined,
        status: form.status || undefined
      });

      if (code === 200 && data) {
        dataList.value = data.rows;
        pagination.total = Number(data.total);
      }
    } catch {
      message("获取项目列表失败", { type: "error" });
    } finally {
      loading.value = false;
    }
  }

  // 获取统计数据
  async function fetchStatistics() {
    try {
      const { code, data } = await getProjectStatistics();
      if (code === 200 && data) {
        statistics.value = data;
      }
    } catch {
      console.error("获取统计数据失败");
    }
  }

  // 重置表单
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    pagination.currentPage = 1;
    onSearch();
  };

  // 分页大小变化
  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  // 页码变化
  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  // 删除项目
  async function handleDelete(row: ProjectItem) {
    try {
      const { code } = await deleteProject(row.id as string);
      if (code === 200) {
        message(`已删除项目 "${row.projectName}"`, { type: "success" });
        onSearch();
        fetchStatistics();
      }
    } catch {
      message("删除项目失败", { type: "error" });
    }
  }

  // 状态筛选按钮
  const statusFilterButtons = [
    { label: "全部项目", value: "" },
    { label: "进行中", value: "ongoing" },
    { label: "已完成", value: "completed" },
    { label: "高风险", value: "high_risk" }
  ];

  // 当前激活的筛选
  const activeFilter = ref("");

  // 设置筛选
  function setFilter(filterValue: string) {
    activeFilter.value = filterValue;
    if (filterValue === "high_risk") {
      form.status = "";
    } else {
      form.status = filterValue;
    }
    pagination.currentPage = 1;
    onSearch();
  }

  onMounted(() => {
    onSearch();
    fetchStatistics();
  });

  return {
    form,
    formRef,
    loading,
    dataList,
    pagination,
    statistics,
    activeFilter,
    statusFilterButtons,
    onSearch,
    resetForm,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    setFilter
  };
}
