<template>
  <el-drawer
    :visible.sync="drawerVisible"
    :size="drawerSize"
    :with-header="true"
    :modal="true"
    :z-index="9000"
    :close-on-click-modal="false"
    :show-close="true"
    @close="handleDrawerClose"
    @update:visible="(val) => $emit('update:visible', val)"
  >
    <div slot="title" class="drawer-title">
      <span>{{ pageTitle || '填报任务' }}</span>
    </div>

    <div class="audit-task-manage-container">
      <!-- 操作按钮 -->
      <div class="action-buttons" style="margin-bottom: 20px">
        <el-button
          type="primary"
          :loading="loading.submit"
          :disabled="isViewMode"
          @click="handleSubmit"
        >
          提交
        </el-button>
        <!-- <el-button type="primary" :loading="loading.save" @click="handleSave" :disabled="isViewMode">
          保存
        </el-button> -->
        <!-- <el-button type="primary" class="ml10" @click="handleBack">
          返回
        </el-button> -->
      </div>

      <!-- 标签页容器 -->
      <div
        v-loading="tabLoading[activeTab]"
        class="tabs-container"
        element-loading-text="数据加载中..."
      >
        <el-tabs
          v-model="activeTab"
          type="border-card"
          @tab-click="handleTabClick"
        >
          <!-- 立项信息 -->
          <el-tab-pane label="立项信息" name="projectInfo">
            <project-info-tab
              :form-data="formData.basicInfo"
              :is-view-mode="isViewMode"
              :unit-list="unitList"
              :org-list="OrgList"
              :user-list="userList"
              :dict-data="dictData"
              @change="handleProjectInfoChange"
              @handleCatalogChange="handleCatalogChange"
              @handleRegionChange="handleRegionChange"
              @addCostYear="addCostYear"
              @deleteCostYear="deleteCostYear"
            />
          </el-tab-pane>

          <!-- 监审文书 -->
          <el-tab-pane label="监审文书" name="auditDocument">
            <audit-document-tab
              :form-data="formData.auditDocument"
              :is-view-mode="isViewMode"
              :pagination="auditDocumentPagination"
              @handleClick="handleClick"
              @handleDownload="handleDownload"
              @handleUpload="handleUpload"
              @refresh="getAuditDocumentList"
              @paginationChange="handleAuditDocumentPaginationChange"
            />
          </el-tab-pane>

          <!-- 报送资料 -->
          <el-tab-pane
            v-if="currentNode === 'clcs' || currentNode === 'tjcl'"
            label="报送资料"
            name="dataRequirements"
          >
            <data-requirements-tab
              :data-requirements="groupedDataRequirements"
              :is-view-mode="isViewMode"
              :dict-data="dictData"
              :current-node="currentNode"
              :audited-unit-id="auditedUnitId"
              :task-id="taskId"
              @handleAddMaterial="handleAddMaterial"
              @handleFileView="handleFileView"
              @handleFileDownload="handleFileDownload"
              @handleFileUpload="handleFileUpload"
              @handleTemplateDownload="handleTemplateDownload"
              @data-upload-success="getTaskRequirementPage"
              @handleDataUpload="handleDataUpload"
              @handle-survey-form-save="getTaskRequirementPage"
              @handle-fixed-table-save="getTaskRequirementPage"
              @handle-dynamic-table-save="getTaskRequirementPage"
            />
          </el-tab-pane>
          <!-- 成本调查表 -->
          <el-tab-pane
            v-if="currentNode === 'clcs' || currentNode === 'tjcl'"
            label="成本调查表"
            name="costSurvey"
          >
            <cost-survey-tab
              :paginated-data="formData.paginatedData"
              :pagination="costSurveyPagination"
              :is-view-mode="isViewMode"
              :audited-unit-id="auditedUnitId"
              :catalog-id="taskInfo.catalogId"
              :task-id="taskInfo.taskId"
              :project-id="taskInfo.projectId"
              :audit-period="getAuditPeriodArray()"
              @handle-modify="handleModify"
              @handle-data-download="handleDataDownload"
              @handle-data-upload="handleDataUpload"
              @handle-preview="handlePreview"
              @handle-page-change="handleCostSurveyPageChange"
              @handle-size-change="handleCostSurveySizeChange"
              @handle-survey-form-save="handleSurveyFormSave"
            />
          </el-tab-pane>

          <!-- 监审意见 -->
          <el-tab-pane
            v-if="currentNode === 'yjfk'"
            label="监审意见"
            name="auditOpinion"
          >
            <audit-opinion-tab
              :id="taskId"
              ref="auditOpinionTabRef"
              :form-data="formData.auditOpinion"
              :is-view-mode="isViewMode"
              @change="handleAuditOpinionChange"
              @data-loaded="handleAuditOpinionDataLoaded"
            />
          </el-tab-pane>

          <!-- 消息通知 -->
          <el-tab-pane label="消息通知" name="messageNotice">
            <message-notice-tab
              :form-data="formData.messageNotice"
              :pagination="messageNoticePagination"
              @handleCurrentChange="handleMessageNoticePageChange"
              @handleSizeChange="handleMessageNoticeSizeChange"
            />
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 补充材料弹窗 -->
      <el-dialog
        title="补充材料"
        :visible.sync="materialDialogVisible"
        width="600px"
        :z-index="10000"
        :close-on-click-modal="false"
        :modal="true"
        append-to-body
      >
        <el-form
          ref="materialForm"
          :model="materialForm"
          :rules="materialRules"
          label-width="100px"
        >
          <el-form-item label="资料类别" prop="informationType">
            <el-select
              v-model="materialForm.informationType"
              placeholder="请选择资料类别"
              style="width: 100%"
              :disabled="isViewMode"
            >
              <el-option
                v-for="item in dictData['materialType']"
                :key="item.key"
                :label="item.name"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="资料名称" prop="informationName">
            <el-input
              v-model="materialForm.informationName"
              placeholder="请输入资料名称"
              style="width: 100%"
              :disabled="isViewMode"
            ></el-input>
          </el-form-item>
          <el-form-item label="资料要求:" prop="informationRequire">
            <el-input
              v-model="materialForm.informationRequire"
              placeholder="请输入资料要求"
              :disabled="isViewMode"
            ></el-input>
          </el-form-item>
          <el-form-item label="格式要求:" prop="formatRequired">
            <el-select
              v-model="materialForm.formatRequired"
              placeholder="请选择格式要求"
              style="width: 100%"
              :disabled="isViewMode"
            >
              <el-option
                v-for="item in dictData['formatAsk']"
                :key="item.id"
                :label="item.name"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传附件:" prop="fileList">
            <el-upload
              class="upload-demo"
              :action="''"
              :http-request="handleMaterialUpload"
              :on-remove="handleMaterialRemove"
              :before-upload="beforeMaterialUpload"
              :on-success="handleMaterialUploadSuccess"
              :on-error="handleMaterialUploadError"
              :on-progress="handleMaterialUploadProgress"
              :file-list="materialForm.fileList"
              :limit="1"
              :on-exceed="handleMaterialExceed"
              :accept="uploadAccept"
            >
              <el-button
                v-show="
                  !isTemplateFormat &&
                  (!materialForm.fileList || materialForm.fileList.length === 0)
                "
                size="small"
                type="primary"
                :disabled="isViewMode"
              >
                选择文件
              </el-button>
              <el-button
                v-if="isTemplateFormat"
                size="small"
                type="primary"
                :disabled="isViewMode"
                @click.stop="openLegalDialog"
              >
                选择模版
              </el-button>
              <!-- <div slot="tip" class="el-upload__tip">
                最多上传1个文件，支持 pdf, doc, docx, xls, xlsx, csv 格式，单个文件不超过50MB
              </div> -->
            </el-upload>
          </el-form-item>
          <!-- <el-button
              type="text"
              size="mini"
              @click="handleMaterialUpload"
            >
              上传附件
            </el-button> -->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            :loading="loading.materialSubmit"
            :disabled="isViewMode"
            @click="handleMaterialSubmit"
          >
            保 存
          </el-button>
          <el-button :disabled="isViewMode" @click="handleMaterialCancel">
            取 消
          </el-button>
        </div>
      </el-dialog>

      <!-- 预置模版选择弹窗 -->
      <!-- <legal-dialog
        v-if="legalDialogMounted"
        :visible.sync="legalDialogVisible"
        @confirm="handleLegalConfirm"
        @close="legalDialogVisible = false"
      /> -->

      <!-- 使用 CostAuditTable 的通用选择模版弹窗 -->
      <CostAuditDialog
        v-if="costAuditDialogVisible"
        :title="'选择模板'"
        :visible="costAuditDialogVisible"
        width="50%"
        :z-index="20000"
        :close-on-click-modal="false"
        :confirm-loading="costAuditSubmitting"
        @confirm="submitCostAuditTemplate"
        @cancel="costAuditDialogVisible = false"
        @close="costAuditDialogVisible = false"
      >
        <cost-audit-table
          :table-data="costTemplateData"
          :columns="costTemplateColumns"
          :show-selection="true"
          :show-pagination="true"
          :pagination="costTemplatePagination"
          @pagination-change="handleCostTemplatePaginationChange"
          @selection-change="handleCostTemplateSelectionChange"
        >
          <template #createTime="{ row }">
            <div>{{ row.createTime ? row.createTime.split(' ')[0] : '-' }}</div>
            <div>{{ row.createTime ? row.createTime.split(' ')[1] : '-' }}</div>
          </template>
        </cost-audit-table>
      </CostAuditDialog>

      <!-- 在线填报弹窗 -->
      <OnlineFillDialog
        :visible.sync="onlineFillDialogVisible"
        :table-type="currentSurveyData ? currentSurveyData.tableType : '单记录'"
        :survey-data="currentSurveyData || {}"
      />
    </div>
  </el-drawer>
