<template>
  <el-dialog
    :visible.sync="dialogVisible"
    title="任务详情"
    width="80%"
    top="5vh"
    :close-on-click-modal="false"
    :before-close="handleClose"
    class="task-info-dialog"
  >
    <div class="task-info-container">
      <!-- 标签页容器 -->
      <el-tabs
        v-model="activeTab"
        type="border-card"
        @tab-click="handleTabClick"
      >
        <!-- 立项信息 -->
        <el-tab-pane label="立项信息" name="projectInfo">
          <div v-loading="loading" element-loading-text="加载中...">
            <el-form
              :model="formData.basicInfo"
              label-width="180px"
              disabled
              class="readonly-form"
            >
              <el-form-item label="成本监审项目名称：">
                <el-input
                  v-model="formData.basicInfo.projectName"
                  style="width: 400px"
                ></el-input>
              </el-form-item>
              <el-form-item label="关联成本监审目录：">
                <CatalogCascader
                  ref="catalogCascader"
                  :key="formData.basicInfo.catalogId"
                  :form-item="{ placeholder: '请选择监审目录' }"
                  style="width: 100%"
                  :value="formData.basicInfo.catalogId"
                  :disabled="isViewMode"
                  @change="handleCatalogChange"
                />
              </el-form-item>
              <el-form-item label="监审地区：">
                <RegionSelector
                  :key="formData.basicInfo.areaCode"
                  :initial-area-code="formData.basicInfo.areaCode"
                  :disabled="isViewMode"
                  @region-change="handleRegionChange"
                ></RegionSelector>
              </el-form-item>
              <el-form-item label="被监审单位：">
                <el-select
                  v-if="
                    formData.basicInfo.auditUnitId &&
                    formData.basicInfo.auditUnitId.length > 0
                  "
                  v-model="formData.basicInfo.auditUnitId"
                  placeholder="请选择单位"
                  clearable
                  multiple
                  style="width: 100%"
                  :disabled="isViewMode"
                >
                  <el-option
                    v-for="unit in unitList"
                    :key="unit.unitId"
                    :label="unit.unitName"
                    :value="unit.unitId"
                  />
                </el-select>
                <el-input
                  v-else
                  v-model="formData.basicInfo.auditUnitName"
                  placeholder="请输入单位"
                  style="width: 100%"
                  :disabled="isViewMode"
                ></el-input>
              </el-form-item>
              <el-form-item label="监审主体：">
                <el-select
                  v-model="formData.basicInfo.orgId"
                  placeholder="请选择监审主体"
                  style="width: 100%"
                  clearable
                  :disabled="isViewMode"
                >
                  <el-option
                    v-for="Org in OrgList"
                    :key="Org.id"
                    :label="Org.name"
                    :value="Org.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="归属年度：">
                <el-date-picker
                  v-model="formData.basicInfo.projectYear"
                  style="width: 100%"
                  type="year"
                  placeholder="请选择归属年度"
                  format="yyyy"
                  value-format="yyyy"
                  clearable
                  :disabled="isViewMode"
                ></el-date-picker>
              </el-form-item>
              <el-form-item label="立项来源：">
                <el-select
                  v-model="formData.basicInfo.sourceType"
                  placeholder="请选择立项类型"
                  style="width: 100%"
                  :disabled="isViewMode"
                >
                  <el-option
                    v-for="item in dictData['projectProposal']"
                    :key="item.key"
                    :label="item.name"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="监审形式：">
                <el-select
                  v-model="formData.basicInfo.auditType"
                  placeholder="请选择监审形式"
                  style="width: 100%"
                  :disabled="isViewMode"
                >
                  <el-option
                    v-for="item in dictData['auditType']"
                    :key="item.key"
                    :label="item.name"
                    :value="item.key"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="监审期间：">
                <div class="cost-period-container">
                  <!-- <el-button
                    type="primary"
                    size="small"
                    class="add-cost-year-btn"
                    :disabled="isViewMode || true"
                    @click="addCostYear"
                  >
                    +
                  </el-button> -->
                  <div class="cost-years-wrapper">
                    <div
                      v-for="(year, index) in formData.basicInfo
                        .auditPeriodArray"
                      :key="index"
                      class="cost-year-item"
                    >
                      <el-date-picker
                        v-model="year.value"
                        style="width: 82%; margin-bottom: 5px"
                        type="year"
                        placeholder="请选择年份"
                        format="yyyy"
                        value-format="yyyy"
                        clearable
                        :disabled="isViewMode"
                      ></el-date-picker>
                      <!-- <el-button
                        type="danger"
                        size="small"
                        class="delete-cost-year-btn"
                        :disabled="isViewMode"
                        @click="deleteCostYear(index)"
                      >
                        删除
                      </el-button> -->
                    </div>
                  </div>
                </div>
              </el-form-item>
              <el-form-item label="是否参加听证：">
                <el-radio-group v-model="formData.basicInfo.needHearing">
                  <el-radio :label="0">是</el-radio>
                  <el-radio :label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="是否应急项目：">
                <el-radio-group v-model="formData.basicInfo.isEmergency">
                  <el-radio :label="0">是</el-radio>
                  <el-radio :label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="立项理由：">
                <el-input
                  v-model="formData.basicInfo.establishmentReason"
                  style="width: 100%"
                  type="textarea"
                  rows="4"
                ></el-input>
              </el-form-item>
              <el-form-item label="监审任务负责人：">
                <el-select
                  v-model="formData.basicInfo.projectMembers"
                  placeholder="请选择负责人"
                  style="width: 100%"
                  :disabled="isViewMode"
                >
                  <el-option
                    v-for="(item, index) in userList"
                    :key="index"
                    :label="item.fullname"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="监审任务组成员：">
                <el-select
                  v-model="formData.basicInfo.leaderId"
                  placeholder="请选择成员"
                  multiple
                  style="width: 100%"
                  :disabled="isViewMode"
                >
                  <el-option
                    v-for="(item, index) in userList"
                    :key="index"
                    :label="item.fullname"
                    :value="item.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="其他专家：">
                <el-input
                  v-model="formData.basicInfo.expertStr"
                  style="width: 100%"
                ></el-input>
              </el-form-item>
              <el-form-item label="预定的监审工作起止时间：">
                <el-date-picker
                  v-model="formData.basicInfo.plannedAuditStartDate"
                  type="date"
                  placeholder="开始日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 150px"
                  :disabled="isViewMode"
                ></el-date-picker>
                <span style="margin: 0 10px">—</span>
                <el-date-picker
                  v-model="formData.basicInfo.plannedAuditEndDate"
                  type="date"
                  placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  style="width: 150px"
                  :disabled="isViewMode"
                ></el-date-picker>
              </el-form-item>
            </el-form>
          </div>
        </el-tab-pane>

        <!-- 监审文书 -->
        <el-tab-pane label="监审文书" name="auditDocument">
          <div v-loading="loading" element-loading-text="加载中...">
            <div style="font-size: 14px; margin-bottom: 15px; color: #606266">
              <strong>说明：</strong>
              被监审单位接收《送达回证》后需签名并反馈监审主体。
            </div>
            <el-table
              style="width: 100%"
              border
              :data="formData.auditDocument"
              size="small"
            >
              <el-table-column prop="id" label="序号" width="80" align="center">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="name"
                label="文书类型"
                min-width="150"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="province"
                label="文书文号"
                min-width="200"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="city"
                label="推送时间"
                min-width="180"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="address"
                label="文书状态"
                min-width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.address || '-' }}</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 报送资料 -->
        <el-tab-pane
          v-if="currentNode === 'clcs' || currentNode === 'tjcl'"
          label="报送资料"
          name="dataRequirements"
        >
          <div v-loading="loading" element-loading-text="加载中...">
            <el-table
              border
              :data="groupedDataRequirements"
              size="small"
              :show-header="true"
              :row-class-name="getRowClassName"
            >
              <el-table-column
                prop="seq"
                label="序号"
                width="80"
                align="center"
              >
                <template slot-scope="scope">
                  <span v-if="!scope.row.isCategoryHeader">
                    {{ scope.row.seq || scope.row.index }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="informationName"
                label="报送资料"
                min-width="280"
              >
                <template slot-scope="scope">
                  <div
                    v-if="scope.row.isCategoryHeader"
                    class="category-header-cell"
                  >
                    {{ scope.row.categoryName }}
                  </div>
                  <span v-else>{{ scope.row.informationName || '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="formatRequired"
                label="资料类型"
                width="130"
                align="center"
              >
                <template slot-scope="scope">
                  <span
                    v-if="
                      scope.row.formatRequired !== null &&
                      scope.row.formatRequired !== undefined
                    "
                  >
                    {{
                      getDictName(
                        'formatAsk',
                        String(scope.row.formatRequired)
                      ) || scope.row.formatRequired
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="isRequired"
                label="是否必填"
                width="110"
                align="center"
              >
                <template slot-scope="scope">
                  <span v-if="!scope.row.isCategoryHeader">
                    {{ scope.row.isRequired === '1' ? '是' : '否' }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="isUpload"
                label="是否上传"
                width="110"
                align="center"
              >
                <template slot-scope="scope">
                  <span v-if="!scope.row.isCategoryHeader">
                    <span
                      v-if="
                        scope.row.isUpload === 1 || scope.row.isUpload === '1'
                      "
                      style="color: #67c23a"
                    >
                      已上传
                    </span>
                    <span v-else style="color: #f56c6c">未上传</span>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="isRequired"
                label="审核状态"
                width="110"
                align="center"
              >
                <template slot-scope="scope">
                  <span v-if="!scope.row.isCategoryHeader">
                    <span
                      v-if="
                        scope.row.auditedStatus !== null &&
                        scope.row.auditedStatus !== undefined
                      "
                    >
                      {{
                        getDictName(
                          'clshzt',
                          String(scope.row.auditedStatus)
                        ) || scope.row.auditedStatus
                      }}
                    </span>
                    <span v-else>-</span>
                  </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="operation"
                label="操作"
                width="220"
                align="center"
              >
                <template slot-scope="scope">
                  <template v-if="!scope.row.isCategoryHeader">
                    <template v-if="scope.row.formatRequired !== '3'">
                      <el-button
                        v-if="
                          scope.row.isUpload === 1 || scope.row.isUpload === '1'
                        "
                        type="text"
                        size="small"
                        @click="$emit('handleFileView', scope.row)"
                      >
                        查看
                      </el-button>
                      <el-button
                        v-if="
                          scope.row.isUpload === 1 || scope.row.isUpload === '1'
                        "
                        type="text"
                        size="small"
                        @click="$emit('handleFileDownload', scope.row)"
                      >
                        下载
                      </el-button>
                      <!-- <el-button
                v-if="scope.row.isUpload === 0 || scope.row.isUpload === '0'"
                type="text"
                size="small"
                :disabled="isViewMode"
                @click="$emit('handleFileUpload', scope.row)"
              >
                上传
              </el-button> -->
                    </template>
                    <template v-if="scope.row.formatRequired == '3'">
                      <el-button
                        v-if="
                          scope.row.isUpload === 1 || scope.row.isUpload === '1'
                        "
                        type="text"
                        size="small"
                        @click="$emit('handleTemplateDownload', scope.row)"
                      >
                        模版下载
                      </el-button>
                      <!-- <el-button
                v-if="scope.row.isUpload === 0 || scope.row.isUpload === '0'"
                type="text"
                size="small"
                :disabled="isViewMode"
                @click="$emit('handleDataUpload', scope.row)"
              >
                数据上传
              </el-button> -->
                    </template>
                  </template>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 成本调查表 -->
        <el-tab-pane
          v-if="currentNode === 'clcs' || currentNode === 'tjcl'"
          label="成本调查表"
          name="costSurvey"
        >
          <div v-loading="loading" element-loading-text="加载中...">
            <el-table
              style="width: 100%"
              :data="paginatedCostSurveyData"
              border
              size="small"
            >
              <el-table-column
                prop="index"
                label="序号"
                width="60"
                align="center"
              ></el-table-column>
              <el-table-column label="成本调查表" min-width="220">
                <template slot-scope="scope">
                  <span>{{ scope.row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column
                prop="dataType"
                label="资料类型"
                width="120"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="tableType"
                label="表格类型"
                width="120"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="isRequired"
                label="是否必填"
                width="100"
                align="center"
              ></el-table-column>
              <el-table-column label="是否上传" width="100" align="center">
                <template slot-scope="scope">
                  <span
                    :style="{
                      color:
                        scope.row.isUpload === true ? '#67c23a' : '#f56c6c',
                    }"
                  >
                    {{ scope.row.isUpload === true ? '已上传' : '未上传' }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              background
              layout="total, sizes, prev, pager, next"
              :current-page="costSurveyPagination.currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="costSurveyPagination.pageSize"
              :total="costSurveyPagination.total"
              style="margin-top: 20px; text-align: right"
              @current-change="handleCostSurveyPageChange"
              @size-change="handleCostSurveySizeChange"
            />
          </div>
        </el-tab-pane>

        <!-- 监审意见 -->
        <el-tab-pane
          v-if="currentNode === 'yjfk'"
          label="监审意见"
          name="auditOpinion"
        >
          <div v-loading="loading" element-loading-text="加载中...">
            <div class="cost-supervision-container">
              <div class="cost-opinion-section">
                <h3>成本监审意见</h3>
                <div class="opinion-item">
                  <label>被监审单位基本情况及主要财务状况</label>
                  <el-input
                    v-model="formData.auditOpinion.basicFinancialInfo"
                    type="textarea"
                    rows="5"
                    disabled
                  />
                </div>
                <div class="opinion-item">
                  <label>监审项目现行执行的价格标准</label>
                  <el-input
                    v-model="formData.auditOpinion.priceStandard"
                    type="textarea"
                    rows="5"
                    disabled
                  />
                </div>
                <div class="opinion-item">
                  <label>
                    监审项目的成本构成、数据核增核减情况、依据及理由
                  </label>
                  <el-input
                    v-model="formData.auditOpinion.costComposition"
                    type="textarea"
                    rows="5"
                    disabled
                  />
                </div>
                <div class="opinion-item">
                  <label>成本审核初步意见</label>
                  <el-input
                    v-model="formData.auditOpinion.preliminaryOpinion"
                    type="textarea"
                    rows="5"
                    disabled
                  />
                </div>
              </div>

              <div class="feedback-section">
                <h3>被监审单位反馈意见</h3>
                <div class="feedback-item">
                  <label>被监审单位反馈意见</label>
                  <el-input
                    v-model="formData.auditOpinion.enterpriseFeedback"
                    type="textarea"
                    rows="5"
                    disabled
                  />
                </div>
                <div class="feedback-item">
                  <label>被监审单位反馈资料</label>
                  <div class="file-list-display">
                    <div
                      v-for="(file, index) in formData.auditOpinion.fileList"
                      :key="index"
                      class="file-item"
                    >
                      <i class="el-icon-document"></i>
                      <span>{{ file.name }}</span>
                    </div>
                    <div
                      v-if="
                        !formData.auditOpinion.fileList ||
                        formData.auditOpinion.fileList.length === 0
                      "
                      style="color: #909399"
                    >
                      暂无文件
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 消息通知 -->
        <el-tab-pane label="消息通知" name="messageNotice">
          <div v-loading="loading" element-loading-text="加载中...">
            <el-table
              style="width: 100%"
              border
              :data="formData.messageNotice"
              size="small"
            >
              <el-table-column prop="id" label="序号" width="80" align="center">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column
                prop="noticeTitle"
                label="消息主题"
                width="200"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="noticeSource"
                label="消息来源"
                width="150"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="noticeContent"
                label="消息内容"
                min-width="350"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="createTime"
                label="发送时间"
                width="180"
                align="center"
              ></el-table-column>
            </el-table>
            <el-pagination
              background
              layout="total, sizes, prev, pager, next"
              :current-page="messageNoticePagination.currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="messageNoticePagination.pageSize"
              :total="messageNoticePagination.total"
              style="margin-top: 20px; text-align: right"
              @current-change="handleMessageNoticePageChange"
              @size-change="handleMessageNoticeSizeChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleClose">关闭</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import RegionSelector from '@/views/costAudit/projectInfo/auditProjectManage/annualReviewPlan/RegionSelector.vue'
  import CatalogCascader from '@/views/costAudit/projectInfo/auditProjectManage/annualReviewPlan/CatalogCascader.vue'
  import { getAllUnitList } from '@/api/auditEntityManage'
  import { getDefaultDem, getOrgListByDemId } from '@/api/annualReviewPlan'
  import { getAllUserList } from '@/api/uc'
  import { dictMixin } from '@/mixins/useDict'
  import {
    getProjectInformationInfo,
    getTaskRequirementList,
    sendMessage,
  } from '@/api/auditTaskProcessing'

  export default {
    name: 'TaskInfo',
    components: {
      RegionSelector,
      CatalogCascader,
    },
    mixins: [dictMixin],
    props: {
      visible: {
        type: Boolean,
        default: false,
      },
      taskData: {
        type: Object,
        default: () => ({}),
      },
    },
    data() {
      return {
        dialogVisible: false,
        activeTab: 'projectInfo',
        isViewMode: true, // 只读模式，始终为true
        currentTaskInfo: null, // 当前任务信息（包含projectId和taskId）
        loading: false, // 数据加载状态
        // 各个标签页的加载状态，避免重复加载
        tabLoadedStatus: {
          projectInfo: false,
          auditDocument: false,
          dataRequirements: false,
          costSurvey: false,
          auditOpinion: false,
          messageNotice: false,
        },
        // 成本调查表分页相关
        costSurveyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 消息通知分页相关
        messageNoticePagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        unitList: [],
        OrgList: [],
        userList: [],
        dictData: {
          projectProposal: [], // 立项来源
          auditType: [], // 监审形式
          attributionYear: [], // 归属年度
          materialType: [], // 资料类别
          materialCategory: [], // 资料类别
          formatAsk: [], // 资料类型
          clshzt: [], // 是否通过
        },
        formData: {
          basicInfo: {
            projectName: '',
            catalogId: '',
            areaCode: '',
            auditUnitId: [],
            auditUnitName: '',
            orgId: '',
            orgName: '',
            projectYear: '',
            sourceType: '',
            sourceTypeText: '',
            auditType: '',
            auditTypeText: '',
            auditPeriod: '',
            auditPeriodArray: [{ value: '' }],
            needHearing: 1,
            isEmergency: 1,
            establishmentReason: '',
            projectMembers: '',
            auditGroupName: '',
            leaderId: [],
            auditTeamMembersText: '',
            expertStr: '',
            plannedAuditStartDate: '',
            plannedAuditEndDate: '',
          },
          auditDocument: [],
          dataRequirements: [],
          costSurveyData: [],
          auditOpinion: {
            basicFinancialInfo: '',
            priceStandard: '',
            costComposition: '',
            preliminaryOpinion: '',
            enterpriseFeedback: '',
            fileList: [],
          },
          messageNotice: [],
        },
        showAuditOpinion: true,
        currentNode: '',
      }
    },
    computed: {
      groupedDataRequirements() {
        if (
          !this.formData.dataRequirements ||
          !Array.isArray(this.formData.dataRequirements) ||
          this.formData.dataRequirements.length === 0
        ) {
          return []
        }

        const groups = {}
        this.formData.dataRequirements.forEach((item, index) => {
          const categoryKey = item.informationType || 'other'
          let categoryName = item.informationTypeName || categoryKey

          if (!groups[categoryKey]) {
            groups[categoryKey] = {
              categoryKey,
              categoryName: categoryName,
              items: [],
            }
          }

          const itemWithSeq = {
            ...item,
            index: index + 1,
            seq: groups[categoryKey].items.length + 1,
          }
          groups[categoryKey].items.push(itemWithSeq)
        })

        const result = []
        Object.keys(groups).forEach((categoryKey) => {
          const group = groups[categoryKey]
          result.push({
            isCategoryHeader: true,
            categoryName: group.categoryName,
            categoryKey: group.categoryKey,
          })
          group.items.forEach((item) => {
            result.push({
              ...item,
              isCategoryHeader: false,
            })
          })
        })

        return result
      },
      // 分页后的成本调查表数据
      paginatedCostSurveyData() {
        const start =
          (this.costSurveyPagination.currentPage - 1) *
          this.costSurveyPagination.pageSize
        const end = start + this.costSurveyPagination.pageSize
        return this.formData.costSurveyData.slice(start, end)
      },
    },
    watch: {
      visible: {
        handler(val) {
          this.dialogVisible = val
          if (val) {
            this.loadData()
          }
        },
        immediate: true,
      },
    },
    mounted() {
      this.initData()
    },
    methods: {
      // 初始化数据
      initData() {
        this.getAllUnitList()
        this.getDefaultDem()
        this.getUser()
      },
      // 获取所有单位列表
      getAllUnitList() {
        getAllUnitList()
          .then((res) => {
            this.unitList = res.value || []
          })
          .catch(() => {})
      },
      // 获取默认维度
      getDefaultDem() {
        getDefaultDem()
          .then((res) => {
            if (res && res.code === 200) {
              const demId = res.value ? res.value.id : null
              if (demId) {
                this.getOrgListByDemId(demId)
              }
            }
          })
          .catch(() => {})
      },
      // 根据维度ID获取组织列表
      getOrgListByDemId(demId) {
        getOrgListByDemId({ demId })
          .then((res) => {
            if (res && res.code === 200) {
              this.OrgList = res.value || []
            }
          })
          .catch(() => {})
      },
      // 获取用户列表
      getUser() {
        getAllUserList()
          .then((res) => {
            this.userList = res.value || []
          })
          .catch(() => {})
      },
      // 对外暴露的打开方法
      open(data) {
        this.dialogVisible = true
        this.activeTab = 'projectInfo'

        // 重置加载状态
        Object.keys(this.tabLoadedStatus).forEach((key) => {
          this.tabLoadedStatus[key] = false
        })

        // 重置分页状态
        this.costSurveyPagination.currentPage = 1
        this.costSurveyPagination.total = 0
        this.messageNoticePagination.currentPage = 1
        this.messageNoticePagination.total = 0

        if (data) {
          // 保存任务信息
          this.currentTaskInfo = {
            projectId: data.projectId || data.id,
            taskId: data.userTask?.id || data.taskId,
            currentNode: data.currentNode,
            ...data,
          }

          // 根据状态决定是否显示监审意见标签页
          // this.showAuditOpinion = data.currentNode !== 'jtsy'
          this.currentNode = data.currentNode

          // 立即加载立项信息
          this.loadProjectInfo()
        }
      },
      // 标签页切换事件
      handleTabClick(tab) {
        const tabName = tab.name

        // 如果该tab还未加载过数据，则加载
        if (!this.tabLoadedStatus[tabName]) {
          this.loadTabData(tabName)
        }
      },
      // 根据tab名称加载对应的数据
      async loadTabData(tabName) {
        switch (tabName) {
          case 'projectInfo':
            await this.loadProjectInfo()
            break
          case 'auditDocument':
            await this.loadAuditDocument()
            break
          case 'dataRequirements':
            await this.loadDataRequirements()
            break
          case 'costSurvey':
            await this.loadCostSurvey()
            break
          case 'auditOpinion':
            await this.loadAuditOpinion()
            break
          case 'messageNotice':
            await this.loadMessageNotice()
            break
        }
      },
      // 加载立项信息
      async loadProjectInfo() {
        if (!this.currentTaskInfo?.projectId) {
          return
        }

        try {
          this.loading = true
          const res = await getProjectInformationInfo(
            this.currentTaskInfo.projectId
          )

          if (res && res.code === 200 && res.value) {
            const data = res.value

            // 处理监审期间数组
            let auditPeriodArray = [{ value: '' }]
            if (data.auditPeriod && typeof data.auditPeriod === 'string') {
              const periods = data.auditPeriod.split(',').filter(Boolean)
              auditPeriodArray = periods.map((p) => ({ value: p }))
            }

            // 处理被监审单位ID（可能是字符串或数组）
            let auditUnitId = []
            if (data.auditUnitId) {
              if (typeof data.auditUnitId === 'string') {
                // 如果是字符串，分割成数组
                auditUnitId = data.auditUnitId.split(',').filter(Boolean)
              } else if (Array.isArray(data.auditUnitId)) {
                // 如果已经是数组，直接使用
                auditUnitId = data.auditUnitId
              }
            }

            // 处理监审任务组成员（可能是字符串或数组）
            let leaderId = []
            if (data.leaderId) {
              if (typeof data.leaderId === 'string') {
                leaderId = data.leaderId.split(',').filter(Boolean)
              } else if (Array.isArray(data.leaderId)) {
                leaderId = data.leaderId
              }
            }

            this.formData.basicInfo = {
              projectName: data.projectName || '',
              catalogId: data.catalogId || '',
              areaCode: data.areaCode || '',
              auditUnitId: auditUnitId,
              auditUnitName: data.auditUnitName || '',
              orgId: data.orgId || '',
              orgName: data.orgName || '',
              projectYear: data.projectYear || '',
              sourceType: data.sourceType || '',
              auditType: data.auditType || '',
              auditPeriod: data.auditPeriod || '',
              auditPeriodArray: auditPeriodArray,
              needHearing:
                data.needHearing !== undefined ? data.needHearing : 1,
              isEmergency:
                data.isEmergency !== undefined ? data.isEmergency : 1,
              establishmentReason: data.establishmentReason || '',
              projectMembers: data.projectMembers || '',
              leaderId: leaderId,
              expertStr: data.expertStr || '',
              plannedAuditStartDate: data.plannedAuditStartDate || '',
              plannedAuditEndDate: data.plannedAuditEndDate || '',
            }

            // 打印日志以便调试
            console.log('立项信息加载完成:', {
              areaCode: this.formData.basicInfo.areaCode,
              auditUnitId: this.formData.basicInfo.auditUnitId,
              auditUnitName: this.formData.basicInfo.auditUnitName,
            })

            this.tabLoadedStatus.projectInfo = true
          }
        } catch (error) {
          console.error('加载立项信息失败:', error)
          this.$message.error('加载立项信息失败')
        } finally {
          this.loading = false
        }
      },
      // 加载监审文书
      async loadAuditDocument() {
        try {
          this.loading = true
          // TODO: 调用监审文书接口
          // const res = await getAuditDocumentList(this.currentTaskInfo.taskId)
          // if (res && res.code === 200) {
          //   this.formData.auditDocument = res.value || []
          // }

          // 暂时使用mock数据
          this.formData.auditDocument = []
          this.tabLoadedStatus.auditDocument = true
        } catch (error) {
          console.error('加载监审文书失败:', error)
          this.$message.error('加载监审文书失败')
        } finally {
          this.loading = false
        }
      },
      // 加载报送资料
      async loadDataRequirements() {
        if (!this.currentTaskInfo?.taskId) {
          return
        }

        try {
          this.loading = true
          const res = await getTaskRequirementList(this.currentTaskInfo.taskId)

          if (res && res.code === 200) {
            this.formData.dataRequirements = Array.isArray(res.value)
              ? res.value
              : []
            this.tabLoadedStatus.dataRequirements = true
          }
        } catch (error) {
          console.error('加载报送资料失败:', error)
          this.$message.error('加载报送资料失败')
        } finally {
          this.loading = false
        }
      },
      // 加载成本调查表
      async loadCostSurvey() {
        try {
          this.loading = true
          // TODO: 调用成本调查表接口
          // const res = await getCostSurveyList(this.currentTaskInfo.taskId)
          // if (res && res.code === 200) {
          //   this.formData.costSurveyData = res.value || []
          //   this.costSurveyPagination.total = this.formData.costSurveyData.length
          // }

          // 暂时使用mock数据
          this.formData.costSurveyData = []
          this.costSurveyPagination.total = this.formData.costSurveyData.length
          this.tabLoadedStatus.costSurvey = true
        } catch (error) {
          console.error('加载成本调查表失败:', error)
          this.$message.error('加载成本调查表失败')
          this.formData.costSurveyData = []
          this.costSurveyPagination.total = 0
        } finally {
          this.loading = false
        }
      },
      // 加载监审意见
      async loadAuditOpinion() {
        try {
          this.loading = true
          // TODO: 调用监审意见接口
          // const res = await getAuditOpinion(this.currentTaskInfo.taskId)
          // if (res && res.code === 200) {
          //   this.formData.auditOpinion = res.value || {}
          // }

          // 暂时使用默认数据
          this.tabLoadedStatus.auditOpinion = true
        } catch (error) {
          console.error('加载监审意见失败:', error)
          this.$message.error('加载监审意见失败')
        } finally {
          this.loading = false
        }
      },
      // 加载消息通知
      async loadMessageNotice() {
        if (!this.currentTaskInfo?.taskId) {
          return
        }

        try {
          this.loading = true
          const params = {
            taskId: this.currentTaskInfo.taskId,
            auditedUnitId: this.currentTaskInfo.auditedUnitId,
            projectId: this.currentTaskInfo.projectId,
            pageNum: this.messageNoticePagination.currentPage,
            pageSize: this.messageNoticePagination.pageSize,
          }
          const res = await sendMessage(params)

          console.log('消息通知接口返回:', res)
          if (res && res.code === 200 && res.value) {
            this.formData.messageNotice = res.value.records || []
            this.messageNoticePagination.total = res.value.total || 0
          } else {
            this.formData.messageNotice = []
            this.messageNoticePagination.total = 0
          }
          this.tabLoadedStatus.messageNotice = true
        } catch (error) {
          console.error('加载消息通知失败:', error)
          this.$message.error('加载消息通知失败')
          this.formData.messageNotice = []
          this.messageNoticePagination.total = 0
        } finally {
          this.loading = false
        }
      },
      loadData() {
        if (this.taskData && Object.keys(this.taskData).length > 0) {
          // 加载传入的数据
          this.formData = { ...this.formData, ...this.taskData }

          // 处理监审期间数组
          if (
            this.formData.basicInfo.auditPeriod &&
            typeof this.formData.basicInfo.auditPeriod === 'string'
          ) {
            const periods = this.formData.basicInfo.auditPeriod
              .split(',')
              .filter(Boolean)
            this.formData.basicInfo.auditPeriodArray = periods.map((p) => ({
              value: p,
            }))
          }
        }
      },
      handleClose() {
        this.dialogVisible = false
        this.$emit('update:visible', false)
        this.$emit('close')
      },
      getRowClassName({ row }) {
        if (row.isCategoryHeader) {
          return 'category-header-row'
        }
        return ''
      },
      // 处理监审目录变化（只读模式下不触发）
      handleCatalogChange(value) {
        // 只读模式，无需处理
      },
      // 处理地区变化（只读模式下不触发）
      handleRegionChange(region) {
        // 只读模式，无需处理
      },
      // 添加监审年份（只读模式下禁用）
      addCostYear() {
        // 只读模式，无需处理
      },
      // 删除监审年份（只读模式下禁用）
      deleteCostYear(index) {
        // 只读模式，无需处理
      },

      // 成本调查表分页 - 页码改变
      handleCostSurveyPageChange(page) {
        this.costSurveyPagination.currentPage = page
        // 如果成本调查表数据来自API，可以在这里调用API
        // this.loadCostSurvey()
      },

      // 成本调查表分页 - 每页条数改变
      handleCostSurveySizeChange(size) {
        this.costSurveyPagination.pageSize = size
        this.costSurveyPagination.currentPage = 1
        // 如果成本调查表数据来自API，可以在这里调用API
        // this.loadCostSurvey()
      },

      // 消息通知分页 - 页码改变
      handleMessageNoticePageChange(page) {
        this.messageNoticePagination.currentPage = page
        this.loadMessageNotice()
      },

      // 消息通知分页 - 每页条数改变
      handleMessageNoticeSizeChange(size) {
        this.messageNoticePagination.pageSize = size
        this.messageNoticePagination.currentPage = 1
        this.loadMessageNotice()
      },
    },
  }
</script>

<style scoped lang="scss">
  .task-info-dialog {
    ::v-deep .el-dialog__body {
      padding: 20px;
      max-height: 70vh;
      overflow-y: auto;
    }
  }

  .task-info-container {
    width: 100%;
  }

  .readonly-form {
    ::v-deep .el-input.is-disabled .el-input__inner {
      color: #606266;
      background-color: #f5f7fa;
    }

    ::v-deep .el-textarea.is-disabled .el-textarea__inner {
      color: #606266;
      background-color: #f5f7fa;
    }

    ::v-deep .el-radio__input.is-disabled + span.el-radio__label {
      color: #606266;
    }
  }

  .cost-period-container {
    display: flex;
    align-items: flex-start;
  }

  .add-cost-year-btn {
    margin-right: 10px;
  }

  .delete-cost-year-btn {
    margin-left: 10px;
  }

  .cost-years-wrapper {
    flex: 1;
  }

  .cost-year-item {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
  }

  .cost-supervision-container {
    width: 100%;

    h3 {
      text-align: center;
      margin-top: 0;
      margin-bottom: 20px;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .cost-opinion-section,
  .feedback-section {
    border: 1px solid #dcdcdc;
    border-radius: 4px;
    padding: 20px;
    margin-bottom: 20px;
    background-color: #f9f9f9;
  }

  .opinion-item,
  .feedback-item {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;

    label {
      margin-bottom: 8px;
      font-weight: bold;
      color: #1549ad;
    }
  }

  .file-list-display {
    border: 1px solid #e9e9e9;
    border-radius: 4px;
    padding: 15px;
    min-height: 60px;
    background-color: #fff;
  }

  .file-item {
    padding: 8px;
    margin-bottom: 5px;
    color: #606266;

    i {
      margin-right: 5px;
      color: #409eff;
    }
  }

  ::v-deep .category-header-row {
    background-color: #f5f7fa !important;

    td {
      background-color: #f5f7fa !important;
      padding: 12px 16px !important;
    }
  }

  .category-header-cell {
    font-weight: 700;
    color: #303133;
    padding-left: 16px;
  }

  .dialog-footer {
    text-align: center;
    padding-top: 10px;
  }
</style>
