<template>
  <div class="comprehensive-query">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="项目名称：">
          <el-input
            v-model="searchForm.projectName"
            placeholder="请输入项目名称"
            style="width: 200px"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="监审期间：">
          <el-date-picker
            v-model="searchForm.startYear"
            type="year"
            placeholder="选择开始年份"
            style="width: 150px"
            clearable
            format="yyyy年"
            value-format="yyyy"
          ></el-date-picker>
          <span style="margin: 0 5px">~</span>
          <el-date-picker
            v-model="searchForm.endYear"
            type="year"
            placeholder="选择结束年份"
            style="width: 150px"
            clearable
            format="yyyy年"
            value-format="yyyy"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="被监审单位：">
          <!-- <el-input
            v-model="searchForm.auditedUnitName"
            placeholder="请输入被监审单位"
            style="width: 200px"
            clearable
          ></el-input> -->
          <el-select
            v-model="searchForm.auditedUnitId"
            placeholder="请选择被监审单位"
            style="width: 200px"
            clearable
            filterable
            allow-create
            default-first-option
          >
            <el-option
              v-for="item in auditedUnitOptions"
              :key="item.unitId"
              :label="item.unitName"
              :value="item.unitId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="立项年度：">
          <el-date-picker
            v-model="searchForm.year"
            type="year"
            placeholder="选择立项年度"
            style="width: 150px"
            clearable
            format="yyyy年"
            value-format="yyyy"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">
            查询
          </el-button>
          <el-button
            icon="el-icon-refresh"
            style="margin-left: 10px"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table
        v-loading="loading"
        :data="auditProjectList"
        :border="true"
        :stripe="false"
        :span-method="handleSpanMethod"
        :row-style="rowStyle"
        :row-class-name="'no-stripe-row'"
      >
        <!-- 序号列 -->
        <el-table-column
          prop="index"
          label="序号"
          width="80"
          header-align="center"
          align="center"
        >
          <template slot-scope="scope">
            {{ getParentNodeIndex(scope.row, scope.$index) }}
          </template>
        </el-table-column>

        <!-- 立项年度 -->
        <el-table-column
          prop="year"
          label="立项年度"
          width="100"
          header-align="center"
          align="center"
        ></el-table-column>

        <!-- 监审地区 -->
        <el-table-column
          prop="areaName"
          label="监审地区"
          width="100"
          header-align="center"
          align="center"
        ></el-table-column>

        <!-- 成本监审项目名称 -->
        <el-table-column
          prop="projectName"
          label="成本监审项目名称"
          align="left"
          header-align="center"
        >
          <template slot-scope="scope">
            <a
              href="javascript:;"
              class="link-text"
              @click="handleViewTaskDetail(scope.row)"
            >
              {{ scope.row.projectName }}
            </a>
          </template>
        </el-table-column>

        <!-- 监审对象 -->
        <el-table-column
          prop="auditObject"
          label="监审对象"
          header-align="center"
        ></el-table-column>

        <!-- 监审期间 -->
        <el-table-column
          prop="auditPeriod"
          label="监审期间"
          width="200"
          header-align="center"
          align="center"
        ></el-table-column>

        <!-- 监审形式 -->
        <el-table-column
          prop="auditTypeName"
          label="监审形式"
          width="120"
          header-align="center"
          align="center"
        >
          <!-- <template slot-scope="scope">
            {{ getDictName('auditType', scope.row.auditType) }}
          </template> -->
        </el-table-column>

        <!-- 监审主体 -->
        <el-table-column
          prop="orgName"
          label="监审主体"
          align="left"
          header-align="center"
        ></el-table-column>

        <!-- 下载 -->
        <el-table-column
          label="下载"
          width="200"
          align="center"
          header-align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleMessage(scope.row, 'chengben')"
            >
              监审任务
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleDownloadFile(scope.row)"
            >
              监审卷宗
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="pagination.pageSizes"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 成本监审任务制定弹窗（用于“主任务”查看） -->
    <task-customized-release-dialog
      :visible.sync="taskReleaseDialogVisible"
      :project="project"
      :is-view="true"
      @backToList="taskReleaseDialogVisible = false"
      @close="taskReleaseDialogVisible = false"
    />
    <!-- 成本监审信息弹窗（用于“子任务”按钮） -->
    <cbjs-info
      :id="cbjsInfoData && cbjsInfoData.id"
      :selected-project="cbjsInfoData"
      :visible.sync="cbjsInfoVisible"
      :current-node="cbjsInfoData && cbjsInfoData.currentNode"
      :current-status="cbjsInfoData && cbjsInfoData.status"
    />
  </div>
</template>