</template>

<script>
  import { Message } from 'element-ui'
  import OnlineFillDialog from './OnlineFill.vue'
  import {
    getProjectInformationInfo,
    getTaskRequirementList,
    addOrUpdateTaskRequirement,
    submitTaskRequirement,
    sendMessage,
  } from '@/api/auditTaskProcessing'
  // import UploadComponent from '@/components/costAudit/UploadComponent.vue'
  import { getAllUnitList } from '@/api/auditEntityManage'
  import { getDefaultDem, getOrgListByDemId } from '@/api/annualReviewPlan'
  import { getAllUserList } from '@/api/uc'
  import { dictMixin } from '@/mixins/useDict'
  import { uploadFile } from '@/api/file'
  import { submitPreliminaryOpinion } from '@/api/audit/preliminaryOpinion'
  import { getSurveyList } from '@/api/audit/survey'
  import ProjectInfoTab from './components/ProjectInfoTab.vue'
  import AuditDocumentTab from './components/AuditDocumentTab.vue'
  import DataRequirementsTab from './components/DataRequirementsTab.vue'
  import CostSurveyTab from './components/CostSurveyTab.vue'
  import AuditOpinionTab from './components/AuditOpinionTab.vue'
  import MessageNoticeTab from './components/MessageNoticeTab.vue'
  import LegalDialog from '@/views/costAudit/baseInfo/catalogManage/legalDialog.vue'
  import CostAuditDialog from '@/components/costAudit/CostAuditDialog'
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import { allcurrentCostSurveyList } from '@/api/financeSheetManage'
  import { getCostProjectDocumentPageList } from '@/api/taskCustomizedRelease.js'
  export default {
    name: 'TaskFillIn',
    components: {
      OnlineFillDialog,
      // UploadComponent,
      ProjectInfoTab,
      AuditDocumentTab,
      DataRequirementsTab,
      CostSurveyTab,
      AuditOpinionTab,
      MessageNoticeTab,
      // LegalDialog,
      CostAuditDialog,
      CostAuditTable,
    },
    mixins: [dictMixin],
    props: {
      // 侧边弹窗是否显示
      visible: {
        type: Boolean,
        default: false,
      },
      // 侧边弹窗尺寸
      drawerSize: {
        type: String,
        default: '85%',
      },
      // 任务信息（从props传入，替代路由query）
      taskInfo: {
        type: Object,
        default: () => ({}),
      },
      // 是否为查看模式
      viewMode: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        drawerVisible: false, // 侧边弹窗显示状态
        isViewMode: false, // 是否为查看模式
        localTaskInfo: {}, // 本地任务信息（用于存储）
        unitList: [],
        OrgList: [],
        userList: [],
        dictData: {
          attributionYear: [], // 归属年度
          projectProposal: [], // 立项来源
          auditType: [], //监审形式
          materialType: [], // 资料类别
          materialCategory: [], // 资料类别
          formatAsk: [], // 资料类型
          clshzt: [], // 是否通过
        },
        // 立项依据文件列表
        accordingFileList: [],
        // 其他材料文件列表
        otherFileList: [],
        // 页面标题
        pageTitle: '立项信息',
        projectId: '', // 项目ID
        taskId: '', // 任务ID
        auditedUnitId: '', // 被监审单位ID
        currentNode: '', // 当前节点
        // 当前激活的标签页
        activeTab: 'projectInfo',
        // 加载状态管理
        loading: {
          submit: false,
          save: false,
          materialSubmit: false,
        },
        // 标签页加载状态
        tabLoading: {
          projectInfo: false,
          auditDocument: false,
          dataRequirements: false,
          costSurvey: false,
          auditOpinion: false,
          messageNotice: false,
        },
        isDisabled: false,
        tabCheck: '', // 状态判断监审意见是否显示
        tabVisiable: true, // 标签页是否显示
        // 成本调查表分页相关
        costSurveyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 消息通知分页相关
        messageNoticePagination: {
          pageNo: 1,
          pageSize: 10,
          total: 0,
        },
        auditDocumentPagination: {
          page: 1,
          pageSize: 10,
          total: 0,
        },
        // 所有表单数据聚合
        formData: {
          basicInfo: {
            projectName: '',
            catalogId: '',
            areaCode: '',
            auditUnitId: [],
            auditUnitName: '',
            orgId: '',
            orgName: '',
            projectYear: '',
            sourceType: '',
            auditType: '',
            auditPeriod: '',
            auditPeriodArray: [{ value: '' }],
            needHearing: 1,
            isEmergency: 1,
            establishmentReason: '',
            accordingFileUrl: '',
            otherFileUrl: '',
            auditGroup: '',
            auditTeamMembers: [],
            expertStr: '',
            plannedAuditStartDate: '',
            plannedAuditEndDate: '',
          },
          auditDocument: [],
          dataRequirements: [],
          costSurveyData: [
            {
              index: 1,
              name: '封面',
              dataType: '模版定制',
              tableType: '单记录',
              isRequired: '是',
              isUploaded: false,
              isDisabled: false,
            },
            {
              index: 2,
              name: '企业基本情况调查表',
              dataType: '模版定制',
              tableType: '固定表',
              isRequired: '是',
              isUploaded: true,
              isDisabled: false,
            },
            {
              index: 3,
              name: '企业成本费用调查表',
              dataType: '模版定制',
              tableType: '固定表',
              isRequired: '是',
              isUploaded: true,
              isDisabled: false,
            },
            {
              index: 4,
              name: '企业期间费用调查表',
              dataType: '模版定制',
              tableType: '动态表',
              isRequired: '是',
              isUploaded: false,
              isDisabled: true, // 灰色不可点击
            },
            {
              index: 5,
              name: '企业职工薪酬调查表',
              dataType: '模版定制',
              tableType: '动态表',
              isRequired: '是',
              isUploaded: false,
              isDisabled: true, // 灰色不可点击
            },
            {
              index: 6,
              name: '……',
              dataType: '模版定制',
              tableType: '动态表',
              isRequired: '是',
              isUploaded: false,
              isDisabled: false,
            },
          ],
          auditOpinion: {
            basicFinancialInfo:
              '此处为被监审单位基本情况及主要财务状况的内容...',
            priceStandard: '此处为监审项目现行执行的价格标准的内容...',
            costComposition:
              '此处为监审项目的成本构成、数据核增核减情况、依据及理由的内容...',
            preliminaryOpinion: '此处为成本审核初步意见的内容...',
            feedbackOpinion: '', // 被监审单位可输入反馈意见
            feedbackMaterials: [], // 被监审单位上传的反馈文件
          },
          messageNotice: [], // 消息通知列表
          paginatedData: [
            {
              name: '封面',
              dataType: '模版定制',
              tableType: '单记录',
              isRequired: '是',
              isUploaded: false,
              isDisabled: false,
            },
            {
              name: '企业基本情况调查表',
              dataType: '模版定制',
              tableType: '固定表',
              isRequired: '是',
              isUploaded: true,
              isDisabled: false,
            },
            {
              name: '企业成本费用调查表',
              dataType: '模版定制',
              tableType: '动态表',
              isRequired: '是',
              isUploaded: true,
              isDisabled: false,
            },
          ],
        },
        // 监审地区级联选择器
        regionOptions: [
          {
            value: 'zhinan',
            label: '指南',
            children: [
              {
                value: 'shejiyuanze',
                label: '设计原则',
                children: [
                  {
                    value: 'yizhi',
                    label: '一致',
                  },
                  {
                    value: 'fankui',
                    label: '反馈',
                  },
                  {
                    value: 'xiaolv',
                    label: '效率',
                  },
                  {
                    value: 'kekong',
                    label: '可控',
                  },
                ],
              },
            ],
          },
        ],
        dialogVisible: false,
        catalogueData: [
          {
            label: '一级 1',
            children: [
              {
                label: '二级 1-1',
                children: [
                  {
                    label: '三级 1-1-1',
                  },
                ],
              },
            ],
          },
          {
            label: '一级 2',
            children: [
              {
                label: '二级 2-1',
                children: [
                  {
                    label: '三级 2-1-1',
                  },
                ],
              },
              {
                label: '二级 2-2',
                children: [
                  {
                    label: '三级 2-2-1',
                  },
                ],
              },
            ],
          },
          {
            label: '一级 3',
            children: [
              {
                label: '二级 3-1',
                children: [
                  {
                    label: '三级 3-1-1',
                  },
                ],
              },
              {
                label: '二级 3-2',
                children: [
                  {
                    label: '三级 3-2-1',
                  },
                ],
              },
            ],
          },
        ],
        defaultProps: {
          children: 'children',
          label: 'label',
        },
        // 补充材料弹窗相关数据
        materialDialogVisible: false,
        materialForm: {
          informationType: '',
          informationName: '',
          informationRequire: '',
          formatRequired: '',
          fileList: [],
          fileUrl: '',
          templateId: '',
        },
        materialRules: {
          informationType: [
            { required: true, message: '请选择资料类别', trigger: 'change' },
          ],
          informationName: [
            { required: true, message: '请输入资料名称', trigger: 'blur' },
          ],
          formatRequired: [
            { required: true, message: '请选择格式要求', trigger: 'change' },
          ],
          informationRequire: [
            { required: true, message: '请输入资料要求', trigger: 'blur' },
          ],
        },
        materialCategoryOptions: [
          { label: '综合性资料', value: 'comprehensive' },
          { label: '财务会计资料', value: 'financial' },
          { label: '其他资料', value: 'other' },
        ],
        // 修复未定义的变量
        value: [], // 监审地区级联选择器的值
        value3: null, // 年份选择器的值

        // 在线填报弹窗相关数据
        onlineFillDialogVisible: false,
        currentSurveyData: null,
        // 选择模版弹窗
        legalDialogVisible: false,
        legalDialogMounted: false,
        // 使用 CostAuditTable 的选择弹窗
        costAuditDialogVisible: false,
        costAuditSubmitting: false,
        costTemplateData: [],
        selectedCostTemplates: [],
        costTemplatePagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        costTemplateColumns: [
          { prop: 'surveyTemplateName', label: '财务数据表名称' },
          {
            prop: 'templateType',
            label: '模版类型',
            width: '100px',
            formatter: (row) => {
              return row.templateType == '1'
                ? '单记录'
                : row.templateType == '2'
                ? '固定表'
                : '动态表'
            },
          },
          { prop: 'status', label: '状态', width: '100px' },
          {
            prop: 'createTime',
            label: '创建时间',
            slotName: 'createTime',
            width: '100px',
          },
        ],
      }
    },
    computed: {
      // 是否选择了“预置模版”格式（通过名称或key含义判断，兼容后端字典差异）
      isTemplateFormat() {
        const raw = this.materialForm.formatRequired
        const v = (raw == null ? '' : String(raw)).toLowerCase()
        // 显式数值/字符串 3 代表预置模版
        if (raw === 3 || raw === '3') return true
        // 名称兜底匹配
        return (
          v.includes('template') ||
          v.includes('preset') ||
          v.includes('tpl') ||
          v.includes('模版') ||
          v.includes('模板')
        )
      },
      // 是否为文档（pdf/word）
      isDocumentFormat() {
        const raw = this.materialForm.formatRequired
        const v = (raw == null ? '' : String(raw)).toLowerCase()
        // 显式数值/字符串 1 代表文档
        if (raw === 1 || raw === '1') return true
        return (
          v.includes('doc') ||
          v.includes('word') ||
          v.includes('pdf') ||
          v.includes('文档') ||
          v.includes('word文档')
        )
      },
      // 是否为Excel
      isExcelFormat() {
        const raw = this.materialForm.formatRequired
        const v = (raw == null ? '' : String(raw)).toLowerCase()
        // 显式数值/字符串 2 代表excel
        if (raw === 2 || raw === '2') return true
        return (
          v.includes('excel') ||
          v.includes('xls') ||
          v.includes('xlsx') ||
          v.includes('表格')
        )
      },
      // 根据所选格式动态生成 accept
      uploadAccept() {
        if (this.isTemplateFormat) return ''
        if (this.isDocumentFormat) return '.pdf,.doc,.docx'
        if (this.isExcelFormat) return '.xls,.xlsx'
        // 默认允许常见类型
        return '.pdf,.doc,.docx,.xls,.xlsx,.csv'
      },
      // 按类别分组的报送资料列表
      groupedDataRequirements() {
        if (
          !this.formData.dataRequirements ||
          !Array.isArray(this.formData.dataRequirements) ||
          this.formData.dataRequirements.length === 0
        ) {
          return []
        }

        // 按类别分组
        const groups = {}
        this.formData.dataRequirements.forEach((item, index) => {
          // 获取类别标识，使用 informationType 作为类别 key
          const categoryKey =
            item.informationType ||
            item.category ||
            item.categoryId ||
            item.categoryName ||
            'other'
          // 优先从字典中获取类别名称
          let categoryName = ''
          if (categoryKey) {
            // 优先使用 getDictNameByValue 根据 value 查找
            categoryName = this.getDictNameByValue(
              'materialCategory',
              categoryKey
            )
            // 如果 getDictNameByValue 没找到，尝试使用 getDictName 根据 key 查找
            if (!categoryName || categoryName === String(categoryKey)) {
              categoryName = this.getDictName('materialCategory', categoryKey)
            }
            // 如果字典中都找不到，使用 item.categoryName 作为后备
            if (!categoryName || categoryName === String(categoryKey)) {
              categoryName = item.informationTypeName || categoryKey
            }
          }

          if (!groups[categoryKey]) {
            groups[categoryKey] = {
              categoryKey,
              categoryName: categoryName || String(categoryKey),
              items: [],
            }
          }
          // 添加序号（每个类别内从1开始）
          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: {
        immediate: true,
        handler(newVal) {
          this.drawerVisible = newVal
          if (
            newVal &&
            this.taskInfo &&
            Object.keys(this.taskInfo).length > 0
          ) {
            // 弹窗打开时初始化数据
            this.initData()
          }
        },
      },
      drawerVisible(newVal) {
        if (!newVal) {
          this.$emit('update:visible', false)
          this.$emit('close')
        }
      },
      taskInfo: {
        immediate: true,
        deep: true,
        handler(newVal) {
          // 如果props传入taskInfo且有值，且弹窗已打开，则初始化数据
          if (newVal && Object.keys(newVal).length > 0 && this.drawerVisible) {
            this.initData()
          }
        },
      },
    },
    mounted() {
      this.drawerVisible = this.visible
      this.getAllUnitList()
      this.getDefaultDem()
      this.getUser()

      // 默认设置立项信息标签页
      this.activeTab = 'projectInfo'
      this.pageTitle = '立项信息'

      // 如果有传入taskInfo，初始化数据
      if (this.taskInfo && Object.keys(this.taskInfo).length > 0) {
        this.initData()
      }

      // 初始化成本调查表分页总数
      this.costSurveyPagination.total = this.formData.costSurveyData.length
    },
    methods: {
      // 初始化数据
      initData() {
        // 优先使用props传入的taskInfo，其次使用localTaskInfo
        const info =
          this.taskInfo && Object.keys(this.taskInfo).length > 0
            ? this.taskInfo
            : this.localTaskInfo
        // 判断是否为查看模式
        this.isViewMode = this.viewMode || false
        this.projectId = info.projectId || ''
        this.taskId = (info.userTask && info.userTask.id) || info.taskId || ''
        this.tabCheck = info.status || ''
        this.auditedUnitId = info.auditedUnitId || ''
        console.log(this.auditedUnitId, 'this.auditedUnitId 122')
        this.currentNode = info.currentNode || ''

        if (this.tabCheck === 'jtsy') {
          this.tabVisiable = false
        }

        // 默认显示立项信息标签页
        this.activeTab = 'projectInfo'
        this.pageTitle = '立项信息'

        // 加载立项信息数据
        if (this.projectId) {
          this.getProjectInformation()
        }
      },
      // 打开弹窗方法（供外部调用）
      open(taskInfo, viewMode = false) {
        this.localTaskInfo = taskInfo || {}
        this.initData()
        this.drawerVisible = true
      },
      // 关闭弹窗方法
      close() {
        this.drawerVisible = false
      },
      getAllUnitList() {
        getAllUnitList().then((res) => {
          this.unitList = res.value || []
        })
      },
      // 获取默认维度
      getDefaultDem() {
        getDefaultDem().then((res) => {
          if (res && res.code === 200) {
            const demId = res.value ? res.value.id : null
            if (demId) {
              this.getOrgListByDemId(demId)
            }
          }
        })
      },
      // 根据维度ID获取单位列表
      getOrgListByDemId(demId) {
        getOrgListByDemId({ demId }).then((res) => {
          if (res && res.code === 200) {
            this.OrgList = res.value || []
          }
        })
      },
      // 获取用户信息
      getUser() {
        getAllUserList()
          .then((res) => {
            this.userList = res.value || []
          })
          .catch(() => {})
      },
      // 添加监审年份
      addCostYear() {
        this.formData.basicInfo.auditPeriodArray.push({ value: '' })
      },
      // 删除监审年份
      deleteCostYear(index) {
        // 若只剩1条，禁止删除并提示
        if (this.formData.basicInfo.auditPeriodArray.length <= 1) {
          Message.warning('监审期间至少需保留1条，无法删除')
          return
        }
        this.formData.basicInfo.auditPeriodArray.splice(index, 1)
      },
      // 更新auditPeriod字符串
      updateAuditPeriodString() {
        const values = this.formData.basicInfo.auditPeriodArray
          .map((item) => item.value)
          .filter(Boolean)
        const uniqueValues = [...new Set(values)]
        this.formData.basicInfo.auditPeriod = uniqueValues.join(',')
      },
      // 立项依据文件处理
      saveAccordingFiles(data) {
        this.accordingFileList = data
        this.formData.basicInfo.accordingFileUrl = data[0]?.savePath || ''
      },
      // 移除立项依据文件
      removeAccordingFile() {
        this.accordingFileList = []
        this.formData.basicInfo.accordingFileUrl = ''
      },
      // 其他材料文件处理
      saveOtherFiles(data) {
        this.otherFileList = data
        this.formData.basicInfo.otherFileUrl = data[0]?.savePath || ''
      },
      // 移除其他材料文件
      removeOtherFile() {
        this.otherFileList = []
        this.formData.basicInfo.otherFileUrl = ''
      },
      // 处理地区选择变化
      handleRegionChange(region) {
        this.formData.basicInfo.areaCode = region.code
      },
      // 处理监审目录选择后的回调
      handleCatalogChange(value) {
        // this.formData.catalogId = value.join(',')
        this.formData.basicInfo.catalogId = value
      },
      // 处理立项信息变化
      handleProjectInfoChange(data) {
        this.formData.basicInfo = { ...data }
      },
      // 处理监审意见变化
      handleAuditOpinionChange(data) {
        this.formData.auditOpinion = { ...data }
      },
      // 处理监审意见数据加载完成
      handleAuditOpinionDataLoaded() {
        // 数据加载完成后，关闭加载状态
        this.tabLoading.auditOpinion = false
      },
      // 表格行样式
      getRowClassName({ row }) {
        if (row.isCategoryHeader) {
          return 'category-header-row'
        }
        return ''
      },
      // 标签页切换
      handleTabClick(tab) {
        console.log(tab, 'qiehuan')

        if (tab.name === 'projectInfo') {
          // 立项项目信息
          this.getProjectInformation()
        } else if (tab.name === 'dataRequirements') {
          // 报送资料要求
          this.getTaskRequirementPage()
        } else if (tab.name === 'costSurvey') {
          // 成本调查表
          this.getCostSurveyList()
        } else if (tab.name === 'messageNotice') {
          // 消息通知
          this.getSendMessage()
        } else if (tab.name === 'auditOpinion') {
          // 监审意见标签页，设置加载状态并调用接口
          this.tabLoading.auditOpinion = true
          // 通过 ref 调用子组件方法，确保接口被调用
          this.$nextTick(() => {
            this.$nextTick(() => {
              const auditOpinionTab = this.$refs.auditOpinionTabRef
              if (
                auditOpinionTab &&
                typeof auditOpinionTab.getPreliminaryOpinionData === 'function'
              ) {
                auditOpinionTab.getPreliminaryOpinionData()
              } else {
                // 如果找不到组件，可能是组件还未创建，延迟调用
                setTimeout(() => {
                  const tab = this.$refs.auditOpinionTabRef
                  if (
                    tab &&
                    typeof tab.getPreliminaryOpinionData === 'function'
                  ) {
                    tab.getPreliminaryOpinionData()
                  } else {
                    this.tabLoading.auditOpinion = false
                  }
                }, 200)
              }
            })
          })
        } else if (tab.name === 'auditDocument') {
          // 监审文件
          this.getAuditDocumentList()
        }
        // 其他标签页（如 auditDocument、costSurvey）如果不需要异步加载数据，则不需要设置加载状态

        // 可添加标签页切换时的逻辑
        this.pageTitle = tab.label
      },
      // 获取立项项目信息
      getProjectInformation() {
        this.tabLoading.projectInfo = true
        getProjectInformationInfo(this.projectId)
          .then((res) => {
            console.log('立项项目信息', res)
            if (res && 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 }))
              }

              // 赋值并添加转换后的数组
              this.formData.basicInfo = {
                ...data,
                auditPeriodArray: auditPeriodArray,
              }
            }
          })
          .catch((err) => {
            console.error('获取立项项目信息失败', err)
          })
          .finally(() => {
            this.tabLoading.projectInfo = false
          })
      },
      // 获取报送资料要求列表
      getTaskRequirementPage() {
        this.tabLoading.dataRequirements = true
        console.log('送报资料接口', this.taskId)
        getTaskRequirementList(this.taskId)
          .then((res) => {
            console.log('报送资料要求', res)
            if (res && res.code === 200 && res.value) {
              this.formData.dataRequirements = Array.isArray(res.value)
                ? res.value
                : []
            } else {
              this.formData.dataRequirements = []
            }
          })
          .catch((err) => {
            console.error('获取报送资料失败', err)
            this.formData.dataRequirements = []
          })
          .finally(() => {
            this.tabLoading.dataRequirements = false
          })
      },
      // 消息通知
      getSendMessage() {
        this.tabLoading.messageNotice = true
        const params = {
          taskId: this.taskId,
          auditedUnitId: this.auditedUnitId,
          projectId: this.projectId,
          pageNum: this.messageNoticePagination.pageNo,
          pageSize: this.messageNoticePagination.pageSize,
        }
        sendMessage(params)
          .then((res) => {
            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
            }
          })
          .catch((err) => {
            console.error('获取消息通知失败', err)
            this.formData.messageNoticeData = []
            this.messageNoticePagination.total = 0
          })
          .finally(() => {
            this.tabLoading.messageNotice = false
          })
      },

      // 获取成本调查表列表
      getCostSurveyList() {
        this.tabLoading.costSurvey = true
        const params = {
          taskId: this.taskId || (this.taskInfo && this.taskInfo.taskId) || '',
          catalogId: this.taskInfo.catalogId,
          pageNum: this.costSurveyPagination.currentPage,
          pageSize: this.costSurveyPagination.pageSize,
          type: 1,
        }
        // if (this.auditedUnitId) params.auditedUnitId = this.auditedUnitId
        getSurveyList(params)
          .then((res) => {
            console.log('成本调查表列表', res)
            if (res && res.code === 200 && res.value) {
              // 处理返回的数据
              const records = res.value.records || res.value || []
              // 映射数据格式，转换为组件需要的格式
              const mappedData = records.map((item, index) => {
                // 转换表格类型：1=单记录，2=固定表，3=动态表
                let tableType = ''
                if (item.templateType === 1 || item.templateType === '1') {
                  tableType = '单记录'
                } else if (
                  item.templateType === 2 ||
                  item.templateType === '2'
                ) {
                  tableType = '固定表'
                } else if (
                  item.templateType === 3 ||
                  item.templateType === '3'
                ) {
                  tableType = '动态表'
                } else if (item.tableType) {
                  tableType = item.tableType
                }

                // 转换是否必填：0=否，1=是
                const isRequired =
                  item.isRequired === 1 || item.isRequired === '1' ? '是' : '否'

                // 转换是否上传：0=未上传，1=已上传
                const isUploaded = item.isUpload === 1 || item.isUpload === '1'

                return {
                  index: index + 1,
                  id: item.id,
                  name: item.surveyTemplateName || '',
                  dataType: item.dataType || '', // 资料类型
                  tableType: tableType, // 表格类型（转换后）
                  isRequired: isRequired, // 是否必填（转换后）
                  isUploaded: isUploaded, // 是否上传（转换后）
                  surveyTemplateId: item.surveyTemplateId || '', // 成本调查表模板ID
                  isDisabled: item.isDisabled || false,
                  fileUrl: item.fileUrl || '',
                  dataUrl: item.dataUrl || '',
                  templateUrl: item.templateUrl || '',
                  ...item, // 保留其他字段
                }
              })
              // 更新 costSurveyData（完整数据）
              this.formData.costSurveyData = mappedData
              console.log(
                'this.formData.costSurveyData',
                this.formData.costSurveyData
              )
              // 更新 paginatedData（用于传递给子组件，如果接口返回的是分页数据，直接使用；否则使用全部数据）
              this.formData.paginatedData = mappedData
              // 更新分页信息
              this.costSurveyPagination.total =
                res.value.total || mappedData.length || 0
            } else {
              this.formData.costSurveyData = []
              this.formData.paginatedData = []
              this.costSurveyPagination.total = 0
            }
          })
          .catch((err) => {
            console.error('获取成本调查表列表失败', err)
            this.formData.costSurveyData = []
            this.formData.paginatedData = []
            this.costSurveyPagination.total = 0
          })
          .finally(() => {
            this.tabLoading.costSurvey = false
          })
      },
      // 消息通知分页处理
      handleMessageNoticePageChange(pageNo) {
        this.messageNoticePagination.pageNo = pageNo
        this.getSendMessage()
      },
      // 消息通知每页大小变化
      handleMessageNoticeSizeChange(pageSize) {
        this.messageNoticePagination.pageSize = pageSize
        this.messageNoticePagination.pageNo = 1
        this.getSendMessage()
      },
      // 提交
      handleSubmit() {
        // 验证必填的报送资料（仅在 clcs 或 tjcl 节点时验证）
        // if (this.currentNode === 'clcs' || this.currentNode === 'tjcl') {
        //   // 验证报送资料必填项
        //   const requiredItems = this.formData.dataRequirements.filter(
        //     (item) => {
        //       // 只检查非类别标题行的数据项
        //       if (item.isCategoryHeader) {
        //         return false
        //       }
        //       // 只检查是否为必填项
        //       const isRequired =
        //         item.isRequired === '1' || item.isRequired === 1
        //       return isRequired
        //     }
        //   )

        //   if (requiredItems.length > 0) {
        //     // 获取必填项名称列表
        //     const itemNames = requiredItems
        //       .map((item) => item.informationName || '未命名资料')
        //       .join('、')
        //     Message.warning(
        //       `有必填数据必须先填完，请先完成以下报送资料：${itemNames}`
        //     )
        //     return
        //   }

        //   // 验证成本调查表必填项
        //   const requiredCostSurveys = this.formData.costSurveyData.filter(
        //     (item) => {
        //       // 只检查是否为必填项
        //       const isRequired =
        //         item.isRequired === '1' ||
        //         item.isRequired === 1 ||
        //         item.isRequired === '是'
        //       return isRequired
        //     }
        //   )

        //   if (requiredCostSurveys.length > 0) {
        //     // 获取必填项名称列表
        //     const itemNames = requiredCostSurveys
        //       .map((item) => item.name || '未命名调查表')
        //       .join('、')
        //     Message.warning(
        //       `有必填数据必须先填完，请先完成以下成本调查表：${itemNames}`
        //     )
        //     return
        //   }
        // }

        this.loading.submit = true

        // 判断是否为监审意见提交（currentNode === 'yjfk'）
        if (this.currentNode === 'yjfk') {
          // 企业监审意见提交
          // 处理文件列表，提取文件URL
          // let fileUrlList = []
          // if (this.formData.auditOpinion?.feedbackMaterials && Array.isArray(this.formData.auditOpinion.feedbackMaterials)) {
          //   fileUrlList = this.formData.auditOpinion.feedbackMaterials.map((file) => {
          //     // 如果file是字符串，直接返回
          //     if (typeof file === 'string') {
          //       return file
          //     }
          //     // 如果file是对象，提取url字段
          //     return file.url || file.response?.savePath || file.savePath || ''
          //   }).filter((url) => url) // 过滤空值
          // }

          const submitData = {
            taskId: this.taskId,
            id: this.formData.auditOpinion.id,
            // 成本监审意见数据
            basicSituation: this.formData.auditOpinion?.basicSituation || '',
            currentPriceStandard:
              this.formData.auditOpinion?.currentPriceStandard || '',
            costComposition: this.formData.auditOpinion?.costComposition || '',
            preliminaryOpinion:
              this.formData.auditOpinion?.preliminaryOpinion || '',
            // 被监审单位反馈意见数据
            feedbackOpinion: this.formData.auditOpinion?.feedbackOpinion || '',
            feedbackMaterials:
              this.formData.auditOpinion?.feedbackMaterials[0]?.url || '', // 附件URL
          }

          submitPreliminaryOpinion(submitData)
            .then((res) => {
              this.loading.submit = false
              console.log('企业监审意见提交成功', res)
              if (res && res.code === 200) {
                Message.success('提交成功')
                // 关闭弹窗
                this.handleBack()
                // 通知父组件刷新列表
                this.$emit('refresh')
              } else {
                Message.error(res?.message || '提交失败')
              }
            })
            .catch((err) => {
              this.loading.submit = false
              console.error('企业监审意见提交失败', err)
              // Message.error('提交失败：' + (err.message || '未知错误'))
            })
        } else {
          // 其他情况走原有逻辑
          setTimeout(() => {
            submitTaskRequirement({ taskId: this.taskId })
              .then((res) => {
                this.loading.submit = false
                console.log('提交成功', res)
                if (res && res.code === 200) {
                  Message.success('提交成功')
                  this.handleBack()
                  // 通知父组件刷新列表
                  this.$emit('refresh')
                } else {
                  Message.error('提交失败')
                }
              })
              .catch((err) => {
                this.loading.submit = false
                console.error('提交失败', err)
                // Message.error('提交失败')
              })
          }, 500)
        }
      },

      // 保存
      handleSave() {
        this.loading.save = true
        // 保存逻辑
        setTimeout(() => {
          this.loading.save = false
          Message.success('保存成功')
        }, 500)
      },

      // 返回
      handleBack() {
        this.drawerVisible = false
        this.$emit('close')
      },
      // 侧边弹窗关闭事件
      handleDrawerClose() {
        this.$emit('update:visible', false)
        this.$emit('close')
      },

      // 监审地区级联选择器
      handleChange(value) {
        console.log(value)
      },

      // 监审地区级联选择器节点点击
      handleNodeClick(data) {
        console.log(data)
        this.formData.basicInfo.projectName = data.label
      },
      // 获取监审文书
      getAuditDocumentList() {
        getCostProjectDocumentPageList({
          pageNum: this.auditDocumentPagination.page,
          pageSize: this.auditDocumentPagination.pageSize,
          projectId: this.projectId,
          documentName: '',
          permissionType: 1,
        }).then((res) => {
          this.formData.auditDocument = res.value.value.records
          this.auditDocumentPagination.total = res.value.value.total
        })
      },
      handleAuditDocumentPaginationChange(val) {
        this.auditDocumentPagination.page = val.pageNum
        this.auditDocumentPagination.pageSize = val.pageSize
        this.getAuditDocumentList()
      },
      handleClick(row) {},

      // 下载文书
      handleDownload(row) {
        console.log(row)
        if (!row.fileUrl) {
          this.$message.warning('该文书暂无文件可下载')
          return
        }
        this.downloadByFetch(row.fileUrl, row.name || '文书文件')
      },
      // 上传附件
      handleUpload(row) {
        console.log(row)
      },

      // 报送资料相关操作方法
      handleFileView(row) {
        console.log('查看文件:', row)
        // 实际开发中可添加文件预览逻辑（如打开新窗口、弹窗展示等）
        if (row.fileUrl) {
          window.open(row.fileUrl, '_blank')
        } else {
          this.$message.warning('暂无文件可查看')
        }
      },
      handleFileDownload(row) {
        console.log('下载文件:', row)
        if (!row.fileUrl) {
          this.$message.warning('该资料暂无文件可下载')
          return
        }
        this.downloadByFetch(row.fileUrl, row.informationName || '下载文件')
      },
      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.success('开始下载文件')
        } catch (e) {
          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 ''
      },
      // 报送资料文件上传
      async handleFileUpload(row, acceptFromChild) {
        // 预置模版：直接打开 CostAuditTable 弹窗选择模版
        const fmt = row && row.formatRequired
        const isTemplate =
          String(fmt) === '3' ||
          (typeof fmt === 'string' && fmt.toLowerCase().includes('模板'))
        if (isTemplate) {
          this.currentDataRequirementRow = row || null
          this.loadCostTemplates()
          this.selectedCostTemplates = []
          this.costAuditDialogVisible = true
          console.log('打开 CostAuditTable 弹窗选择模版')
          return
        }

        // 非预置模版：走本地文件上传
        // 创建文件选择器
        const input = document.createElement('input')
        input.type = 'file'
        input.accept =
          (typeof acceptFromChild === 'string' && acceptFromChild) ||
          '.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
            }

            // 显示上传加载提示
            const 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.code !== 200 || !uploadRes.value) {
              loading.close()
              this.$message.error('文件上传失败，请稍后重试')
              return
            }

            // 文件上传成功后，更新报送资料项
            const fileInfo = uploadRes.value
            const updateData = {
              // id: row.id,
              // taskId: this.taskId,
              // projectId: this.projectId,
              // informationType: row.informationType,
              // informationName: row.informationName,
              // informationRequire: row.informationRequire,
              // formatRequired: row.formatRequired,
              // isRequired: row.isRequired,
              ...row,
              fileUrl: fileInfo.savePath || fileInfo.url, // 更新文件URL
            }

            // 调用更新API
            const updateRes = await addOrUpdateTaskRequirement(updateData)

            loading.close()

            if (updateRes && updateRes.code === 200) {
              this.$message.success('文件上传并更新成功！')
              // 刷新报送资料列表
              this.getTaskRequirementPage()
            } else {
              this.$message.error('文件上传成功，但更新资料失败')
            }
          } catch (error) {
            console.error('文件上传失败:', error)
            // this.$message.error('操作失败：' + (error.message || '未知错误'))
          }
        }

        // 触发文件选择
        input.click()
      },
      handleTemplateDownload(row) {
        console.log('下载预置模版:', row)
        if (!row.templateUrl && !row.fileUrl) {
          this.$message.warning('该模版暂无文件可下载')
          return
        }

        const downloadUrl = row.templateUrl || row.fileUrl
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = downloadUrl
        link.download = row.name ? `${row.name}_模版` : '模版文件'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('开始下载模版')
      },
      handleDataUpload(row) {
        // 预置模版：打开 CostAuditTable 弹窗进行模板选择
        this.currentDataRequirementRow = row || null
        this.loadCostTemplates()
        this.selectedCostTemplates = []
        this.costAuditDialogVisible = true
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handlePreview(file) {
        console.log(file)
      },
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
            files.length + fileList.length
          } 个文件`
        )
      },
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`)
      },
      // 成本调查表点击事件（可点击时触发）
      handleSurveyClick(row) {
        console.log('点击成本调查表：', row.name)
        // 实际逻辑：跳转页面、打开弹窗等
      },
      // 在线填报
      handleOnlineFill(row) {
        console.log('在线填报：', row.name)
        this.currentSurveyData = row
        this.onlineFillDialogVisible = true
      },
      // 修改已上传的表
      handleModify(row) {
        console.log('修改：', row.name)
        // 实际逻辑：打开修改表单
      },
      // 数据下载
      handleDataDownload(row) {
        console.log('数据下载：', row.name)
        if (!row.fileUrl && !row.dataUrl) {
          this.$message.warning('该数据暂无文件可下载')
          return
        }

        const downloadUrl = row.dataUrl || row.fileUrl
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = downloadUrl
        link.download = row.name ? `${row.name}_数据` : '数据文件'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('开始下载数据')
      },

      // 补充材料相关方法
      handleAddMaterial() {
        this.materialDialogVisible = true
        this.resetMaterialForm()
      },

      // 重置补充材料表单
      resetMaterialForm() {
        this.materialForm = {
          informationType: '',
          informationName: '',
          informationRequire: '',
          formatRequired: '',
          fileList: [],
          fileUrl: '',
        }
        if (this.$refs.materialForm) {
          this.$refs.materialForm.resetFields()
        }
      },

      // 补充材料弹窗取消
      handleMaterialCancel() {
        this.materialDialogVisible = false
        this.resetMaterialForm()
      },

      // 补充材料弹窗确定
      handleMaterialSubmit() {
        this.$refs.materialForm.validate((valid) => {
          if (valid) {
            // 设置 loading 状态
            this.loading.materialSubmit = true
            // 这里可以添加提交逻辑
            console.log('补充材料表单数据:', this.materialForm)
            addOrUpdateTaskRequirement({
              taskId: this.taskId,
              projectId: this.projectId,
              informationType: this.materialForm.informationType,
              informationName: this.materialForm.informationName,
              informationRequire: this.materialForm.informationRequire,
              formatRequired: this.materialForm.formatRequired,
              fileUrl: this.materialForm.fileUrl,
              templateId: this.materialForm.templateId,
            })
              .then((res) => {
                console.log('补充材料提交成功', res)
                if (res && res.code === 200) {
                  this.loading.materialSubmit = false
                  Message.success('补充材料提交成功')
                  this.materialDialogVisible = false
                  this.resetMaterialForm()
                  this.getTaskRequirementPage()
                } else {
                  Message.error('补充材料提交失败')
                }
              })
              .catch((err) => {
                console.error('补充材料提交失败', err)
                Message.error('补充材料提交失败')
              })
              .finally(() => {
                // 重置 loading 状态
                this.loading.materialSubmit = false
              })
          } else {
            Message.error('请完善表单信息')
            return false
          }
        })
      },

      // 上传
      // handleMaterialUpload(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
      //       // 创建更新数据对象
      //       const updateData = {
      //         ...row,
      //         fileUrl: fileInfo?.savePath, // 更新扫描件URL
      //       }

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

      //       // // 第七步：更新成功，显示提示并刷新
      //       // this.$message.success('文件上传成功并更新数据！')
      //       // this.$emit('refresh', this.project.projectId) // 通知父组件刷新
      //     } catch (error) {
      //       // 错误处理
      //       this.$message.error('操作失败：' + (error.message || '未知错误'))
      //     } finally {
      //       // 关闭遮罩层
      //       loading.close()
      //     }
      //   }
      //   // 触发文件选择
      //   input.click()
      // },

      // 文件上传前验证
      beforeMaterialUpload(file) {
        // 预置模版不允许在此上传
        if (this.isTemplateFormat) {
          this.$message.warning(
            '“预置模版”不支持直接上传，请按模版入口添加材料'
          )
          return false
        }

        const ext = '.' + file.name.split('.').pop().toLowerCase()
        const mime = (file.type || '').toLowerCase()

        // 文档格式
        if (this.isDocumentFormat) {
          const allowedExt = ['.pdf', '.doc', '.docx']
          const allowedMime = [
            'application/pdf',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          ]
          const ok = allowedExt.includes(ext) || allowedMime.includes(mime)
          if (!ok) {
            this.$message.error('当前格式要求为文档，仅支持 pdf, doc, docx')
            return false
          }
        }

        // Excel 格式
        if (this.isExcelFormat) {
          const allowedExt = ['.xls', '.xlsx']
          const allowedMime = [
            'application/vnd.ms-excel',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          ]
          const ok = allowedExt.includes(ext) || allowedMime.includes(mime)
          if (!ok) {
            this.$message.error('当前格式要求为表格，仅支持 xls, xlsx')
            return false
          }
        }

        // 检查文件大小 (50MB)
        const isLt50M = file.size / 1024 / 1024 < 50
        if (!isLt50M) {
          this.$message.error('文件大小不能超过 50MB!')
          return false
        }

        return true
      },

      // 自定义上传方法
      async handleMaterialUpload(options) {
        const { file, onProgress, onSuccess, onError } = options

        // 检查是否已经上传了文件
        if (
          this.materialForm.fileList &&
          this.materialForm.fileList.length >= 1
        ) {
          this.$message.warning('只能上传一个文件，请先删除已上传的文件')
          // 手动触发onError回调
          if (onError) {
            onError(new Error('只能上传一个文件'))
          }
          return
        }

        const formData = new FormData()
        formData.append('file', file)

        try {
          // 显示上传进度
          if (onProgress) {
            onProgress({ percent: 0 })
          }

          // 调用上传API
          const uploadRes = await uploadFile('/api/file/v1/upload', formData, {
            onUploadProgress: (progressEvent) => {
              // 计算上传进度
              if (progressEvent.total) {
                const percent = Math.round(
                  (progressEvent.loaded * 100) / progressEvent.total
                )
                if (onProgress) {
                  onProgress({ percent })
                }
              }
            },
          })

          // 检查上传结果
          if (uploadRes && uploadRes.code === 200 && uploadRes.value) {
            const fileInfo = uploadRes.value
            // 构造文件信息对象，符合element-ui upload组件的格式
            const fileObj = {
              uid: file.uid,
              name: file.name,
              status: 'success',
              size: file.size,
              response: fileInfo,
              url: fileInfo.savePath || fileInfo.url,
            }

            if (onSuccess) {
              onSuccess(fileInfo, fileObj)
              this.materialForm.fileUrl = fileInfo.savePath || fileInfo.url
            }

            this.$message.success(`${file.name} 上传成功`)
          } else {
            throw new Error(uploadRes?.message || '上传失败，请稍后重试')
          }
        } catch (error) {
          console.error('文件上传失败:', error)
          this.$message.error(`文件上传失败：${error.message || '未知错误'}`)
          if (onError) {
            onError(error)
          }
        }
      },

      // 打开预置模版弹窗
      openLegalDialog() {
        // 需求：改用 CostAuditTable 弹窗选择模版
        this.loadCostTemplates()
        this.selectedCostTemplates = []
        this.costAuditDialogVisible = true
        console.log(
          '打开 CostAuditTable 弹窗选择模版',
          this.costAuditDialogVisible
        )
      },
      // 接收模版弹窗选择结果
      handleLegalConfirm(payload) {
        // 兼容不同返回字段，将关键信息落到表单中
        const url =
          payload?.templateUrl ||
          payload?.url ||
          payload?.savePath ||
          payload?.fileUrl ||
          ''
        if (url) {
          // 将选中的模版链接记录在fileUrl，后端若有专属字段可按需调整
          this.materialForm.fileUrl = url
          // 在UI上体现已选择（以文件列表形式展示一个只读项）
          this.materialForm.fileList = [
            {
              uid: 'tpl-' + Date.now(),
              name: payload?.name || payload?.templateName || '已选择的模版',
              status: 'success',
              url: url,
              response: payload,
            },
          ]
          this.$message.success('已选择模版')
        } else {
          this.$message.info('未获取到模版链接')
        }
        this.legalDialogVisible = false
      },

      // 拉取模板列表（CostAuditTable用）
      loadCostTemplates() {
        allcurrentCostSurveyList({
          pageNum: this.costTemplatePagination.currentPage,
          pageSize: this.costTemplatePagination.pageSize,
        }).then((res) => {
          this.costTemplateData = res?.value?.records || res?.value || []
          this.costTemplatePagination.total =
            res?.value?.total || this.costTemplateData.length || 0
        })
      },
      handleCostTemplatePaginationChange({ currentPage, pageSize }) {
        this.costTemplatePagination.currentPage = currentPage
        this.costTemplatePagination.pageSize = pageSize
        this.loadCostTemplates()
      },
      handleCostTemplateSelectionChange(val) {
        if (Array.isArray(val) && val.length > 1) {
          this.$message.warning('最多只能选择一个模板')
          return
        }
        this.selectedCostTemplates = val || []
      },
      submitCostAuditTemplate() {
        if (
          !this.selectedCostTemplates ||
          this.selectedCostTemplates.length !== 1
        ) {
          this.$message.error('请选择一个模板')
          return
        }
        const chosen = this.selectedCostTemplates[0]
        const url = chosen?.templateUrl || chosen?.url || chosen?.savePath || ''
        // 记录到表单
        this.materialForm.fileUrl = url
        this.materialForm.templateId =
          chosen?.surveyTemplateId || chosen?.templateId || chosen?.id || ''
        this.materialForm.fileList = [
          {
            uid: 'tpl-' + Date.now(),
            name: chosen?.surveyTemplateName || '已选择的模版',
            status: 'success',
            url: url,
            response: chosen,
          },
        ]
        this.$message.success('已选择模版')
        this.costAuditDialogVisible = false
      },

      // 上传成功回调
      handleMaterialUploadSuccess(response, file, fileList) {
        // 更新文件列表，添加文件URL信息
        this.materialForm.fileList = fileList.map((item) => {
          if (item.uid === file.uid && response) {
            return {
              ...item,
              url: response.savePath || response.url || item.url,
              response: response,
            }
          }
          return item
        })
      },

      // 上传进度回调
      handleMaterialUploadProgress(event, file, fileList) {
        // 可以在这里显示上传进度，element-ui 会自动处理
      },

      // 上传失败回调
      handleMaterialUploadError(err, file, fileList) {
        console.error('文件上传错误:', err)
        this.$message.error(`${file.name} 上传失败`)
        // 从文件列表中移除失败的文件
        this.materialForm.fileList = fileList.filter(
          (item) => item.uid !== file.uid
        )
      },

      // 超出文件数量限制
      handleMaterialExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${fileList.length} 个文件`
        )
      },

      // 移除文件
      handleMaterialRemove(file, fileList) {
        this.materialForm.fileList = fileList
        this.$message.info(`${file.name} 已移除`)
      },

      // 成本调查表分页 - 页码改变
      handleCostSurveyPageChange(page) {
        this.costSurveyPagination.currentPage = page
        // 调用接口重新获取数据
        this.getCostSurveyList()
      },

      // 成本调查表分页 - 每页条数改变
      handleCostSurveySizeChange(size) {
        this.costSurveyPagination.pageSize = size
        this.costSurveyPagination.currentPage = 1
        // 调用接口重新获取数据
        this.getCostSurveyList()
      },

      // 处理单记录调查表保存
      handleSurveyFormSave(data) {
        // 保存成功后刷新列表
        this.getCostSurveyList()
      },

      // 获取监审期间数组（从立项信息中获取）
      getAuditPeriodArray() {
        // 优先从 formData.basicInfo.auditPeriodArray 获取
        if (
          this.formData &&
          this.formData.basicInfo &&
          this.formData.basicInfo.auditPeriodArray &&
          Array.isArray(this.formData.basicInfo.auditPeriodArray)
        ) {
          const periods = this.formData.basicInfo.auditPeriodArray
            .map((item) => item.value)
            .filter((val) => val && val.trim())
          if (periods.length > 0) {
            return periods
          }
        }
        // 其次从 taskInfo.auditPeriod 获取
        if (this.taskInfo && this.taskInfo.auditPeriod) {
          if (Array.isArray(this.taskInfo.auditPeriod)) {
            return this.taskInfo.auditPeriod
          } else if (typeof this.taskInfo.auditPeriod === 'string') {
            // 如果是字符串，尝试解析
            return this.taskInfo.auditPeriod
              .split(',')
              .map((p) => p.trim())
              .filter((p) => p)
          }
        }
        // 最后从 formData.basicInfo.auditPeriod 获取
        if (
          this.formData &&
          this.formData.basicInfo &&
          this.formData.basicInfo.auditPeriod
        ) {
          if (Array.isArray(this.formData.basicInfo.auditPeriod)) {
            return this.formData.basicInfo.auditPeriod
          } else if (typeof this.formData.basicInfo.auditPeriod === 'string') {
            return this.formData.basicInfo.auditPeriod
              .split(',')
              .map((p) => p.trim())
              .filter((p) => p)
          }
        }
        return null
      },
    },
  }
</script>
<style scoped lang="scss">
  .drawer-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
  }

  .audit-task-manage-container {
    padding: 20px;
    height: 100%;
    overflow-y: auto;

    h3 {
      text-align: center;
      margin-top: 0;
      margin-bottom: 20px;
      font-size: 18px;
      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;
    align-items: center;

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

  .file-info {
    margin-bottom: 10px;
  }

  .file-info a {
    color: #0066cc;
    text-decoration: none;
  }

  .file-info a:hover {
    text-decoration: underline;
  }

  .upload-btn {
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    cursor: pointer;
  }

  .upload-btn:hover {
    background-color: #0056b3;
  }

  .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;
  }

  .ml10 {
    margin-left: 10px;
  }

  .text-danger {
    color: #d9001b;
  }

  // 类别头行样式
  ::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;
  }

  // 侧边弹窗样式优化
  ::v-deep .el-drawer__body {
    overflow-y: auto;
    padding: 0;
  }

  ::v-deep .el-drawer__header {
    margin-bottom: 0;
    padding: 20px;
    border-bottom: 1px solid #e4e7ed;
  }

  ::v-deep .el-drawer__body {
    padding: 0;
  }
  .document-edit-container {
    display: flex;
    .document-params {
      width: 55%;
    }
    .document-preview {
      width: 45%;
    }
  }
</style>
