<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">
      <!-- 报送资料预置模版查看弹窗：复用 SurveyFormDialog / FixedTableDialog / DynamicTableDialog，只读模式 -->
      <survey-form-dialog
        :visible.sync="surveyFormDialogVisible"
        :survey-data="{ ...(currentTemplateRow || {}), ...surveyDetailData }"
        :form-fields="formFields"
        :is-view-mode="true"
        :audited-unit-id="auditedUnitId"
        :request-type="viewContext === 'costSurvey' ? 1 : 2"
        :upload-id="
          (currentTemplateRow &&
            (currentTemplateRow.uploadId || currentTemplateRow.id)) ||
          ''
        "
        :survey-template-id="getSurveyTemplateId(currentTemplateRow)"
        :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
      />

      <fixed-table-dialog
        :visible.sync="fixedTableDialogVisible"
        :survey-data="{ ...(currentTemplateRow || {}), fixedHeaders }"
        :fixed-fields="fixedFields || ''"
        :fixed-fieldids="fixedFieldids || ''"
        :table-items="tableItems"
        :audit-periods="auditPeriods"
        :is-view-mode="true"
        :request-type="viewContext === 'costSurvey' ? 1 : 2"
        :audited-unit-id="auditedUnitId"
        :upload-id="
          (currentTemplateRow &&
            (currentTemplateRow.uploadId || currentTemplateRow.id)) ||
          ''
        "
        :survey-template-id="getSurveyTemplateId(currentTemplateRow)"
        :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
      />

      <dynamic-table-dialog
        :key="dynamicDialogKey"
        :visible.sync="dynamicTableDialogVisible"
        :survey-data="currentTemplateRow || {}"
        :table-data="dynamicTableData"
        :table-items="tableItems"
        :is-view-mode="true"
        :request-type="viewContext === 'costSurvey' ? 1 : 2"
        :audited-unit-id="auditedUnitId"
        :upload-id="
          (currentTemplateRow &&
            (currentTemplateRow.uploadId || currentTemplateRow.id)) ||
          ''
        "
        :survey-template-id="getSurveyTemplateId(currentTemplateRow)"
        :catalog-id="(currentTemplateRow && currentTemplateRow.catalogId) || ''"
      />
      <!-- 标签页容器 -->
      <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.leaderId"
                  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.projectMembers"
                  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="documentName"
                label="文书类型"
                min-width="150"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="documentNumber"
                label="文书文号"
                min-width="200"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="generateTime"
                label="推送时间"
                min-width="180"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="electronicDocumentUrl"
                label="文书操作"
                min-width="120"
                align="center"
              >
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="mini"
                    @click="handleDocView(scope.row)"
                  >
                    查看
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    @click="handleDownloadDocument(scope.row)"
                  >
                    下载
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column
                prop="feedbackDocumentUrl"
                label="向监审主体反馈文件"
                min-width="120"
                align="center"
              >
                <template
                  v-if="scope.row.documentName.includes('送达回证')"
                  slot-scope="scope"
                >
                  <!-- <el-button
                    :disabled="isViewMode"
                    type="text"
                    size="mini"
                    @click="handleUploadScan(scope.row, 'feedbackDocumentUrl')"
                  >
                    上传附件
                  </el-button> -->
                  <!-- <span>
                    {{ scope.row.feedbackDocumentUrl ? '已回传' : '未回传' }}
                  </span> -->
                  <el-button
                    v-if="scope.row.feedbackDocumentUrl"
                    type="text"
                    size="mini"
                    @click="handleViewFeedback(scope.row.feedbackDocumentUrl)"
                  >
                    查看附件
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页 -->
            <el-pagination
              style="margin: 20px 0"
              :current-page.sync="auditDocumentPagination.page"
              :page-sizes="[50, 100]"
              :page-size.sync="auditDocumentPagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="auditDocumentPagination.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 报送资料 -->
        <el-tab-pane 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"
                header-align="center"
                align="left"
              >
                <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="handleFileView(scope.row)"
                      >
                        查看
                      </el-button>
                      <el-button
                        v-if="
                          scope.row.isUpload === 1 || scope.row.isUpload === '1'
                        "
                        type="text"
                        size="small"
                        @click="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="handleViewTemplate(scope.row)"
                      >
                        查看
                      </el-button>
                      <el-button
                        v-if="
                          (scope.row.isUpload === 1 ||
                            scope.row.isUpload === '1') &&
                          scope.row.templateType !== '1'
                        "
                        type="text"
                        size="small"
                        @click="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 label="成本调查表" name="costSurvey">
          <div v-loading="loading" element-loading-text="加载中...">
            <el-table
              style="width: 100%"
              :data="formData.costSurveyData"
              border
              size="small"
            >
              <el-table-column
                prop="index"
                label="序号"
                width="60"
                align="center"
              ></el-table-column>
              <el-table-column
                label="成本调查表"
                min-width="220"
                align="center"
              >
                <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-column label="操作" width="120" align="center">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="handleCostSurveyView(scope.row)"
                  >
                    查看
                  </el-button>
                </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>
    <!-- 查看监审通知书 -->
    <CostAuditDialog
      :title="documentDialogTitle"
      :visible="documentDialogVisible"
      width="82%"
      :close-on-click-modal="false"
      :z-index="9400"
      :show-confirm-btn="false"
      cancel-text="关闭"
      @cancel="handleDocCancel"
    >
      <div class="document-edit-container">
        <!-- 左侧：文书参数设置 -->
        <div class="document-params">
          <h4>文书参数设置：</h4>
          <el-form
            ref="documentForm"
            :model="document"
            label-width="170px"
            size="small"
            disabled
          >
            <el-form-item label="模板：" prop="documentId">
              {{ document.documentName }}
            </el-form-item>
            <el-form-item label="通知书文号：" prop="documentNumber">
              {{ document.documentNumber }}
            </el-form-item>
            <el-form-item label="被监审单位" prop="enterpriseId">
              <div style="display: flex; align-items: center; gap: 15px">
                <el-select
                  v-model="document.enterpriseId"
                  placeholder="请选择被监审单位"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in unitList"
                    :key="item.unitId"
                    :label="item.unitName"
                    :value="item.unitId"
                  ></el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item label="是否推送被监审单位：" prop="isPushed">
              <!-- 是否推送被监审单位 -->
              <el-radio-group v-model="document.isPushed">
                <el-radio label="1">是</el-radio>
                <el-radio label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
            <!-- 数据内容区域 -->
            <div style="margin-top: 20px">
              <h4 style="margin-bottom: 10px">数据内容：</h4>
              <el-table
                :data="costDocumentTemplateFiles"
                style="
                  width: 100%;
                  border: 1px solid #dcdfe6;
                  border-radius: 4px;
                "
              >
                <el-table-column
                  prop="originalText"
                  label="数据项"
                  width="120"
                  align="center"
                  show-overflow-tooltip
                ></el-table-column>
                <!-- <el-table-column
                  prop="labelValue"
                  label="标签"
                  width="100"
                  align="center"
                  show-overflow-tooltip
                ></el-table-column> -->
                <el-table-column
                  prop="originalText"
                  label="描述"
                  min-width="120"
                  align="center"
                  show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                  prop="dataValue"
                  label="数据值"
                  min-width="150"
                  align="center"
                  show-overflow-tooltip
                >
                  <template slot-scope="scope">
                    <el-input
                      v-if="scope.row.originalText !== '需要提供材料'"
                      v-model="scope.row.dataValue"
                      size="small"
                      placeholder="请输入数据值"
                      disabled
                    ></el-input>
                    <!-- 否则显示上传按钮 -->
                    <div v-else>
                      <!-- <el-button
                      type="primary"
                      size="small"
                      @click="handleUploadClick(scope.row)"
                    >
                      上传附件
                    </el-button> -->
                      <el-button
                        v-if="scope.row.dataValue"
                        type="primary"
                        size="small"
                        :disabled="false"
                        @click="handleViewScan(scope.row.dataValue)"
                      >
                        查看附件
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>
        </div>

        <!-- 右侧：模板预览和编辑区 -->
        <div class="document-preview">
          <!-- 预览/修改标签页 -->
          <TemplatePreviewEdit
            :active-tab="activeDocTab"
            :file-url="fileUrl"
            :is-show-edit="false"
          />
        </div>
      </div>
    </CostAuditDialog>
    <!-- 多附件查看弹窗 -->
    <multi-attachment-dialog
      :visible="dialogMultiVisible"
      :attachments="attachments"
      @close="dialogMultiVisible = false"
    ></multi-attachment-dialog>

    <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'
  import { getSurveyList } from '@/api/audit/survey'
  import {
    getCostProjectDocumentPageList,
    updateFeedback,
    downDocument,
  } from '@/api/taskCustomizedRelease.js'
  import { getCostProjectDocumentFile } from '@/api/auditReviewDocManage.js'
  import CostAuditDialog from '@/components/costAudit/CostAuditDialog.vue'
  import TemplatePreviewEdit from '@/components/costAudit/TemplatePreviewEdit.vue'
  import MultiAttachmentDialog from '@/components/costAudit/MultiAttachmentDialog'
  import { uploadFile } from '@/api/file'
  import SurveyFormDialog from '@/views/EntDeclaration/auditTaskManagement/components/SurveyFormDialog.vue'
  import FixedTableDialog from '@/views/EntDeclaration/auditTaskManagement/components/FixedTableDialog.vue'
  import DynamicTableDialog from '@/views/EntDeclaration/auditTaskManagement/components/DynamicTableDialog.vue'
  import {
    getSingleRecordSurveyList,
    getSurveyDetail,
    getDynamicTableData,
    downloadTemplate,
  } from '@/api/audit/survey'
  import { getListBySurveyFdTemplateIdAndVersion } from '@/api/costSurveyTemplateHeaders'
  export default {
    name: 'TaskInfo',
    components: {
      RegionSelector,
      CatalogCascader,
      CostAuditDialog,
      TemplatePreviewEdit,
      MultiAttachmentDialog,
      SurveyFormDialog,
      FixedTableDialog,
      DynamicTableDialog,
    },
    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,
        },
        auditDocumentPagination: {
          page: 1,
          pageSize: 50,
          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: '',
        documentDialogVisible: false,
        documentDialogTitle: '查看监审通知书',
        dialogWidth: '80%',
        fileUrl: '',
        costDocumentTemplateFiles: [],
        document: {},
        activeDocTab: 'preview', // 当前标签页，preview:预览，edit:修改
        dialogMultiVisible: false,
        attachments: [],
        // 报送资料预置模版查看相关
        currentTemplateRow: null,
        surveyFormDialogVisible: false,
        fixedTableDialogVisible: false,
        dynamicTableDialogVisible: false,
        // 视图上下文：'costSurvey' 或 'dataRequirements'
        viewContext: 'dataRequirements',
        formFields: [],
        surveyDetailData: {},
        tableItems: [],
        auditPeriods: [],
        dynamicTableData: [],
        dynamicDialogKey: 0,
        fixedHeaders: null,
        fixedFields: '',
        fixedFieldids: '',
      }
    },
    computed: {
      // 从传入 taskData/formData 中派生 catalogId/auditedUnitId，供成本调查表接口使用
      catalogId() {
        return (
          (this.taskData &&
            (this.taskData.catalogId || this.taskData.catalogid)) ||
          (this.formData &&
            this.formData.basicInfo &&
            (this.formData.basicInfo.catalogId ||
              this.formData.basicInfo.catalogid)) ||
          ''
        )
      },
      auditedUnitId() {
        return (
          (this.taskData &&
            (this.taskData.auditedUnitId || this.taskData.auditedunitid)) ||
          ''
        )
      },
      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()
            // 若默认即在成本调查表页且尚未加载，则加载
            if (
              this.activeTab === 'costSurvey' &&
              !this.tabLoadedStatus.costSurvey
            ) {
              this.loadCostSurvey()
            }
          }
        },
        immediate: true,
      },
    },
    mounted() {
      this.initData()
    },
    methods: {
      // 报送资料-查看（同 taskFillIn）
      handleFileView(row) {
        console.log(row, '这一行数据')
        try {
          const filePath =
            row?.filePath ||
            row?.filepath ||
            row?.fileUrl ||
            row?.url ||
            row?.path ||
            ''
          if (!filePath) {
            this.$message &&
              this.$message.warning &&
              this.$message.warning('未找到可预览的文件路径')
            return
          }
          const encodedUrl = encodeURIComponent(
            Base64.encode((window.context && window.context.form) + filePath)
          )
          window.open(`${host}:8012/onlinePreview?url=${encodedUrl}`)
          // 兼容保留：通知父组件
          this.$emit('handleFileView', row)
        } catch (e) {
          console.error('文件预览失败: ', e)
          // this.$message &&
          //   this.$message.error &&
          //   this.$message.error('文件预览失败')
        }
      },
      // 报送资料-下载（同 taskFillIn）
      handleFileDownload(row) {
        if (!row || !row.fileUrl) {
          this.$message &&
            this.$message.warning &&
            this.$message.warning('该资料暂无文件可下载')
          return
        }
        this.downloadByFetch(row.fileUrl, row.informationName || '下载文件')
      },
      // 模版下载（对齐 CostSurveyTab，兼容两种上下文）
      async handleTemplateDownload(row) {
        try {
          const loading = this.$loading({
            lock: true,
            text: '模板下载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          const surveyTemplateId = this.getSurveyTemplateId(row)
          const versionId =
            (row && (row.versionId || row.version || row.templateVersionId)) ||
            ''
          const params = {
            type: this.viewContext === 'costSurvey' ? 1 : 2,
          }
          if (surveyTemplateId) params.surveyTemplateId = surveyTemplateId
          if (versionId) params.versionId = versionId
          const taskId = (row && (row.taskId || row.taskID)) || this.taskId
          if (taskId) params.taskId = taskId
          const res = await downloadTemplate(params)
          loading.close()
          const headers = (res && res.headers) || {}
          const contentDisposition =
            headers['content-disposition'] || headers['Content-Disposition']
          let fileName =
            this.extractFileNameFromHeader(contentDisposition) ||
            `${row.informationName || row.name || '模板文件'}.xlsx`
          if (!/\.[a-zA-Z0-9]+$/.test(fileName)) fileName += '.xlsx'
          const blobData = (res && res.data) || res
          const blob =
            blobData instanceof Blob ? blobData : new Blob([blobData])
          const url = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.download = fileName
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(url)
          this.$message &&
            this.$message.success &&
            this.$message.success('开始下载文件')
        } catch (error) {
          console.error('模板下载失败:', error)
          this.$message &&
            this.$message.error &&
            this.$message.error(error.message || '模板下载失败，请稍后重试')
        }
      },
      extractFileNameFromHeader(contentDisposition) {
        if (!contentDisposition) return ''
        const match = /filename[^;=\n]*=((['"])?.*?\2|[^;\n]*)/i.exec(
          contentDisposition
        )
        if (match && match[1]) {
          try {
            return decodeURIComponent(match[1].replace(/['"]/g, ''))
          } catch (e) {
            return match[1].replace(/['"]/g, '')
          }
        }
        return ''
      },
      async downloadByFetch(rawUrl, fallbackName) {
        const url = this.normalizeUrl(rawUrl)
        let loading
        try {
          loading = this.$baseLoading
            ? this.$baseLoading(1, '文件下载中...')
            : this.$loading({
                lock: true,
                text: '文件下载中...',
                spinner: 'el-icon-loading',
                background: 'rgba(0,0,0,0.7)',
              })
          const res = await fetch(url, { method: 'GET' })
          if (!res.ok) throw new Error('下载失败')
          const blob = await res.blob()
          let fileName =
            this.extractFileName(res.headers.get('content-disposition')) ||
            fallbackName ||
            '下载文件'
          if (!/\.[a-zA-Z0-9]+$/.test(fileName)) {
            const extFromUrl = (
              url.split('?')[0].split('#')[0].split('.').pop() || ''
            ).toLowerCase()
            fileName = extFromUrl ? `${fileName}.${extFromUrl}` : fileName
          }
          const objectUrl = window.URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = objectUrl
          link.download = fileName
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          window.URL.revokeObjectURL(objectUrl)
          this.$message &&
            this.$message.success &&
            this.$message.success('开始下载文件')
        } catch (e) {
          console.log(e.message || '文件下载失败')
          // this.$message &&
          //   this.$message.error &&
          //   this.$message.error(e.message || '文件下载失败')
        } finally {
          if (loading && loading.close) loading.close()
        }
      },
      normalizeUrl(u) {
        if (!u) return ''
        if (/^https?:\/\//i.test(u)) return u
        const base = (window.context && window.context.form) || ''
        if (!base) return u
        if (u.startsWith('/')) return base + u
        return base.replace(/\/$/, '') + '/' + u
      },
      extractFileName(contentDisposition) {
        if (!contentDisposition) return ''
        const match = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/i.exec(
          contentDisposition
        )
        if (match && match[1]) {
          try {
            return decodeURIComponent(match[1].replace(/['"]/g, ''))
          } catch (e) {
            return match[1].replace(/['"]/g, '')
          }
        }
        return ''
      },
      // 初始化数据
      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, type) {
        console.log('data', data)
        console.log('type', type)
        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: type === 'chengben' ? data.projectId : data.id,
            taskId:
              type === 'chengben'
                ? data.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() {
        console.log(this.currentTaskInfo.projectId)
        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 auditTeamMembers = []
            if (data.projectMembers) {
              if (typeof data.projectMembers === 'string') {
                auditTeamMembers = data.projectMembers
                  .split(',')
                  .filter(Boolean)
              } else if (Array.isArray(data.projectMembers)) {
                auditTeamMembers = data.projectMembers
              }
            }

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

            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 || '',
              projectMembers: auditTeamMembers,
              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 handleOnlineSubmission(row) {
        if (!row) return
        this.currentTemplateRow = row
        this.surveyDetailData = {}

        const t = String(row.templateType || row.templatetype || '').trim()
        if (t === '1') {
          if (row.uploadId || row.id) {
            try {
              const params = {
                uploadId: row.uploadId || row.id,
                auditedUnitId: this.auditedUnitId,
                type: this.viewContext === 'costSurvey' ? 1 : 2,
              }
              const res = await getSurveyDetail(params)
              if (res && res.code === 200 && res.value) {
                const detailData = {}
                if (Array.isArray(res.value)) {
                  res.value.forEach((item) => {
                    if (item.rowid && item.rvalue !== undefined) {
                      detailData[item.rowid] = item.rvalue
                    }
                  })
                } else if (res.value && typeof res.value === 'object') {
                  Object.assign(detailData, res.value)
                }
                this.surveyDetailData = detailData
              }
            } catch (err) {
              console.error('获取单记录详情失败', err)
            }
          }
          await this.initFormFields()
        } else if (t === '2') {
          await this.initFixedTableData()
        } else if (t === '3') {
          await this.initDynamicTableData()
        }
      },
      handleViewTemplate(row) {
        this.currentTemplateRow = row || null
        const t = String(
          (row && (row.templateType || row.templatetype)) || ''
        ).trim()
        if (t === '1' || t === '2' || t === '3') {
          // 报送资料查看
          this.viewContext = 'dataRequirements'
          this.handleOnlineSubmission(row)
        } else {
          this.$message &&
            this.$message.warning &&
            this.$message.warning('未知的模板类型，无法打开预置模板')
        }
      },
      handleCostSurveyView(row) {
        // 成本调查表查看
        this.viewContext = 'costSurvey'
        const templateRow = {
          ...row,
          uploadId: row.id,
          surveyTemplateId: row.surveyTemplateId || row.templateId || '',
          catalogId: row.catalogId || this.catalogId || '',
          auditedUnitId: row.auditedUnitId || this.auditedUnitId || '',
          informationName: row.name,
        }
        this.handleOnlineSubmission(templateRow)
      },
      async initDynamicTableData() {
        try {
          const uploadId =
            (this.currentTemplateRow &&
              (this.currentTemplateRow.uploadId ||
                this.currentTemplateRow.id)) ||
            ''
          const auditedUnitId = this.auditedUnitId || ''
          const catalogId =
            (this.currentTemplateRow && this.currentTemplateRow.catalogId) || ''
          const surveyTemplateId = this.getSurveyTemplateId(
            this.currentTemplateRow
          )

          const params = {
            uploadId,
            auditedUnitId,
            catalogId,
            surveyTemplateId,
            type: this.viewContext === 'costSurvey' ? 1 : 2,
          }
          const res = await getDynamicTableData(params)
          if (res && res.code === 200) {
            const records = res.value?.records || res.value || []
            this.dynamicTableData = Array.isArray(records) ? records : []
          } else {
            this.dynamicTableData =
              this.currentTemplateRow?.dynamicTableData || []
          }

          if (
            this.currentTemplateRow &&
            this.currentTemplateRow.tableItems &&
            this.currentTemplateRow.tableItems.length > 0
          ) {
            this.tableItems = this.currentTemplateRow.tableItems
          } else {
            this.tableItems = this.getMockTableItems()
          }
          this.dynamicTableDialogVisible = true
        } catch (error) {
          console.error('获取动态表数据失败', error)
          this.dynamicTableData =
            this.currentTemplateRow?.dynamicTableData || []
          this.tableItems =
            this.currentTemplateRow?.tableItems || this.getMockTableItems()
          this.dynamicTableDialogVisible = true
        }
      },
      async initFormFields() {
        if (
          this.currentTemplateRow &&
          this.getSurveyTemplateId(this.currentTemplateRow)
        ) {
          try {
            const params = {
              surveyTemplateId: this.getSurveyTemplateId(
                this.currentTemplateRow
              ),
              type: this.viewContext === 'costSurvey' ? 1 : 2,
            }
            const res = await getListBySurveyFdTemplateIdAndVersion(params)
            if (res && res.code === 200) {
              let mapped = []
              if (Array.isArray(res.value)) {
                mapped = res.value
                  .map((item, index) =>
                    this.mapApiFieldToFormField(item, index)
                  )
                  .filter(Boolean)
              } else if (res.value && typeof res.value === 'object') {
                const { fixedFields, fixedFieldids } = res.value
                if (fixedFields && fixedFieldids) {
                  const labels = fixedFields.split(',').map((i) => i.trim())
                  const ids = fixedFieldids.split(',').map((i) => i.trim())
                  mapped = labels.map((label, index) => ({
                    prop: ids[index] || `field_${index}`,
                    label,
                    type: 'input',
                    colSpan: 12,
                    placeholder: `请输入${label}`,
                    rules: [],
                    defaultValue: '',
                    disabled: false,
                    clearable: true,
                    multiple: false,
                    required: false,
                  }))
                }
              }
              this.formFields =
                mapped.length > 0 ? mapped : this.getMockFormFields()
            } else {
              this.formFields = this.getMockFormFields()
            }
            this.surveyFormDialogVisible = true
          } catch (err) {
            console.error('获取单记录表单字段配置失败', err)
            this.formFields = this.getMockFormFields()
            this.surveyFormDialogVisible = true
          }
        } else {
          this.formFields = this.getMockFormFields()
          this.surveyFormDialogVisible = true
        }
      },
      async initFixedTableData() {
        if (
          this.currentTemplateRow &&
          this.getSurveyTemplateId(this.currentTemplateRow)
        ) {
          try {
            const params = {
              surveyTemplateId: this.getSurveyTemplateId(
                this.currentTemplateRow
              ),
              type: this.viewContext === 'costSurvey' ? 1 : 2,
            }
            const res = await getSingleRecordSurveyList(params)
            if (res && res.code === 200 && res.value) {
              const { itemlist } = res.value
              if (itemlist && Array.isArray(itemlist) && itemlist.length > 0) {
                this.tableItems = itemlist.map((item) => ({
                  id: item.id || item.itemId || '',
                  rowid: item.rowid || item.id || item.itemId || '',
                  seq: item.序号,
                  itemName: item.项目 || '',
                  unit: item.unit || '',
                  isCategory: item.isCategory || false,
                  categorySeq: item.categorySeq || '',
                  categoryId: item.categoryId || '',
                  parentid:
                    item.parentid !== undefined
                      ? item.parentid
                      : item.parentId !== undefined
                      ? item.parentId
                      : '-1',
                  validateRules: item.validateRules || {},
                  linkageRules: item.linkageRules || {},
                  children: item.children || [],
                  ...item,
                }))
                // 如果接口返回 fixedFields/fixedFieldids，一并保存，供弹窗表头渲染
                if (res.value.fixedFields && res.value.fixedFieldids) {
                  this.fixedFields = res.value.fixedFields
                  this.fixedFieldids = res.value.fixedFieldids
                }
              } else {
                this.tableItems = this.getMockTableItems()
              }
            } else {
              this.tableItems = this.getMockTableItems()
            }
          } catch (err) {
            console.error('获取固定表配置失败', err)
            this.tableItems = this.getMockTableItems()
          }
        } else if (
          this.currentTemplateRow &&
          this.currentTemplateRow.tableItems
        ) {
          this.tableItems = this.currentTemplateRow.tableItems
        } else {
          this.tableItems = this.getMockTableItems()
        }

        const currentYear = new Date().getFullYear()
        this.auditPeriods = [
          String(currentYear - 2),
          String(currentYear - 1),
          String(currentYear),
        ]

        try {
          const headerRes = await getListBySurveyFdTemplateIdAndVersion({
            surveyTemplateId: this.getSurveyTemplateId(this.currentTemplateRow),
            type: this.viewContext === 'costSurvey' ? 1 : 2,
          })
          if (headerRes && headerRes.code === 200) {
            this.fixedHeaders = headerRes.value || null
          } else {
            this.fixedHeaders = null
          }
        } catch (err) {
          console.error('获取固定表表头配置失败', err)
          this.fixedHeaders = null
        }

        this.fixedTableDialogVisible = true
      },
      getSurveyTemplateId(row) {
        return (
          row?.surveyTemplateId ||
          row?.templateId ||
          row?.surveyTemplateID ||
          row?.templateID ||
          ''
        )
      },
      getMockFormFields() {
        return []
      },
      getMockTableItems() {
        return []
      },
      mapApiFieldToFormField(item, index = 0) {
        if (!item) return null
        const getVal = (keys, fallback) => {
          for (const key of keys) {
            if (
              key &&
              item[key] !== undefined &&
              item[key] !== null &&
              item[key] !== ''
            ) {
              return item[key]
            }
          }
          return fallback
        }
        const prop =
          getVal(
            [
              'fieldName',
              'field_name',
              'columnName',
              'column_name',
              'fieldCode',
            ],
            undefined
          ) || `field_${index}`
        const label =
          getVal(
            [
              'columnComment',
              'column_comment',
              'fieldCname',
              'field_cname',
              'fieldLabel',
              'field_label',
            ],
            prop
          ) || prop
        return {
          prop,
          label,
          type: 'input',
          colSpan: 12,
          placeholder: `请输入${label}`,
          rules: [],
          defaultValue: '',
          disabled: false,
          clearable: true,
          multiple: false,
          required: false,
        }
      },
      // 加载监审文书
      async loadAuditDocument() {
        try {
          this.loading = true
          //调用监审文书接口
          this.formData.auditDocument = []
          this.tabLoadedStatus.auditDocument = true
          getCostProjectDocumentPageList({
            pageNum: this.auditDocumentPagination.page,
            pageSize: this.auditDocumentPagination.pageSize,
            projectId: this.currentTaskInfo.projectId,
            // documentName: '',
            permissionType: 1,
          }).then((res) => {
            let records = res.value.value.records
            this.formData.auditDocument = records.filter((item) => {
              const excludeTypes = [
                '成本监审工作底稿-送达回证',
                '成本监审提取资料登记表-送达回证',
                '成本审核初步意见表1-送达回证',
                '成本监审集体审议记录-送达回证',
              ]
              return !excludeTypes.includes(item.documentName)
            })
            this.auditDocumentPagination.total = res.value.value.total
          })
        } catch (error) {
          console.error('加载监审文书失败:', error)
          // this.$message.error('加载监审文书失败')
        } finally {
          this.loading = false
        }
      },
      handleTemplateChange() {
        let data = this.documentData.documentTypes.find(
          (item) => item.id === this.document.documentId
        )
        this.fileUrl = data.fileUrl
      },
      // 查看监审文书
      handleDocView(row) {
        this.document = {
          ...row,
        }
        // 从API中获取文件URL
        downDocument({
          id: row.id,
        }).then((res) => {
          if (res.state) {
            // this.fileUrl = res.value || ''
            this.handleViewScan(res.value || '')
          } else {
            this.$message.error('获取文件URL失败')
          }
        })
        // this.handleTemplateChange()
        // this.documentDialogVisible = true
        // getCostProjectDocumentFile({
        //   id: row.id,
        // }).then((res) => {
        //   this.costDocumentTemplateFiles = res.value || []
        // })
      },
      // 关闭监审文书查看弹窗
      handleDocCancel() {
        this.documentDialogVisible = false
        // 重置相关数据状态，避免再次打开时显示上一次的数据
        this.document = {}
        this.fileUrl = ''
        this.costDocumentTemplateFiles = []
      },
      // 查看文件
      handleViewScan(fileUrl) {
        if (!fileUrl) {
          this.$message.error('暂无文件！')
          return
        }
        let _fileUrl = ''
        if (fileUrl.startsWith('http')) {
          _fileUrl = fileUrl
        } else {
          _fileUrl = window.context.form + fileUrl
        }
        // 对文件URL进行Base64编码
        const encodedUrl = encodeURIComponent(Base64.encode(_fileUrl))

        // 构建 kkFileView 预览URL
        // onlinePreview - 在线预览
        // onlinePreview?type=pdf - 强制使用PDF模式预览
        window.open(`${host}:8012/onlinePreview?url=${encodedUrl}`)
      },
      // 查看反馈
      handleViewFeedback(feedbackDocumentUrl) {
        if (!feedbackDocumentUrl) {
          this.$message.error('暂无文件！')
          return
        }
        // 确保attachments是数组格式
        if (feedbackDocumentUrl) {
          if (typeof feedbackDocumentUrl === 'string') {
            // 如果是逗号分隔的字符串，转换为数组
            this.attachments = feedbackDocumentUrl.split(',')
          } else {
            // 其他情况，包装为数组
            this.attachments = [feedbackDocumentUrl]
          }
        } else {
          this.attachments = []
        }
        // 显示附件弹窗
        this.dialogMultiVisible = true
      },
      // 上传文件
      handleUploadScan(row, type) {
        let loading = null
        // 第一步：创建文件选择器
        const input = document.createElement('input')
        input.type = 'file'
        input.accept = '.pdf,.doc,.docx,.xls,.xlsx,.csv' // 允许的文件类型

        input.onchange = async (event) => {
          const file = event.target.files[0]
          if (!file) return

          try {
            // 校验文件大小（50MB）
            const maxSize = 50 * 1024 * 1024 // 50MB
            if (file.size > maxSize) {
              this.$message.error('文件大小不能超过50MB！')
              return
            }

            // 校验文件格式
            const allowedFormats = [
              '.pdf',
              '.doc',
              '.docx',
              '.xls',
              '.xlsx',
              '.csv',
            ]
            const fileName = file.name.toLowerCase()
            const isValidFormat = allowedFormats.some((format) =>
              fileName.endsWith(format)
            )

            if (!isValidFormat) {
              this.$message.error(
                '只允许上传.pdf,.doc,.docx,.xls,.xlsx,.csv格式的文件！'
              )
              return
            }

            // 显示遮罩层
            loading = this.$baseLoading(1, '文件上传中...')

            // 第三步：创建FormData并上传文件
            const formData = new FormData()
            formData.append('file', file)

            // 先调用上传API
            const uploadRes = await uploadFile('/api/file/v1/upload', formData)

            // 第四步：检查上传结果
            if (!uploadRes || !uploadRes.value) {
              // this.$message.error('文件上传失败！');
              return
            }

            // 第五步：文件上传成功后，再更新数据
            const fileInfo = uploadRes.value
            let feedbackDocumentUrl = row.feedbackDocumentUrl
            if (feedbackDocumentUrl) {
              feedbackDocumentUrl = feedbackDocumentUrl.split(',')
              feedbackDocumentUrl.push(fileInfo?.savePath)
              feedbackDocumentUrl = feedbackDocumentUrl.join(',')
            } else {
              feedbackDocumentUrl = fileInfo?.savePath
            }
            // 创建更新数据对象
            const updateData = {
              id: row.id,
              feedbackDocumentUrl: feedbackDocumentUrl, // 更新扫描件URL
            }

            // 第六步：调用更新API
            await updateFeedback(updateData)

            // 第七步：更新成功，显示提示并刷新
            this.$message.success('文件上传成功并更新数据！')
            this.loadAuditDocument()
          } catch (error) {
            // 错误处理
            this.$message.error('操作失败：' + (error.message || '未知错误'))
            console.error('文件上传失败:', error)
          } finally {
            // 关闭遮罩层
            loading.close()
          }
        }
        // 触发文件选择
        input.click()
      },
      // 下载文档
      handleDownloadDocument(row) {
        // 显示加载状态
        this.$loading({
          lock: true,
          text: '文件下载中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)',
        })

        // 从API中获取文件URL
        downDocument({
          id: row.id,
        })
          .then((res) => {
            // 关闭加载状态
            this.$loading().close()

            // 检查返回结果是否成功
            if (!res || !res.state) {
              this.$message.error(
                `下载失败：${res?.message || '未获取到文件数据'}`
              )
              return
            }

            // 获取文件URL
            const fileUrl = res.value
            if (!fileUrl) {
              this.$message.error('下载失败：未获取到文件URL')
              return
            }

            // 优先从URL中提取文件名
            let fileName = ''

            // 从URL中提取文件名
            const urlParts = fileUrl.split('/')
            let urlFileName = urlParts[urlParts.length - 1]

            // 处理URL可能包含查询参数的情况
            if (urlFileName.includes('?')) {
              urlFileName = urlFileName.split('?')[0]
            }

            // 检查从URL提取的文件名是否有效
            if (urlFileName && /\.[a-zA-Z0-9]+$/.test(urlFileName)) {
              fileName = urlFileName
            } else {
              // URL中无法提取有效文件名时，使用row.documentName作为备选
              fileName =
                row.documentName ||
                `${row.documentName}_${new Date().getTime()}`

              // 确保备选文件名有扩展名
              if (!/\.[a-zA-Z0-9]+$/.test(fileName)) {
                fileName += '.pdf'
              }
            }
            // 创建隐藏的a标签进行下载
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = fileUrl
            // link.href = window.context.form + row.electronicDocumentUrl
            // 设置下载文件名
            link.download = fileName
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
          .catch((error) => {
            // 关闭加载状态
            this.$loading().close()
            console.error('获取文件URL失败:', error)
          })
      },

      // 加载报送资料
      async loadDataRequirements() {
        if (!this.currentTaskInfo?.taskId) {
          return
        }

        try {
          this.loading = true
          const res = await getTaskRequirementList(this.currentTaskInfo.taskId)
          console.log('报送资料', res)

          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() {
        console.log(1111111)
        // if (!this.catalogId) {
        //   this.formData.costSurveyData = []
        //   this.costSurveyPagination.total = 0
        //   this.tabLoadedStatus.costSurvey = true
        //   return
        // }
        try {
          this.loading = true
          // getSurveyList 现在按 taskId 查询
          if (!this.currentTaskInfo || !this.currentTaskInfo.taskId) {
            this.formData.costSurveyData = []
            this.costSurveyPagination.total = 0
            this.tabLoadedStatus.costSurvey = true
            this.loading = false
            return
          }
          const params = {
            taskId: this.currentTaskInfo.taskId,
            pageNum: this.costSurveyPagination.currentPage,
            pageSize: this.costSurveyPagination.pageSize,
            type: 1,
          }
          if (this.auditedUnitId) params.auditedUnitId = this.auditedUnitId
          const res = await getSurveyList(params)
          console.log(res, 'res')
          // 兼容不同返回结构
          const raw =
            (res &&
              ((res.value && (res.value.records || res.value)) ||
                res.data ||
                res)) ||
            []
          const list = Array.isArray(raw)
            ? raw
            : Array.isArray(raw.records)
            ? raw.records
            : []
          const rows = list.map((it, idx) => {
            const t = String(it.templateType || it.templatetype || '')
            const tableType =
              t === '1'
                ? '单记录'
                : t === '2'
                ? '固定表'
                : t === '3'
                ? '动态表'
                : ''
            return {
              index:
                (this.costSurveyPagination.currentPage - 1) *
                  this.costSurveyPagination.pageSize +
                idx +
                1,
              id: it.uploadId || it.id || '',
              name:
                it.surveyTemplateName || it.informationName || it.name || '',
              dataType: it.dataType || '预置模板',
              tableType,
              isRequired: String(it.isRequired) === '1' ? '是' : '否',
              isUpload: String(it.isUpload) === '1' || it.isUpload === true,
              uploadId: it.uploadId || it.id || '',
              surveyTemplateId: it.templateId || it.surveyTemplateId || '',
              catalogId: it.catalogId || this.catalogId || '',
              auditedUnitId: it.auditedUnitId || this.auditedUnitId || '',
              templateType: t,
            }
          })
          this.formData.costSurveyData = rows
          // 设置总数
          const total =
            (res &&
              res.value &&
              (res.value.total ||
                (Array.isArray(res.value.records)
                  ? res.value.records.length
                  : Array.isArray(res.value)
                  ? res.value.length
                  : 0))) ||
            (Array.isArray(raw) ? raw.length : raw.total || 0)
          this.costSurveyPagination.total = total
          this.tabLoadedStatus.costSurvey = true
        } catch (err) {
          console.error('加载成本调查表失败:', err)
          // this.$message &&
          //   this.$message.error &&
          //   this.$message.error('加载成本调查表失败')
          this.formData.costSurveyData = []
          this.costSurveyPagination.total = 0
          this.tabLoadedStatus.costSurvey = true
        } 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
        this.loadCostSurvey()
      },

      // 成本调查表分页 - 每页条数改变
      handleCostSurveySizeChange(size) {
        this.costSurveyPagination.pageSize = size
        this.costSurveyPagination.currentPage = 1
        this.loadCostSurvey()
      },

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

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

      // 监审文书分页 - 每页条数改变
      handleSizeChange(size) {
        this.auditDocumentPagination.pageSize = size
        this.auditDocumentPagination.page = 1
        this.loadAuditDocument()
      },

      // 监审文书分页 - 页码改变
      handleCurrentChange(page) {
        this.auditDocumentPagination.page = page
        this.loadAuditDocument()
      },
    },
  }
</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: right;
    padding-top: 10px;
  }
  .document-edit-container {
    display: flex;
    .document-params {
      width: 55%;
    }
    .document-preview {
      width: 45%;
    }
  }
</style>
