<template>
  <div class="audit-task-manage-container" style="padding: 20px">
    <!-- 页面标题 -->
    <div class="page-header">
      <!-- <h2>{{ pageTitle }}</h2> -->
    </div>

    <!-- 操作按钮 -->
    <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 class="tabs-container">
      <el-tabs
        v-model="activeTab"
        type="border-card"
        @tab-click="handleTabClick"
      >
        <!-- 立项信息 -->
        <el-tab-pane label="立项信息" name="projectInfo">
          <el-form
            :model="formData.basicInfo"
            label-width="180px"
            :disabled="true"
          >
            <el-form-item label="成本监审项目名称：">
              <el-input
                v-model="formData.basicInfo.projectName"
                placeholder="请输入成本监审项目名称"
                style="width: 400px"
                :disabled="isViewMode"
              ></el-input>
            </el-form-item>
            <el-form-item label="关联成本监审目录：">
              <CatalogCascader
                ref="catalogCascader"
                :form-item="{ placeholder: '请选择监审目录' }"
                style="width: 100%"
                :value="formData.basicInfo.catalogId"
                :disabled="isViewMode"
                @change="handleCatalogChange"
              />
            </el-form-item>
            <el-form-item label="监审地区：">
              <RegionSelector
                :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"
                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%"
                      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 || true"
                      @click="deleteCostYear(index)"
                    >
                      删除
                    </el-button>
                  </div>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="是否参加听证：">
              <el-radio-group
                v-model="formData.basicInfo.needHearing"
                :disabled="isViewMode"
              >
                <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"
                :disabled="isViewMode"
              >
                <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"
                placeholder="请输入立项理由"
                :disabled="isViewMode"
              ></el-input>
            </el-form-item>
            <el-form-item label="监审任务负责人：">
              <el-select
                v-model="formData.basicInfo.auditGroup"
                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.auditTeamMembers"
                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"
                placeholder="请输入其他专家"
                style="width: 100%"
                :disabled="isViewMode"
              ></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>
        </el-tab-pane>

        <!-- 监审文书 -->
        <el-tab-pane label="监审文书" name="auditDocument">
          <div style="font-size: 18px">
            <strong>说明：</strong>
            被监审单位接收《送达回证》后需签名并反馈监审主体。
          </div>
          <el-table
            style="width: 100%; margin-top: 20px"
            border
            :data="formData.auditDocument"
          >
            <el-table-column prop="id" label="序号" width="120" align="center">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="文书类型"
              min-width="150"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="province"
              label="文书文号"
              min-width="230"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="city"
              label="推送时间"
              min-width="230"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="address"
              label="文书操作"
              min-width="150"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  :disabled="isViewMode"
                  @click="handleClick(scope.row)"
                >
                  查看
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  :disabled="isViewMode"
                  @click="handleDownload(scope.row)"
                >
                  下载
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              prop="zip"
              label="向监审主体反馈文件"
              min-width="200"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  :disabled="isViewMode"
                  @click="handleUpload(scope.row)"
                >
                  上传附件
                </el-button>
                <el-button
                  type="text"
                  size="small"
                  :disabled="isViewMode"
                  @click="handleClick(scope.row)"
                >
                  查看附件
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 报送资料 -->
        <!-- <el-tab-pane label="报送资料" name="dataRequirements"></el-tab-pane> -->
        <el-tab-pane label="报送资料" name="dataRequirements">
          <el-button
            type="primary"
            :disabled="isViewMode"
            @click="handleAddMaterial"
          >
            补充材料
          </el-button>
          <el-table
            style="margin-top: 20px"
            border
            :data="groupedDataRequirements"
            size="mini"
            :show-header="true"
            :row-class-name="getRowClassName"
          >
            <el-table-column prop="seq" label="序号" width="80" align="center">
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategoryHeader">
                  {{ scope.row.seq || scope.row.index }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="informationName"
              label="报送资料"
              min-width="280"
            >
              <template slot-scope="scope">
                <div
                  v-if="scope.row.isCategoryHeader"
                  class="category-header-cell"
                >
                  {{ scope.row.categoryName }}
                </div>
                <span v-else>{{ scope.row.informationName || '-' }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="formatRequired"
              label="资料类型"
              width="130"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategoryHeader">
                  <span
                    v-if="
                      scope.row.formatRequired !== null &&
                      scope.row.formatRequired !== undefined
                    "
                  >
                    {{
                      getDictName(
                        'formatAsk',
                        String(scope.row.formatRequired)
                      ) || scope.row.formatRequired
                    }}
                  </span>
                  <span v-else>-</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">
                  {{ scope.row.isRequired === '1' ? '是' : '否' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="isUploaded"
              label="是否上传"
              width="110"
              align="center"
            >
              <template slot-scope="scope">
                <span v-if="!scope.row.isCategoryHeader">
                  <span v-if="scope.row.isUploaded === true">已上传</span>
                  <span v-else class="text-danger">未上传</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
                      type="text"
                      size="small"
                      :disabled="isViewMode"
                      @click="handleFileView(scope.row)"
                    >
                      查看
                    </el-button>
                    <el-button
                      type="text"
                      size="small"
                      :disabled="isViewMode"
                      @click="handleFileDownload(scope.row)"
                    >
                      下载
                    </el-button>
                    <el-button
                      v-if="scope.row.isUploaded === false"
                      type="text"
                      size="small"
                      :disabled="isViewMode"
                      @click="handleFileUpload(scope.row)"
                    >
                      上传
                    </el-button>
                  </template>
                  <template v-if="scope.row.formatRequired == '3'">
                    <el-button
                      type="text"
                      size="small"
                      :disabled="isViewMode"
                      @click="handleTemplateDownload(scope.row)"
                    >
                      模版下载
                    </el-button>
                    <el-button
                      v-if="scope.row.isUploaded === false"
                      type="text"
                      size="small"
                      :disabled="isViewMode"
                      @click="handleDataUpload(scope.row)"
                    >
                      数据上传
                    </el-button>
                    <!-- <template v-else>
                      <el-button
                        type="text"
                        size="small"
                        @click="handleFileUpload(scope.row)"
                      >
                        上传
                      </el-button>
                    </template> -->
                  </template>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 成本调查表 -->
        <el-tab-pane label="成本调查表" name="costSurvey">
          <el-table
            style="width: 100%; margin-top: 20px"
            :data="paginatedCostSurveyData"
            border
            size="medium"
          >
            <!-- 序号列 -->
            <el-table-column
              prop="index"
              label="序号"
              width="60"
              align="center"
            ></el-table-column>
            <el-table-column label="成本调查表" min-width="220">
              <template slot-scope="scope">
                <span
                  :style="{
                    color: scope.row.isDisabled ? '#909399' : '#409EFF',
                    cursor: scope.row.isDisabled ? 'default' : 'pointer',
                  }"
                  @click="!scope.row.isDisabled && handleSurveyClick(scope.row)"
                >
                  {{ 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.isUploaded === true ? '#67c23a' : '#f56c6c',
                  }"
                >
                  {{ scope.row.isUploaded === true ? '已上传' : '未上传' }}
                </span>
              </template>
            </el-table-column>

            <!-- 操作列（根据“是否上传”“表格类型”显示不同按钮） -->
            <el-table-column label="操作" width="280" align="center">
              <template slot-scope="scope">
                <template v-if="scope.row.isUploaded">
                  <el-button
                    type="text"
                    size="small"
                    :disabled="isViewMode"
                    @click="handleModify(scope.row)"
                  >
                    修改
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    :disabled="isViewMode"
                    @click="handleDataDownload(scope.row)"
                  >
                    数据下载
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    :disabled="isViewMode"
                    @click="handleDataUpload(scope.row)"
                  >
                    数据上传
                  </el-button>
                </template>
                <template v-else>
                  <el-button
                    type="text"
                    size="small"
                    :disabled="isViewMode"
                    @click="handleOnlineFill(scope.row)"
                  >
                    在线填报
                  </el-button>
                  <el-button
                    v-if="scope.row.tableType === '动态表'"
                    type="text"
                    size="small"
                    :disabled="isViewMode"
                    @click="handleTemplateDownload(scope.row)"
                  >
                    模版下载
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    :disabled="isViewMode"
                    @click="handleDataUpload(scope.row)"
                  >
                    数据上传
                  </el-button>
                </template>
              </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"
          />
        </el-tab-pane>

        <!-- 监审意见 -->
        <el-tab-pane v-if="tabVisiable" label="监审意见" name="auditOpinion">
          <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="isViewMode"
                />
              </div>
              <div class="opinion-item">
                <label>监审项目现行执行的价格标准</label>
                <el-input
                  v-model="formData.auditOpinion.priceStandard"
                  type="textarea"
                  rows="5"
                  :disabled="isViewMode"
                />
              </div>
              <div class="opinion-item">
                <label>监审项目的成本构成、数据核增核减情况、依据及理由</label>
                <el-input
                  v-model="formData.auditOpinion.costComposition"
                  type="textarea"
                  rows="5"
                  :disabled="isViewMode"
                />
              </div>
              <div class="opinion-item">
                <label>成本审核初步意见</label>
                <el-input
                  v-model="formData.auditOpinion.preliminaryOpinion"
                  type="textarea"
                  rows="5"
                  :disabled="isViewMode"
                />
              </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="isViewMode"
                />
              </div>
              <div class="feedback-item">
                <label>被监审单位反馈资料</label>
                <div
                  style="
                    border: 1px solid #e9e9e9;
                    border-radius: 10px;
                    padding: 20px 10px;
                    width: 100%;
                  "
                >
                  <el-upload
                    class="upload-demo"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :on-preview="handlePreview"
                    :on-remove="handleRemove"
                    :before-remove="beforeRemove"
                    multiple
                    :limit="1"
                    :on-exceed="handleExceed"
                    :file-list="formData.auditOpinion.fileList"
                  >
                    <el-button size="small" type="text" :disabled="isViewMode">
                      上传附件
                    </el-button>
                  </el-upload>
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 消息通知 -->
        <el-tab-pane label="消息通知" name="messageNotice">
          <el-table
            style="width: 100%; margin-top: 20px"
            border
            :data="formData.messageNoticeData"
          >
            <el-table-column prop="id" label="序号" width="120" 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="230"
              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"
          />
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 补充材料弹窗 -->
    <el-dialog
      title="补充材料"
      :visible.sync="materialDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <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"
          >
            <el-button
              v-show="
                !materialForm.fileList || materialForm.fileList.length === 0
              "
              size="small"
              type="primary"
              :disabled="isViewMode"
            >
              选择文件
            </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"
          :disabled="isViewMode"
          @click="handleMaterialSubmit"
        >
          保 存
        </el-button>
        <el-button :disabled="isViewMode" @click="handleMaterialCancel">
          取 消
        </el-button>
      </div>
    </el-dialog>

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

<script>
  import { Message } from 'element-ui'
  import OnlineFillDialog from './OnlineFill.vue'
  import {
    getProjectInformationInfo,
    getTaskRequirementList,
    addOrUpdateTaskRequirement,
    submitTaskRequirement,
    sendMessage,
  } from '@/api/auditTaskProcessing'
  import RegionSelector from '@/views/costAudit/projectInfo/auditProjectManage/annualReviewPlan/RegionSelector.vue'
  import CatalogCascader from '@/views/costAudit/projectInfo/auditProjectManage/annualReviewPlan/CatalogCascader.vue'
  // 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'

  export default {
    name: 'TaskFillIn',
    components: {
      OnlineFillDialog,
      RegionSelector,
      CatalogCascader,
      // UploadComponent,
    },
    mixins: [dictMixin],
    data() {
      return {
        isViewMode: false, // 是否为查看模式
        unitList: [],
        OrgList: [],
        userList: [],
        dictData: {
          attributionYear: [], // 归属年度
          projectProposal: [], // 立项来源
          auditType: [], //监审形式
          materialType: [], // 资料类别
          materialCategory: [], // 资料类别
          formatAsk: [], // 资料类型
        },
        // 立项依据文件列表
        accordingFileList: [],
        // 其他材料文件列表
        otherFileList: [],
        // 页面标题
        pageTitle: '立项信息',
        projectId: '', // 项目ID
        taskId: '', // 任务ID
        // 当前激活的标签页
        activeTab: 'projectInfo',
        // 加载状态管理
        loading: {
          submit: false,
          save: false,
        },
        isDisabled: false,
        tabCheck: '', // 状态判断监审意见是否显示
        tabVisiable: true, // 标签页是否显示
        // 成本调查表分页相关
        costSurveyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 消息通知分页相关
        messageNoticePagination: {
          currentPage: 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: [
            {
              date: '2016-05-02',
              name: '王小虎',
              province: '上海',
              city: '普陀区',
              address: '上海市普陀区金沙江路 1518 弄',
              zip: 200333,
            },
            {
              date: '2016-05-04',
              name: '王小虎',
              province: '上海',
              city: '普陀区',
              address: '上海市普陀区金沙江路 1517 弄',
              zip: 200333,
            },
          ],
          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: '此处为成本审核初步意见的内容...',
            enterpriseFeedback: '', // 被监审单位可输入反馈意见
            fileList: [], // 被监审单位上传的反馈文件
          },
          messageNotice: {},
        },
        // 监审地区级联选择器
        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',
        },
        messageNoticeData: [],
        // 补充材料弹窗相关数据
        materialDialogVisible: false,
        materialForm: {
          informationType: '',
          informationName: '',
          informationRequire: '',
          formatRequired: '',
          fileList: [],
          fileUrl: '',
        },
        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,
      }
    },
    computed: {
      // 按类别分组的报送资料列表
      groupedDataRequirements() {
        if (
          !this.formData.dataRequirements ||
          !Array.isArray(this.formData.dataRequirements) ||
          this.formData.dataRequirements.length === 0
        ) {
          return []
        }

        // 按类别分组
        const groups = {}
        this.formData.dataRequirements.forEach((item, index) => {
          // 获取类别标识，使用 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)
      },
    },
    mounted() {
      this.getAllUnitList()
      this.getDefaultDem()
      this.getUser()
      // 从路由参数中获取 formType
      console.log('路由参数', this.$route.query)
      // 判断是否为查看模式
      this.isViewMode =
        this.$route.query.viewMode === true ||
        this.$route.query.viewMode === 'true'
      this.projectId = this.$route.query.info.projectId
      this.taskId = this.$route.query.info.userTask.id
      this.tabCheck = this.$route.query.info.status
      if (this.tabCheck === 'jtsy') {
        this.tabVisiable = false
      }
      const formType = this.$route.query.formTypeconst
      if (formType) {
        // 如果有 formType，将 activeTab 设置为 formType
        this.activeTab = formType
        // 更新页面标题
        this.pageTitle = '消息通知'
      } else {
        this.getProjectInformation()
      }
      // 初始化成本调查表分页总数
      this.costSurveyPagination.total = this.formData.costSurveyData.length
    },
    methods: {
      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
      },
      // 表格行样式
      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 === 'messageNotice') {
          this.getSendMessage() // 消息通知
        }
        // 可添加标签页切换时的逻辑
        this.pageTitle = tab.label
      },
      // 获取立项项目信息
      getProjectInformation() {
        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,
            }
          }
        })
      },
      // 获取报送资料要求列表
      getTaskRequirementPage() {
        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 = []
          })
      },
      // 消息通知
      getSendMessage() {
        const params = {
          taskId: this.taskId,
          currentPage: this.messageNoticePagination.currentPage,
          pageSize: this.messageNoticePagination.pageSize,
        }
        sendMessage(params)
          .then((res) => {
            console.log('消息通知', res)
            if (res && res.code === 200 && res.value && res.value.value) {
              this.formData.messageNoticeData = res.value.value.records || []
              this.messageNoticePagination.total = res.value.value.total || 0
            } else {
              this.formData.messageNoticeData = []
              this.messageNoticePagination.total = 0
            }
          })
          .catch((err) => {
            console.error('获取消息通知失败', err)
            this.formData.messageNoticeData = []
            this.messageNoticePagination.total = 0
          })
      },

      // 提交
      handleSubmit() {
        this.loading.submit = true
        // 保存逻辑
        setTimeout(() => {
          submitTaskRequirement({ taskId: this.taskId })
            .then((res) => {
              this.loading.submit = false
              console.log('提交成功', res)
              if (res && res.code === 200) {
                Message.success('提交成功')
                this.handleBack()
              } else {
                Message.error('提交失败')
              }
            })
            .catch((err) => {
              console.error('提交失败', err)
              Message.error('提交失败')
            })
        }, 500)
      },

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

      // 返回
      handleBack() {
        this.$router.back()
      },

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

      // 监审地区级联选择器节点点击
      handleNodeClick(data) {
        console.log(data)
        this.formData.basicInfo.projectName = data.label
      },

      // 查看文书
      handleClick(row) {
        console.log(row)
        if (row.fileUrl) {
          window.open(row.fileUrl, '_blank')
        } else {
          this.$message.warning('暂无文件可查看')
        }
      },
      // 下载文书
      handleDownload(row) {
        console.log(row)
        if (!row.fileUrl) {
          this.$message.warning('该文书暂无文件可下载')
          return
        }

        // 创建隐藏的a标签进行下载
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = row.fileUrl
        // 设置下载文件名
        link.download = row.name || '文书文件'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('开始下载文件')
      },
      // 上传附件
      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
        }

        // 创建隐藏的a标签进行下载
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = row.fileUrl
        // 设置下载文件名，优先使用资料名称
        link.download = row.informationName || '下载文件'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)

        this.$message.success('开始下载文件')
      },
      // 报送资料文件上传
      async handleFileUpload(row) {
        // 创建文件选择器
        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
            }

            // 显示上传加载提示
            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) {
        console.log('上传模版数据:', row)
        // 实际开发中可添加基于模版的数据上传逻辑
      },
      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) {
            // 这里可以添加提交逻辑
            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,
            })
              .then((res) => {
                console.log('补充材料提交成功', res)
                if (res && res.code === 200) {
                  Message.success('补充材料提交成功')
                  this.materialDialogVisible = false
                  this.resetMaterialForm()
                  this.getTaskRequirementPage()
                } else {
                  Message.error('补充材料提交失败')
                }
              })
              .catch((err) => {
                console.error('补充材料提交失败', err)
                Message.error('补充材料提交失败')
              })
          } 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) {
        const allowedTypes = [
          'application/pdf',
          'application/msword',
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
          'application/vnd.ms-excel',
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'text/csv',
        ]

        const allowedExtensions = [
          '.pdf',
          '.doc',
          '.docx',
          '.xls',
          '.xlsx',
          '.csv',
        ]
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase()

        // 检查文件格式
        const isCorrectType = allowedTypes.includes(file.type)
        const isCorrectExtension = allowedExtensions.includes(fileExtension)

        if (!isCorrectType && !isCorrectExtension) {
          this.$message.error(
            '只允许上传 pdf, doc, docx, xls, xlsx, csv 格式的文件！'
          )
          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)
          }
        }
      },

      // 上传成功回调
      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
        // 如果成本调查表数据来自API，可以在这里调用API
        // this.getCostSurveyData()
      },

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

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

      // 消息通知分页 - 每页条数改变
      handleMessageNoticeSizeChange(size) {
        this.messageNoticePagination.pageSize = size
        this.messageNoticePagination.currentPage = 1
        this.getSendMessage()
      },
    },
  }
</script>
<style scoped lang="scss">
  .cost-supervision-container {
    width: 80%;
    margin-top: 20px;

    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;
  }
</style>
