<template>
  <div class="app-container dpc-project-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">初核项目管理</h2>
      <el-button v-hasPermi="['ccdi:project:add']" type="primary" icon="el-icon-plus" @click="handleAdd">新建项目</el-button>
    </div>

    <!-- 搜索和操作区 -->
    <search-bar
      :show-search="showSearch"
      :tab-counts="tabCounts"
      :show-deleted-tab="isProjectAdmin"
      @query="handleQuery"
    />

    <!-- 项目列表表格 -->
    <project-table
      :loading="loading"
      :data-list="projectList"
      :total="total"
      :page-params="queryParams"
      :deleted-list="queryParams.includeDeleted === true"
      @pagination="handlePagination"
      @open="handleOpenProject"
      @archive="handleArchive"
      @delete="handleDelete"
      @restore="handleRestore"
    />

    <!-- 快捷入口区 -->
    <quick-entry
      v-hasPermi="['ccdi:project:add']"
      @import-history="handleImport"
      @create-quarterly="handleCreateQuarterly"
      @create-employee="handleCreateEmployee"
      @create-highrisk="handleCreateHighRisk"
    />

    <!-- 新建项目弹窗 -->
    <add-project-dialog
      :visible.sync="addDialogVisible"
      :title="addDialogTitle"
      :form="projectForm"
      @submit="handleSubmitProject"
      @close="handleCloseAddDialog"
    />

    <!-- 导入历史项目弹窗 -->
    <import-history-dialog
      :visible.sync="importDialogVisible"
      @submit="handleSubmitImport"
      @close="handleCloseImportDialog"
    />

    <!-- 项目归档确认弹窗 -->
    <archive-confirm-dialog
      :visible.sync="archiveDialogVisible"
      :project-data="currentArchiveProject"
      @confirm="handleConfirmArchive"
      @close="archiveDialogVisible = false"
    />
  </div>
</template>

<script>
import {archiveProject, delProject, getStatusCounts, listProject} from '@/api/ccdiProject'
import { restoreProject } from '@/api/ccdiProject'
import SearchBar from './components/SearchBar'
import ProjectTable from './components/ProjectTable'
import QuickEntry from './components/QuickEntry'
import AddProjectDialog from './components/AddProjectDialog'
import ImportHistoryDialog from './components/ImportHistoryDialog'
import ArchiveConfirmDialog from './components/ArchiveConfirmDialog'

