<template>
  <div class="completed-supervision-query-container">
    <!-- 查询条件表单 -->
    <div class="search-panel">
      <el-form :model="searchForm" inline>
        <el-form-item label="年度：">
          <el-date-picker
            v-model="searchForm.projectYear"
            type="year"
            placeholder="请选择年度"
            format="yyyy"
            value-format="yyyy"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="监审项目名称：">
          <el-input
            v-model="searchForm.projectName"
            placeholder="请输入项目名称"
            style="width: 300px"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格视图 -->
    <div v-if="activeTab === 'list'">
      <el-table
        v-loading="loading"
        class="mb10"
        :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">
              {{ getParentNodeIndex(scope.row) }}
            </span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          prop="projectName"
          label="成本监审项目名称"
          show-overflow-tooltip
          header-align="center"
          align="left"
        />
        <el-table-column
          prop="auditObject"
          label="监审对象"
          header-align="center"
          align="left"
        />
        <el-table-column
          prop="auditPeriod"
          label="监审期间"
          header-align="center"
          align="center"
          width="120"
        />
        <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="160">
          <template slot-scope="scope">
            <span v-if="!scope.row.isSubTask" class="action-buttons">
              <el-button
                type="text"
                size="small"
                @click="handleViewTaskDetail(scope.row)"
              >
                任务详情
              </el-button>
            </span>
            <span v-if="scope.row.isSubTask" class="action-buttons">
              <el-button
                type="text"
                size="small"
                @click="handleView(scope.row, 'chengben')"
              >
                查看
              </el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        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>

    <!-- 任务详情视图 -->
    <div v-else-if="activeTab === 'detail' && selectedTask" class="task-detail">
      <el-breadcrumb
        separator-class="el-icon-arrow-right"
        style="margin-bottom: 20px"
      >
        <el-breadcrumb-item>
          <a href="javascript:void(0)" @click="backToList">办结监审查询列表</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>任务详情</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- <taskDetail /> -->
    </div>
    <!-- 任务信息弹窗 -->
    <taskInfo ref="taskInfo" />
    <cbjs-info
      :id="cbjsInfoData && cbjsInfoData.id"
      :visible.sync="cbjsInfoVisible"
      :current-node="cbjsInfoData && cbjsInfoData.currentNode"
      :current-status="cbjsInfoData && cbjsInfoData.status"
    />
    <taskDetail ref="taskDetail" />
  </div>
</template>

<script>
  import { getCompletedSupervisionList } from '@/api/audit/reviewTask'
  // import taskDetail from '@/views/costAudit/auditInfo/auditManage/taskDetail.vue'
  import taskInfo from '@/components/task/taskInfo.vue'
  import cbjsInfo from '@/components/task/cbjsInfo.vue'
  import taskDetail from '@/components/task/taskDetail.vue'
  export default {
    name: 'CompletedSupervisionQuery',
    components: {
      taskDetail,
      taskInfo,
      cbjsInfo,
    },
    data() {
      return {
        // 搜索条件
        searchForm: {
          projectYear: '2025',
          projectName: '',
        },
        // 表格数据
        tableData: [],
        // 分页配置
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 加载状态
        loading: false,
        // 当前视图
        activeTab: 'list',
        // 选中的任务
        selectedTask: null,
        // 是否显示任务详情
        showTaskDetail: false,
        // cbjsInfo弹窗相关
        cbjsInfoVisible: false,
        cbjsInfoData: null,
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      // 获取父节点的连续序号
      getParentNodeIndex(row) {
        // 过滤出所有父节点
        const parentNodes = this.tableData.filter(
          (item) => item.children && item.children.length > 0
        )
        // 找到当前行在父节点数组中的索引
        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,
          }
          const response = await getCompletedSupervisionList(params)

          // 根据API返回格式处理数据
          if (response.state && response.value) {
            // 获取记录列表
            const records = response.value.records || []
            // 转换数据格式，将childTasks转换为children以适应表格组件
            this.tableData = records.map((record) => {
              return {
                id: record.id,
                projectName: record.projectName,
                auditObject: record.auditedUnitName,
                auditPeriod: record.auditPeriod,
                source: this.getSourceTypeText(record.sourceType),
                form: this.getAuditTypeText(record.auditType),
                isSubTask: record.pid !== '0',
                projectId: record.projectId,
                auditedUnitId: record.auditedUnitId,
                taskId: record.id,
                children: record.childTasks
                  ? record.childTasks.map((child) => ({
                      id: child.id,
                      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
            this.$message.warning('未获取到数据')
          }
        } 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
      },
      backToList() {
        this.activeTab = 'list'
      },

      // 处理查询
      handleQuery() {
        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()
      },

      // 查看任务（打开taskInfo弹窗）
      handleView(row, type) {
        if (type === 'chengben') {
          this.cbjsInfoData = row
          this.cbjsInfoVisible = true
        } else {
          this.$refs.taskInfo.open(row, type)
        }
      },

      // 查看任务详情
      handleViewTaskDetail(row) {
        // this.selectedTask = row
        // this.activeTab = 'detail'
        // this.showTaskDetail = true
        this.$refs.taskDetail.open(row, 'chengben')
      },

      // 切换视图
      switchView(view) {
        this.activeTab = view
      },
    },
  }
</script>

<style scoped>
  .completed-supervision-query-container {
    padding: 20px;
  }

  .header {
    margin-bottom: 20px;
  }

  .header h2 {
    margin: 0;
    color: #303133;
  }

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

  .view-switch {
    margin-bottom: 20px;
  }

  .task-detail {
    background-color: #fff;
    border-radius: 4px;
    padding: 20px;
  }

  .detail-header {
    margin-bottom: 20px;
  }

  .detail-header h3 {
    margin: 10px 0 0 0;
    color: #303133;
  }

  .subtasks {
    margin-top: 30px;
  }

  .subtasks h4 {
    margin: 0 0 15px 0;
    color: #303133;
  }
</style>
