<template>
  <div class="archive-list">
    <div v-if="activeTab == 'list'">
      <!-- 搜索表单 -->
      <div class="search-panel">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="年度:" prop="projectYear">
            <el-date-picker
              v-model="searchForm.projectYear"
              type="year"
              placeholder="选择年"
              format="yyyy"
              value-format="yyyy"
            ></el-date-picker>
          </el-form-item>

          <el-form-item label="监审项目名称:">
            <el-input
              v-model="searchForm.projectName"
              placeholder="请输入监审项目名称"
              clearable
              style="width: 200px"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button plain type="primary" @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
        border
        default-expand-all
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            <!-- 只显示父节点的序号 -->
            <span v-if="scope.row.children || !scope.row.isSubTask">
              {{ getParentNodeIndex(scope.row) }}
            </span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          prop="year"
          label="立项年度"
          width="100"
          header-align="center"
          align="center"
        />
        <el-table-column
          prop="projectName"
          label="成本监审项目名称"
          show-overflow-tooltip
          header-align="center"
          align="left"
        >
          <template slot-scope="scope">
            <div class="cell-content cell-content--left">
              <span class="project-link" @click="handleDetail(scope.row)">
                {{ scope.row.projectName }}
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="auditObject"
          label="监审对象"
          header-align="center"
          align="left"
        />
        <el-table-column
          prop="auditPeriod"
          label="监审期间"
          header-align="center"
          align="center"
          width="200"
        />
        <el-table-column
          prop="source"
          label="立项来源"
          header-align="center"
          align="center"
          width="120"
        />
        <el-table-column
          prop="form"
          label="监审形式"
          header-align="center"
          align="center"
          width="120"
        />
        <el-table-column label="操作" align="center" width="200" fixed="right">
          <template slot-scope="scope">
            <span class="action-buttons">
              <el-button
                type="text"
                size="small"
                @click="handleTaskDetail(scope.row)"
              >
                任务详情
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="handleView(scope.row)"
              >
                查看
              </el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 10px"
        background
        layout="total, sizes, prev, pager, next"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 任务详情弹窗 -->
    <taskDetail ref="taskDetail" />
  </div>
</template>

<script>
  import taskDetail from '@/components/task/taskDetail.vue'
  import { getArchiveList } from '@/api/audit/archive'
  export default {
    name: 'ArchiveList',
    components: {
      taskDetail,
    },
    data() {
      return {
        searchForm: {
          projectYear: '2025',
          projectName: '',
        },
        loading: false,
        tableData: [],
        // 分页配置
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        activeTab: 'list',
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      // 获取父节点的连续序号
      getParentNodeIndex(row) {
        // 过滤出所有父节点
        const parentNodes = this.tableData.filter(
          (item) =>
            (item.children && item.children.length > 0) || !item.isSubTask
        )
        // 找到当前行在父节点数组中的索引
        const index = parentNodes.findIndex((item) => item.id === row.id)
        // 返回序号（索引+1）
        return index + 1
      },
      // 获取数据
      async fetchData() {
        try {
          this.loading = true
          const params = {
            currentPage: this.pagination.currentPage,
            pageSize: this.pagination.pageSize,
            projectYear: this.searchForm.projectYear,
            projectName: this.searchForm.projectName,
            isGd: 1, // 已归档
          }
          const response = await getArchiveList(params)

          // 根据API返回格式处理数据
          if (response && response.value) {
            // 获取记录列表
            const records = response.value.records || []
            // 转换数据格式，将childTasks转换为children以适应表格组件
            this.tableData = records.map((record) => {
              return {
                id: record.id,
                year: record.projectYear || record.year || '',
                projectName: record.projectName,
                auditObject: record.auditedUnitName || record.auditObject || '',
                auditPeriod: record.auditPeriod || '',
                source: this.getSourceTypeText(record.sourceType),
                form: this.getAuditTypeText(record.auditType),
                isSubTask: record.pid && record.pid !== '0',
                projectId: record.projectId,
                auditedUnitId: record.auditedUnitId,
                taskId: record.id,
                children: record.childTasks
                  ? record.childTasks.map((child) => ({
                      id: child.id,
                      year: '',
                      projectName: child.projectName,
                      auditObject: child.auditedUnitName || '',
                      auditPeriod: record.auditPeriod || '', // 子任务可能使用父任务的审核期间
                      source: '',
                      form: '',
                      isSubTask: true,
                      projectId: child.projectId,
                      auditedUnitId: child.auditedUnitId,
                      taskId: child.id,
                    }))
                  : [],
              }
            })
            // 设置总数
            this.pagination.total = response.value.total || 0
          } else {
            this.tableData = []
            this.pagination.total = 0
          }
        } catch (error) {
          // this.$message.error('加载列表失败')
          console.error('加载列表失败:', error)
          this.tableData = []
          this.pagination.total = 0
        } finally {
          this.loading = false
        }
      },
      // 获取来源类型文本
      getSourceTypeText(type) {
        const typeMap = {
          1: '年度计划内',
          2: '年度计划外',
        }
        return typeMap[type] || type || ''
      },
      // 获取审核类型文本
      getAuditTypeText(type) {
        const typeMap = {
          1: '定期监审',
          2: '定调价监审',
        }
        return typeMap[type] || type || ''
      },
      handleSearch() {
        this.pagination.currentPage = 1
        this.fetchData()
      },
      handleReset() {
        this.searchForm = {
          projectYear: '2025',
          projectName: '',
        }
        this.pagination.currentPage = 1
        this.fetchData()
      },
      // 处理分页变化
      handleCurrentChange(current) {
        this.pagination.currentPage = current
        this.fetchData()
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.pagination.currentPage = 1
        this.fetchData()
      },
      handleDetail(row) {
        // 可以在这里处理详情点击
        console.log('详情:', row)
      },
      handleTaskDetail(row) {
        // 打开任务详情弹窗
        this.$refs.taskDetail.open(row, 'chengben')
      },
      handleView(row) {
        // 查看操作，可以打开查看弹窗或跳转
        console.log('查看:', row)
        this.$message.info('查看功能待实现')
      },
      backToList() {
        this.activeTab = 'list'
      },
    },
  }
</script>

<style scoped lang="scss">
  .archive-list {
    padding: 20px;
  }

  .search-panel {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .action-buttons {
    display: inline-flex;
    gap: 8px;
  }

  .action-link {
    color: #409eff;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s;

    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }

  .project-link {
    color: #409eff;
    cursor: pointer;
    text-decoration: none;
    transition: color 0.3s;

    &:hover {
      color: #66b1ff;
      text-decoration: underline;
    }
  }
</style>