export default {
  name: "DpcProject",
  components: {
    SearchBar,
    ProjectTable,
    QuickEntry,
    AddProjectDialog,
    ImportHistoryDialog,
    ArchiveConfirmDialog,
  },
  data() {
    return {
      // 加载状态
      loading: true,
      // 显示搜索栏
      showSearch: true,
      // 总条数
      total: 0,
      // 项目列表
      projectList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectName: null,
        status: null,
        includeDeleted: false
      },
      // 标签页数量统计
      tabCounts: {
        all: 0,
        '0': 0,
        '1': 0,
        '2': 0,
        '3': 0,
        '4': 0,
        '5': 0
      },
      // 新增/编辑弹窗
      addDialogVisible: false,
      addDialogTitle: "新建项目",
      projectForm: {},
      // 导入历史项目弹窗
      importDialogVisible: false,
      // 归档确认弹窗
      archiveDialogVisible: false,
      currentArchiveProject: null,
    };
  },
  created() {
    this.getList();
  },
  computed: {
    isProjectAdmin() {
      const roles = this.$store && this.$store.getters ? this.$store.getters.roles || [] : []
      return roles.includes("admin") || roles.includes("manager")
    }
  },
  methods: {
    /** 查询项目列表 */
    getList() {
      this.loading = true

      // 并行请求列表数据和状态统计
      Promise.all([
        listProject(this.queryParams),
        getStatusCounts()
      ]).then(([listResponse, countsResponse]) => {
        // 处理列表数据
        this.projectList = listResponse.rows
        this.total = listResponse.total

        // 处理状态统计
        const counts = countsResponse.data || {}
        this.tabCounts = {
          all: counts.all || 0,
          '0': counts.status0 || 0,
          '1': counts.status1 || 0,
          '2': counts.status2 || 0,
          '3': counts.status3 || 0,
          '4': counts.status4 || 0,
          '5': counts.status5 || 0
        }

        this.loading = false
      }).catch((error) => {
        this.loading = false
        console.error('加载数据失败:', error)
        this.$modal.msgError('加载数据失败，请稍后重试')
      })
    },
    /** 搜索按钮操作 */
    handleQuery(queryParams) {
      const nextQueryParams = { ...this.queryParams }
      if (queryParams) {
        Object.assign(nextQueryParams, queryParams)
      }
      if (nextQueryParams.includeDeleted && !this.isProjectAdmin) {
        nextQueryParams.includeDeleted = false
        nextQueryParams.status = null
      }
      if (nextQueryParams.includeDeleted) {
        nextQueryParams.status = null
      } else {
        nextQueryParams.includeDeleted = false
      }
      nextQueryParams.pageNum = 1
      this.queryParams = nextQueryParams
      this.getList();
    },
    /** 分页事件处理 */
    handlePagination(pagination) {
      if (pagination) {
        this.queryParams.pageNum = pagination.pageNum
        this.queryParams.pageSize = pagination.pageSize
      }
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.projectForm = this.getEmptyForm();
      this.addDialogTitle = "新建项目";
      this.addDialogVisible = true;
    },
    /** 获取空表单 */
    getEmptyForm() {
      return {
        projectId: null,
        projectName: "",
        description: "",
        configType: "default",
      };
    },
    getProjectTemplate(type) {
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth() + 1;
      const quarter = Math.floor(now.getMonth() / 3) + 1;
      const quarterNames = ["一", "二", "三", "四"];
      const templates = {
        quarterly: {
          projectName: `${year}年第${quarterNames[quarter - 1]}季度纪检初核项目`,
          description: `用于开展${year}年第${quarterNames[quarter - 1]}季度纪检初核排查工作。`,
          configType: "default",
        },
        employee: {
          projectName: `${year}年${month}月新员工排查项目`,
          description: `用于开展${year}年${month}月新入职员工排查工作。`,
          configType: "default",
        },
        highRisk: {
          projectName: `${year}年高风险专项排查项目`,
          description: `用于开展${year}年高风险人员和异常线索专项排查工作。`,
          configType: "custom",
        },
      };
      return {
        ...this.getEmptyForm(),
        ...templates[type],
      };
    },
    /** 关闭新增弹窗 */
    handleCloseAddDialog() {
      this.addDialogVisible = false;
      this.projectForm = {};
    },
    /** 提交项目表单 */
    handleSubmitProject(data) {
      // 不需要再次调用API，因为AddProjectDialog已经处理了
      this.addDialogVisible = false
      if (!data || !data.projectId) {
        this.$modal.msgError("项目创建成功后未返回项目ID，无法进入上传数据页面")
        this.getList()
        return
      }
      this.$router.push({
        path: `/ccdiProject/detail/${data.projectId}`,
        query: { tab: "upload" },
      })
    },
    /** 导入历史项目 */
    handleImport() {
      this.importDialogVisible = true;
    },
    /** 关闭导入弹窗 */
    handleCloseImportDialog() {
      this.importDialogVisible = false;
    },
    /** 提交导入 */
    handleSubmitImport(project) {
      this.$modal.msgSuccess("历史项目导入任务已开始");
      this.importDialogVisible = false;
      this.getList();
      this.$router.push({
        path: `/ccdiProject/detail/${project.projectId}`,
      });
    },
    /** 创建季度初核 */
    handleCreateQuarterly() {
      this.projectForm = this.getProjectTemplate("quarterly");
      this.addDialogTitle = "创建季度初核项目";
      this.addDialogVisible = true;
    },
    /** 创建新员工排查 */
    handleCreateEmployee() {
      this.projectForm = this.getProjectTemplate("employee");
      this.addDialogTitle = "创建新员工排查项目";
      this.addDialogVisible = true;
    },
    /** 创建高风险专项 */
    handleCreateHighRisk() {
      this.projectForm = this.getProjectTemplate("highRisk");
      this.addDialogTitle = "创建高风险专项项目";
      this.addDialogVisible = true;
    },
    /** 打开项目 */
    handleOpenProject(row) {
      if (this.queryParams.includeDeleted) {
        return
      }
      this.$router.push({
        path: `/ccdiProject/detail/${row.projectId}`,
        query: { tab: this.resolveProjectEntryTab(row) },
      });
    },
    resolveProjectEntryTab(row) {
      const status = row && row.status !== undefined ? String(row.status) : ""
      if (row && row.canOperate === false) {
        return "overview"
      }
      return ["1", "2"].includes(status) ? "overview" : "upload"
    },
    /** 归档项目 */
    handleArchive(row) {
      if (!this.canOperate(row)) {
        this.$modal.msgWarning("当前项目仅可查看，不能归档")
        return
      }
      this.currentArchiveProject = row;
      this.archiveDialogVisible = true;
    },
    /** 确认归档 */
    async handleConfirmArchive(data) {
      try {
        await archiveProject(data.projectId)
        this.$modal.msgSuccess("项目归档成功")
        this.archiveDialogVisible = false
        this.currentArchiveProject = null
        this.getList()
      } catch (error) {
        const message = error && error.message ? error.message : "项目归档失败，请稍后重试"
        this.$modal.msgError(message)
      }
    },
    /** 删除项目 */
    async handleDelete(row) {
      if (!this.canDelete(row)) {
        this.$modal.msgWarning("当前项目不能删除")
        return
      }
      try {
        await this.$modal.confirm(
          `确认删除项目“${row.projectName}”吗？删除后项目进入已删除列表，项目内数据不会删除。`
        )
      } catch (confirmError) {
        if (confirmError === "cancel" || confirmError === "close") {
          return
        }
        throw confirmError
      }
      try {
        await delProject(row.projectId)
        this.$modal.msgSuccess("项目删除成功")
        this.getList()
      } catch (error) {
        const message = error && error.message ? error.message : "项目删除失败，请稍后重试"
        this.$modal.msgError(message)
      }
    },
    /** 恢复已删除项目 */
    async handleRestore(row) {
      if (!this.isProjectAdmin) {
        this.$modal.msgWarning("当前用户不能恢复项目")
        return
      }
      try {
        await this.$modal.confirm(`确认恢复项目“${row.projectName}”吗？项目将恢复为已完成状态。`)
      } catch (confirmError) {
        if (confirmError === "cancel" || confirmError === "close") {
          return
        }
        throw confirmError
      }
      try {
        await restoreProject(row.projectId)
        this.$modal.msgSuccess("项目恢复成功")
        this.getList()
      } catch (error) {
        const message = error && error.message ? error.message : "项目恢复失败，请稍后重试"
        this.$modal.msgError(message)
      }
    },
    canOperate(row) {
      return !row || row.canOperate !== false
    },
    canDelete(row) {
      return !row || row.canDelete !== false
    },
  },
};
</script>

<style lang="scss" scoped>
.dpc-project-container {
  padding: 24px;
  background: var(--ccdi-page-bg);
  min-height: calc(100vh - 84px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  .page-title {
    margin: 0;
    font-size: 20px;
    font-weight: 700;
    color: var(--ccdi-text-primary);
  }
}
</style>