<script>
  import { getReviewTaskList } from '@/api/audit/auditIndex'
  // import { dictMixin } from '@/mixins/useDict'
  import TaskCustomizedReleaseDialog from '@/components/task/TaskCustomizedReleaseDialog.vue'
  import cbjsInfo from './components/cbjsInfo.vue'
  import { getCostProjectDetail } from '@/api/taskCustomizedRelease.js'
  import { getAllUnitList } from '@/api/auditEntityManage.js'
  export default {
    name: 'ComprehensiveQuery',
    components: {
      TaskCustomizedReleaseDialog,
      cbjsInfo,
    },
    // mixins: [dictMixin],
    data() {
      return {
        dictData: {
          auditType: [], // 监审形式
        },
        // 搜索表单数据
        searchForm: {
          projectName: '',
          startYear: '',
          endYear: '',
          auditedUnitId: '',
          year: '',
        },
        // 表格数据
        auditProjectList: [],
        // 行合并映射表（当前页）
        rowSpanMap: {},
        // 分页配置
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          pageSizes: [10, 20, 50],
        },
        // 任务详情弹窗相关
        taskReleaseDialogVisible: false,
        project: {},
        isView: true,
        // 成本监审信息弹窗相关
        cbjsInfoVisible: false,
        cbjsInfoData: null,
        loading: false,
        auditedUnitOptions: [],
      }
    },
    mounted() {
      this.getOptions()
      this.handleQuery()
    },
    methods: {
      getOptions() {
        getAllUnitList()
          .then((res) => {
            if (res && res.value) {
              this.auditedUnitOptions = res.value
            }
          })
          .catch((e) => {
            console.warn('获取单位列表失败', e)
          })
      },
      // 加载项目列表（优化分页数据处理）
      async handleQuery() {
        try {
          this.loading = true
          const params = {
            pageNum: this.pagination.currentPage,
            pageSize: this.pagination.pageSize,
            isGd: 1,
            type: 1,
            ...this.searchForm,
          }
          const response = await getReviewTaskList(params)

          if (response.state && response.value) {
            const records = response.value.records || []
            this.auditProjectList = []
            this.rowSpanMap = {} // 重置为当前页的合并映射

            records.forEach((record) => {
              // 处理父项（保留用于当前页合并计算，会被隐藏）
              const parentRow = {
                ...record,
                // 合并列：这些列会被合并显示
                year: record.year, // 立项年度
                areaName: record.areaName, // 监审地区
                projectName: record.projectName, // 成本监审项目名称
                // 非合并列（父行会被隐藏，这些值不会显示）
                auditObject: record.auditedUnitName || record.auditObject || '',
                auditPeriod: record.auditPeriod || record.auditPeriodName || '',
                auditType: record.auditType || record.auditTypeName || '',
                orgName: record.orgName || record.orgFullName || '',
                status: this.getStatusText(record.status),
                isSubTask: record.pid !== '0',
                isParent: true,
                hasChildren:
                  !!record.childTasks && record.childTasks.length > 0,
              }
              this.auditProjectList.push(parentRow)

              // 处理子项（仅当前页内的子行）
              if (record.childTasks && record.childTasks.length > 0) {
                // 记录当前页父项的合并行数（父行+子行）
                this.rowSpanMap[record.id] = record.childTasks.length + 1

                record.childTasks.forEach((child) => {
                  this.auditProjectList.push({
                    ...child,
                    // 合并列：这些列会被合并显示，使用父项的值
                    year: child.year || record.year, // 立项年度
                    areaName: child.areaName || record.areaName, // 监审地区
                    projectName: record.projectName, // 继承父项项目名称
                    // 非合并列：每行独立显示，使用子项自己的值
                    auditObject: child.auditedUnitName || '', // 监审对象（子项自己的被监审单位）
                    auditPeriod: child.auditPeriod || record.auditPeriod || '', // 监审期间
                    auditType: child.auditType || record.auditType || '', // 监审形式
                    auditTypeName: record.auditTypeName || '', // 监审形式名称
                    orgName:
                      child.orgName ||
                      child.orgFullName ||
                      record.orgName ||
                      record.orgFullName ||
                      '', // 监审主体
                    status: this.getStatusText(child.status),
                    isSubTask: true,
                    parentId: record.id,
                    isParent: false,
                  })
                })
              }
            })

            // 使用接口返回的总条数（而非当前页长度）
            this.pagination.total = response.value.total || 0
          } else {
            this.auditProjectList = []
            this.rowSpanMap = {}
            this.pagination.total = 0
            this.$message.warning('未获取到项目数据')
          }
        } catch (error) {
          console.error('加载审核项目列表失败:', error)
          this.auditProjectList = []
          this.rowSpanMap = {}
          this.pagination.total = 0
        } finally {
          this.loading = false
        }
      },

      // 获取状态文本
      getStatusText(status) {
        const statusMap = {
          ccls: '资料初审',
          200: '审核通过',
          clcs: '审核中',
        }
        return statusMap[status] || status
      },

      // 处理重置
      handleReset() {
        this.searchForm = {
          projectName: '',
          startYear: '',
          endYear: '',
          auditedUnitName: '',
          year: '',
        }
        this.pagination.currentPage = 1 // 重置页码
        this.handleQuery()
      },

      // 处理分页大小变化
      handleSizeChange(size) {
        this.pagination.pageSize = size
        this.pagination.currentPage = 1 // 页码重置为1
        this.handleQuery() // 重新加载当前页数据
      },

      // 处理页码变化
      handleCurrentChange(current) {
        this.pagination.currentPage = current
        this.handleQuery() // 重新加载当前页数据
      },

      // 处理分页变化（兼容旧接口）
      handlePaginationChange(pagination) {
        this.pagination = { ...this.pagination, ...pagination }
        this.handleQuery() // 重新加载当前页数据
      },

      // 处理下载监审卷宗
      handleDownloadFile(row) {
        console.log('下载监审卷宗:', row)
        this.$message.success('监审卷宗功能待实现')
      },

      // 查看任务详情
      handleViewTaskDetail(row) {
        this.openTaskReleaseDialog(row)
      },

      // 打开成本监审任务制定弹窗（只读查看）
      openTaskReleaseDialog(row) {
        if (!row) return
        const projectId = row.projectId || row.id || ''
        if (!projectId) {
          this.$message.warning('缺少项目ID，无法查看详情')
          return
        }
        this.project = row
        this.isView = true
        this.taskReleaseDialogVisible = true
        // getCostProjectDetail({ id: projectId })
        //   .then((res) => {
        //     this.project = (res && res.value) || {}
        //     this.taskReleaseDialogVisible = true
        //   })
        //   .catch(() => {
        //     this.project = row || {}
        //     this.taskReleaseDialogVisible = true
        //   })
      },

      // 查看成本监审信息
      handleMessage(row, type) {
        if (type === 'chengben') {
          this.cbjsInfoData = row
          this.cbjsInfoData.taskId = row.id || {}
          this.cbjsInfoVisible = true
        }
      },

      // 生成连续序号（基于当前页可见行）
      getParentNodeIndex(row, index) {
        // 过滤当前页可见行（排除父行）
        const visibleRows = this.auditProjectList.filter(
          (item) => !item.isParent
        )
        // 查找当前行在可见行中的索引
        const visibleIndex = visibleRows.findIndex((item) => item.id === row.id)
        return visibleIndex !== -1 ? visibleIndex + 1 : index + 1
      },

      // 隐藏父行样式
      rowStyle({ row }) {
        if (row.isParent) {
          return {
            display: 'none',
            height: '0px !important',
            padding: '0px !important',
            border: 'none !important',
          }
        }
        return {}
      },

      // 处理合并单元格逻辑（基于当前页数据）
      handleSpanMethod({ row, column, rowIndex }) {
        const mergeColumns = ['year', 'areaName', 'projectName']
        const columnProp = column && column.property

        // 父行：所有列都隐藏（通过 rowStyle 已经隐藏，这里确保不显示）
        if (row.isParent) {
          return { rowspan: 0, colspan: 0 }
        }

        // 非合并列：不合并，正常显示
        if (!mergeColumns.includes(columnProp)) {
          return { rowspan: 1, colspan: 1 }
        }

        // 合并列：只处理子行的合并逻辑
        if (!row.parentId) {
          // 没有父行的行（无子项的父项），不合并
          return { rowspan: 1, colspan: 1 }
        }

        // 在当前页数据中查找父行
        const parentRow = this.auditProjectList.find(
          (item) => item.id === row.parentId
        )
        // 父行不在当前页时不合并
        if (!parentRow) {
          return { rowspan: 1, colspan: 1 }
        }

        const spanCount = this.rowSpanMap[parentRow.id] || 1
        // 判断是否是当前页父行的第一个子行
        if (this.isFirstChildInCurrentPage(parentRow.id, rowIndex)) {
          // 合并行数 = 子行数量（因为父行被隐藏了）
          const childCount = spanCount - 1
          return { rowspan: childCount, colspan: 1 }
        } else {
          // 其他子行的合并列隐藏
          return { rowspan: 0, colspan: 0 }
        }
      },

      // 判断是否是当前页父行的第一个子行
      isFirstChildInCurrentPage(parentId, currentIndex) {
        // 在当前页数据中查找父行索引
        const parentIndex = this.auditProjectList.findIndex(
          (item) => item.id === parentId
        )
        // 父行不在当前页或索引错误时返回false
        if (parentIndex === -1) return false
        // 第一个子行索引 = 父行索引 + 1（当前页内有效）
        return currentIndex === parentIndex + 1
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/styles/costAudit.scss';

  .comprehensive-query {
    padding: 20px;
  }

  // 表格区域样式
  .table-area {
    margin-top: 20px;
  }

  // 分页组件样式
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
  }

  // 覆盖斑马纹样式
  ::v-deep .no-stripe-row {
    background-color: #ffffff !important;
  }

  ::v-deep .el-table__body tr {
    background-color: #ffffff !important;
  }

  // 确保合并单元格边框正常
  ::v-deep .el-table__cell {
    border-right: 1px solid #ebeef5 !important;
  }

  ::v-deep .el-table__header th {
    border-right: 1px solid #ebeef5 !important;
  }
</style>
