<template>
  <div class="catalog-manage-container">
    <!-- 列表视图 -->
    <div v-if="!showInfoMaintain" class="list-view">
      <div class="search-panel">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="目录类别:">
            <el-select
              v-model="searchForm.categoryId"
              placeholder="请选择目录类别"
              clearable
              filterable
            >
              <el-option
                v-for="item in catalogNmaes"
                :key="item.catalogId"
                :label="item.catalogName"
                :value="item.catalogId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="监审形式:">
            <el-select
              v-model="searchForm.auditType"
              placeholder="请选择监审形式"
              clearable
            >
              <el-option
                v-for="item in dictData['auditType']"
                :key="item.id"
                :label="item.name"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="监审内容:">
            <el-input
              v-model="searchForm.catalogName"
              placeholder="请输入监审内容"
              clearable
            ></el-input>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="fetchData">
              搜索
            </el-button>
            <el-button
              plain
              type="primary"
              icon="el-icon-refresh"
              @click="handleReset"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="operation-bar">
        <el-button
          plain
          type="success"
          icon="el-icon-circle-plus"
          @click="handleAdd()"
        >
          添加类别
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
        :row-class-name="getRowClassName"
      >
        <el-table-column
          prop="name"
          label="成本监审目录"
          show-overflow-tooltip
          header-align="center"
          align="left"
          min-width="200"
        >
          <template slot-scope="scope">
            <span
              class="link-text"
              :class="{ 'disabled-text': scope.row.status == 0 }"
              @click="handleViewDetail(scope.row)"
            >
              {{ scope.row.catalogName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="code"
          label="目录编码"
          show-overflow-tooltip
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <span :class="{ 'disabled-text': scope.row.status == 0 }">
              {{ scope.row.code }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="nodeType"
          label="nodeType"
          show-overflow-tooltip
          align="center"
          width="120"
        >
          <template slot-scope="scope">
            <span :class="{ 'disabled-text': scope.row.status == 0 }">
              {{ scope.row.nodeType }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="auditType"
          label="成本监审形式"
          show-overflow-tooltip
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            <span :class="{ 'disabled-text': scope.row.status == 0 }">
              {{ getDictName('auditType', scope.row.auditType) }}
            </span>
          </template>
        </el-table-column>
        <!-- <el-table-column
          prop="keyword"
          label="监审内容"
          show-overflow-tooltip
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            <span :class="{ 'disabled-text': scope.row.status == 0 }">
              {{ scope.row.catalogName }}
            </span>
          </template>
        </el-table-column> -->
        <el-table-column
          prop="pricingDept"
          label="定价部门"
          show-overflow-tooltip
          align="center"
          width="150"
        >
          <template slot-scope="scope">
            <span :class="{ 'disabled-text': scope.row.status == 0 }">
              {{ scope.row.pricingDept }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="remark"
          label="备注"
          header-align="center"
          show-overflow-tooltip
          align="left"
          width="150"
        >
          <template slot-scope="scope">
            <span :class="{ 'disabled-text': scope.row.status == 0 }">
              {{ scope.row.remark }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="status"
          label="状态"
          show-overflow-tooltip
          align="center"
          width="100"
        >
          <template slot-scope="scope">
            <span :class="{ 'disabled-text': scope.row.status == 0 }">
              {{ scope.row.status == 0 ? '停用' : '启用' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="360" fixed="right" align="center">
          <template slot-scope="scope">
            <div>
              <el-button
                v-if="scope.row.status != 0 && scope.row.nodeType !== 'nr'"
                type="text"
                size="mini"
                @click="handleEdit(scope.row)"
              >
                修改类别
              </el-button>
              <el-button
                v-if="scope.row.status != 0 && scope.row.nodeType !== 'nr'"
                type="text"
                size="mini"
                @click="handleAddChild(scope.row)"
              >
                添加子类
              </el-button>
              <el-button
                v-if="
                  !scope.row.auditType &&
                  scope.row.status != 0 &&
                  scope.row.nodeType !== 'nr'
                "
                type="text"
                size="mini"
                @click="handleAddContent(scope.row)"
              >
                添加内容
              </el-button>
              <el-button
                v-if="scope.row.nodeType == 'nr' && scope.row.status != 0"
                type="text"
                size="mini"
                @click="handleEditContent(scope.row)"
              >
                修改内容
              </el-button>
              <el-button
                v-if="scope.row.nodeType == 'nr' && scope.row.status != 0"
                type="text"
                size="mini"
                @click="handleDropdownCommand('infoMaintain', scope.row)"
              >
                信息维护
              </el-button>
              <el-button
                v-if="scope.row.nodeType == 'nr'"
                type="text"
                @click.native="handleDropdownCommand('status', scope.row)"
              >
                {{ scope.row.status === 1 ? '停用' : '启用' }}
              </el-button>
              <el-button
                v-if="scope.row.nodeType == 'nr'"
                type="text"
                class="delete-btn"
                @click.native="handleDropdownCommand('delete', scope.row)"
              >
                删除
              </el-button>
              <!-- 第四个以后的按钮放入更多下拉菜单 -->
              <el-dropdown
                v-if="scope.row.status != 0 && scope.row.nodeType !== 'nr'"
                trigger="click"
                class="ml10"
              >
                <el-button type="text" size="mini">
                  更多
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-if="scope.row.nodeType == 'nr'"
                    @click.native="
                      handleDropdownCommand('infoMaintain', scope.row)
                    "
                  >
                    信息维护
                  </el-dropdown-item>
                  <el-dropdown-item
                    divided
                    @click.native="handleDropdownCommand('status', scope.row)"
                  >
                    {{ scope.row.status === 1 ? '停用' : '启用' }}
                  </el-dropdown-item>
                  <el-dropdown-item
                    @click.native="handleDropdownCommand('delete', scope.row)"
                  >
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!--添加、修改类别弹窗 -->
      <el-dialog
        v-loading="submitting"
        :title="title"
        :visible.sync="editDialogVisible"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
      >
        <el-form
          ref="editForm"
          :model="editForm"
          :rules="rules"
          label-width="120px"
          class="edit-form"
        >
          <el-form-item label="上级类别:">
            <el-cascader
              v-model="editForm.parentId"
              :options="tableListData"
              placeholder=" 请选择上级类别"
              v-bind="catalogProps"
              style="width: 100%"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="节点类型:" prop="nodeType">
            <el-radio-group v-model="editForm.nodeType">
              <el-radio
                v-for="item in dictData['nodeType']"
                :key="item.id"
                :label="item.key"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="类别名称:" prop="catalogName">
            <el-input
              v-model="editForm.catalogName"
              clearable
              @change="changeName(editForm)"
            ></el-input>
          </el-form-item>
          <el-form-item label="备注:">
            <el-input
              v-model="editForm.remark"
              type="textarea"
              :rows="3"
              maxlength="500"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            :loading="submitting"
            @click="submitForm('editForm')"
          >
            确 认
          </el-button>
          <el-button class="ml10" @click="editDialogVisible = false">
            取 消
          </el-button>
        </div>
      </el-dialog>

      <!-- 添加/修改成本监审内容弹窗 -->
      <el-dialog
        :title="editContentDialogTitle"
        :visible.sync="contentDialogVisible"
        width="600px"
        append-to-body
        :close-on-click-modal="false"
      >
        <el-form
          ref="contentForm"
          :model="contentForm"
          :rules="contentRules"
          label-width="120px"
          class="edit-form"
          :disabled="editContentDialogTitle == '查看成本监审内容（项目）'"
        >
          <el-form-item label="上级目录类别:" prop="parentId">
            <el-cascader
              v-model="contentForm.parentId"
              :options="tableListData"
              placeholder=" 请选择上级类别"
              v-bind="catalogProps"
              style="width: 100%"
              disabled
            ></el-cascader>
          </el-form-item>
          <el-form-item label="目录编码:">
            <el-input v-model="contentForm.code" disabled></el-input>
          </el-form-item>
          <el-form-item label="类别名称:" prop="catalogName">
            <el-input
              v-model="contentForm.catalogName"
              maxlength="30"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="监审形式:" prop="auditType">
            <el-select
              v-model="contentForm.auditType"
              multiple
              placeholder="请选择监审形式"
              style="width: 100%"
              clearable
            >
              <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="监审部门:" prop="pricingDept">
            <el-input
              v-model="contentForm.pricingDept"
              placeholder="请输入监审部门"
              style="width: 100%"
              clearable
              maxlength="30"
            ></el-input>
          </el-form-item>
          <el-form-item label="监审级别:" prop="priceLevel">
            <el-select
              v-model="contentForm.priceLevel"
              multiple
              placeholder="请选择监审级别"
              style="width: 100%"
              clearable
            >
              <el-option
                v-for="item in dictData['priceLevel']"
                :key="item.id"
                :label="item.name"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注:">
            <el-input
              v-model="contentForm.remark"
              type="textarea"
              :rows="3"
              maxlength="500"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            v-if="editContentDialogTitle != '查看成本监审内容（项目）'"
            type="primary"
            @click="submitContentForm('contentForm')"
          >
            确 认
          </el-button>
          <el-button @click="contentDialogVisible = false">
            {{
              editContentDialogTitle == '查看成本监审内容（项目）'
                ? '关 闭'
                : '取 消'
            }}
          </el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 信息维护视图 -->
    <div v-else class="info-maintain-container">
      <div class="page-header">
        <el-button
          plain
          type="primary"
          size="small"
          icon="el-icon-arrow-left"
          @click="backToList"
        >
          返回列表
        </el-button>
        <h3>{{ currentCatalogName || '监审目录' }}信息维护</h3>
      </div>
      <el-tabs
        v-model="activeTab"
        type="border-card"
        @tab-click="handleTabClick"
      >
        <el-tab-pane label="政策文件" name="policyFiles">
          <div class="tab-content">
            <div class="operation-bar">
              <el-button
                plain
                type="primary"
                size="small"
                icon="el-icon-circle-plus"
                @click="handleAddPolicy"
              >
                关联政策文件
              </el-button>
              <el-button
                plain
                type="danger"
                size="small"
                icon="el-icon-delete"
                :disabled="!selectedPolicyFiles.length"
                @click="handleDeletePolicy"
              >
                取消关联文件
              </el-button>
            </div>
            <cost-audit-table
              :table-data="policyFilesData"
              :columns="policyColumns"
              :show-selection="true"
              :show-pagination="true"
              :pagination="policyPagination"
              @pagination-change="policyPaginationChange"
              @selection-change="handlePolicySelectionChange"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="监审对象提交资料清单" name="legalBasis">
          <div class="tab-content">
            <div class="operation-bar">
              <el-button
                plain
                type="success"
                size="small"
                icon="el-icon-circle-plus"
                @click="handleAddLegal"
              >
                添加
              </el-button>
            </div>

            <cost-audit-table
              :table-data="legalBasisData"
              :columns="legalColumns"
              :show-pagination="true"
              :pagination="legalBasisPagination"
              @pagination-change="legalBasisPaginationChange"
              @selection-change="handleLegalSelectionChange"
            >
              <!-- 操作列插槽 -->
              <template #action="{ row }">
                <el-button
                  type="text"
                  size="mini"
                  @click="handleEditLegal(row)"
                >
                  修改
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="handleDeleteSingleLegal(row)"
                >
                  删除
                </el-button>
              </template>
            </cost-audit-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="成本调查表" name="costSurvey">
          <div class="tab-content">
            <div class="operation-bar">
              <el-button
                plain
                type="primary"
                size="small"
                icon="el-icon-circle-plus"
                @click="handleAddCostSurvey"
              >
                关联成本调查表
              </el-button>
              <el-button
                plain
                type="danger"
                size="small"
                icon="el-icon-delete"
                :disabled="!selectCostSurvey.length"
                @click="handleDeleteCostSurvey"
              >
                取消关联成本调查表
              </el-button>
            </div>
            <cost-audit-table
              :table-data="costSurveyData"
              :columns="costSurveyColumns"
              :show-selection="true"
              :border="true"
              :show-pagination="true"
              :pagination="costSurveyPagination"
              @selection-change="handleCostSurveySelectionChange"
              @pagination-change="handlePaginationChange"
            >
              <!-- 操作列插槽 -->
              <template #action="{ row }">
                <el-button
                  type="text"
                  size="mini"
                  @click="handleViewCostSurvey(row)"
                >
                  查看
                </el-button>
              </template>
            </cost-audit-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <!-- 政策文件表单 -->
      <el-dialog
        :title="policyDialogTitle"
        :visible.sync="policyDialogVisible"
        width="50%"
        :close-on-click-modal="false"
      >
        <el-form
          :inline="true"
          :model="selectPolicySearchForm"
          class="demo-form-inline"
        >
          <el-form-item label="文件标题：">
            <el-input
              v-model="selectPolicySearchForm.title"
              placeholder="请输入文件标题"
              clearable
            />
          </el-form-item>
          <el-form-item label="文号：">
            <el-input
              v-model="selectPolicySearchForm.documentNumber"
              placeholder="请输入文号"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-search"
              type="primary"
              @click="getSelectPolicyFilesData"
            >
              搜索
            </el-button>
            <el-button
              plain
              type="primary"
              icon="el-icon-refresh"
              @click="handleResetPolicy"
            >
              重置
            </el-button>
          </el-form-item>
        </el-form>
        <cost-audit-table
          :table-data="formatterSelectFilesData"
          :columns="selectPolicyColumns"
          :table-props="{
            maxHeight: '400',
          }"
          :show-selection="true"
          :show-pagination="true"
          :pagination="selectPolicyPagination"
          @pagination-change="selectPolicyPaginationChange"
          @selection-change="selectPolicySelectionChange"
        />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitPolicyForm('policyForm')">
            确认
          </el-button>
          <el-button @click="policyDialogVisible = false">取消</el-button>
        </div>
      </el-dialog>

      <!-- 监审对象提交资料清单表单 -->
      <el-dialog
        :title="legalDialogTitle"
        :visible.sync="legalDialogVisible"
        width="600px"
        :close-on-click-modal="false"
      >
        <el-form
          ref="legalForm"
          :model="legalForm"
          :rules="legalRules"
          label-width="100px"
        >
          <el-form-item label="资料类别:" prop="informationType">
            <el-select
              v-model="legalForm.informationType"
              placeholder="请选择资料类别"
              style="width: 100%"
            >
              <el-option
                v-for="item in dictData['materialType']"
                :key="item.id"
                :label="item.name"
                :value="item.key"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="资料名称:" prop="informationName">
            <el-input
              v-model="legalForm.informationName"
              placeholder="请输入资料名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="资料要求:" prop="informationRequire">
            <el-input
              v-model="legalForm.informationRequire"
              placeholder="请输入资料要求"
            ></el-input>
          </el-form-item>
          <el-form-item label="格式要求:" prop="formatRequired">
            <el-select
              v-model="legalForm.formatRequired"
              placeholder="请选择格式要求"
              style="width: 100%"
            >
              <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
            v-if="legalForm.formatRequired === '3'"
            label="选择模板:"
            prop="templateId"
          >
            <el-input
              v-model="legalForm.surveyTemplateName"
              style="width: 80%"
              disabled
            ></el-input>
            <el-button type="primary" @click="handleTemplateClick">
              选择模板
            </el-button>
          </el-form-item>
          <el-form-item label="资料排序:" prop="orderNum">
            <el-input-number
              v-model="legalForm.orderNum"
              controls-position="right"
              :min="1"
              style="width: 100%"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="是否必填:" prop="isRequired">
            <el-radio-group v-model="legalForm.isRequired">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            :loading="submitting"
            @click="submitLegalForm('legalForm')"
          >
            确认
          </el-button>
          <el-button @click="legalDialogVisible = false">取消</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="选择模板"
        :visible.sync="templateDialogVisible"
        width="50%"
        :close-on-click-modal="false"
      >
        <cost-audit-table
          :table-data="templateData"
          :columns="templateColumns"
          :show-selection="true"
          :show-pagination="true"
          :pagination="templatePagination"
          @pagination-change="templatePaginationChange"
          @selection-change="templateSelectionChange"
        >
          <!-- 创建时间自定义单元格 -->
          <template #createTime="{ row }">
            <div>{{ row.createTime ? row.createTime.split(' ')[0] : '-' }}</div>
            <div>{{ row.createTime ? row.createTime.split(' ')[1] : '-' }}</div>
          </template>
        </cost-audit-table>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitTemplateForm('templateForm')">
            确认
          </el-button>
          <el-button @click="templateDialogVisible = false">取消</el-button>
        </div>
      </el-dialog>

      <!-- 成本调查表表单 -->
      <el-dialog
        title="关联成本调查表"
        :visible.sync="costSurveyDialogVisible"
        width="50%"
        :close-on-click-modal="false"
      >
        <cost-audit-table
          :table-data="selectCostSurveyData"
          :columns="selectCostSurveyColumns"
          :show-selection="true"
          :show-pagination="true"
          :pagination="selectCostSurveyPagination"
          @pagination-change="selectCostSurveyPaginationChange"
          @selection-change="selectCostSurveySelectionChange"
        >
          <!-- 创建时间自定义单元格 -->
          <template #createTime="{ row }">
            <div>{{ row.createTime ? row.createTime.split(' ')[0] : '-' }}</div>
            <div>{{ row.createTime ? row.createTime.split(' ')[1] : '-' }}</div>
          </template>
        </cost-audit-table>

        <div slot="footer" class="dialog-footer">
          <el-button @click="costSurveyDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitCostSurveyForm('costSurveyForm')"
          >
            确认
          </el-button>
        </div>
      </el-dialog>
      <!-- 成本调查表查看弹窗 -->
      <SurveyDialog
        :dialog-visible="contentEditDialogVisible"
        :dialog-title="contentEditDialogTitle"
        :form-data="contentEditForm"
        :disabled="contentEditDisabled"
        @cancel="handleContentEditCancel"
      />
    </div>
  </div>
</template>

<script>
  import CostAuditTable from '@/components/costAudit/CostAuditTable.vue'
  import SurveyDialog from './surveyDialog.vue'
  import {
    getCategory,
    getCatalogList,
    validateName,
    changeCatalogstatus,
    getCatalogDetail,
    editCatalogCategory,
    deleteCatalog,
    editCatalogContent,
    addCatalogCategory,
    addCatalogContent,
    // 信息维护相关API
    getPolicyDoc,
    associatePolicyDoc,
    unassociatePolicyDoc,
    // 资料清单相关API
    getDocumentCatalog,
    addDocumentCatalog,
    updateDocumentCatalog,
    deleteDocumentCatalog,
    // 成本调查与模板相关API
    getCostSurveyForms,
    getallCurrentCostSurveyList,
    addCostSurvey,
    cleanByIds,
    // 文件管理相关API
  } from '@/api/catalogManage'
  import { getInfoList } from '@/api/auditDocManage'
  import { allcurrentCostSurveyList } from '@/api/financeSheetManage'
  import { getCostFormDetail } from '@/api/costFormManage'
  import { dictMixin } from '@/mixins/useDict'

  export default {
    name: 'CatalogManage',
    components: {
      CostAuditTable,
      SurveyDialog,
    },
    mixins: [dictMixin],
    props: {
      isLinkDialog: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        dictData: {
          nodeType: [], //节点类型
          priceLevel: [], //监审级别
          auditType: [], //监审形式
          materialType: [], //资料类别
          formatAsk: [], //格式要求
        },
        // 列表视图相关数据
        loading: false,
        submitting: false,
        searchForm: {
          categoryId: '',
          auditType: '',
          catalogName: '',
        },
        total: 2,
        // 树形结构数据
        tableData: [],
        tableListData: [],
        catalogProps: {
          filterable: true,
          style: 'width: 100%',
          showAllLevels: false,
          props: {
            children: 'children',
            checkStrictly: true,
            label: 'catalogName',
            value: 'id',
            emitPath: false,
          },
        },
        title: '添加成本监审类别',
        editDialogVisible: false,
        contentDialogVisible: false,
        editContentDialogTitle: '添加成本监审内容（项目）',
        editForm: {
          id: '',
          parentId: '',
          parentName: '',
          code: '',
          catalogName: '',
          // auditType: [],
          // pricingDept: '',
          remark: '',
          // priceLevel: [],
        },
        contentForm: {
          parentName: '',
          code: '',
          catalogName: '',
          auditType: [],
          pricingDept: '',
          priceLevel: [],
          remark: '',
        },
        rules: {
          parentId: [
            { required: true, message: '请选择上级类别', trigger: 'change' },
            { max: 30, message: '长度不能超过30个字符', trigger: 'blur' },
          ],
          catalogName: [
            { required: true, message: '请输入类别名称', trigger: 'blur' },
            { max: 30, message: '长度不能超过30个字符', trigger: 'blur' },
          ],
          nodeType: [
            { required: true, message: '请选择节点类型', trigger: 'change' },
          ],
        },
        contentRules: {
          catalogName: [
            { required: true, message: '请输入监审内容', trigger: 'blur' },
            { max: 30, message: '长度不能超过30个字符', trigger: 'blur' },
          ],
          auditType: [
            { required: false, message: '请选择监审形式', trigger: 'change' },
          ],
          pricingDept: [
            { required: true, message: '请选择监审部门', trigger: 'change' },
          ],
          priceLevel: [
            { required: true, message: '请选择监审级别', trigger: 'change' },
          ],
        },
        isNameExist: false,
        IsEditContent: false,
        catalogNmaes: [],
        // 信息维护视图相关数据
        showInfoMaintain: false,
        currentCatalogId: '',
        currentCatalogName: '',
        activeTab: 'policyFiles',

        // 政策文件数据
        policyFilesData: [],
        selectedPolicyFiles: [],
        policyDialogVisible: false,
        policyDialogTitle: '关联政策文件',
        policyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        selectPolicyFilesData: [],
        selectedDocFiles: [],
        selectPolicyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        selectPolicySearchForm: {
          title: '',
          documentNumber: '',
        },
        selectPolicyColumns: [
          {
            prop: 'title',
            label: '文件标题',
            align: 'center',
          },
          {
            prop: 'documentNumber',
            label: '文号',
            align: 'center',
          },
        ],
        // 监审对象提交资料清单数据
        legalBasisData: [],
        legalBasisPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        selectLegalBasis: [],
        legalDialogVisible: false,
        legalDialogTitle: '提交资料清单',
        legalForm: {
          informationType: '',
          informationName: '',
          informationRequire: '',
          formatRequired: '',
          templateId: '',
          isRequired: '0',
          orderNum: 1,
        },
        templateDialogVisible: false,
        templateData: [],
        selectTemplateData: [],
        templatePagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        templateColumns: [
          {
            prop: 'surveyTemplateName',
            label: '财务数据表名称',
          },
          {
            prop: 'templateType',
            label: '模版类型',
            width: '100px',
            formatter: (row) => {
              return row.templateType == '1'
                ? '单记录'
                : row.templateType == '2'
                ? '固定表'
                : '动态表'
            },
          },
          {
            prop: 'storageTable',
            label: '财务数据表数据存储表名称',
          },
          {
            prop: 'status',
            label: '状态',
            width: '100px',
            formatter: (row) => {
              return row.status == '-1'
                ? '草稿'
                : row.status == '0'
                ? '启用'
                : '停用'
            },
          },
          {
            prop: 'createTime',
            label: '创建时间',
            slotName: 'createTime',
            width: '100px',
          },
        ],

        legalRules: {
          informationType: [
            { required: true, message: '请选择资料类别', trigger: 'change' },
          ],
          informationName: [
            { required: true, message: '请输入资料名称', trigger: 'blur' },
          ],
          formatRequired: [
            { required: true, message: '请选择格式要求', trigger: 'change' },
          ],
          isRequired: [
            { required: true, message: '请选择是否必填', trigger: 'change' },
          ],
          orderNum: [
            { required: true, message: '请输入资料排序', trigger: 'blur' },
          ],
          informationRequire: [
            { required: true, message: '请输入资料要求', trigger: 'blur' },
          ],
          // templateId: [
          //   { required: true, message: '请选择模板', trigger: 'change' },
          // ],
        },
        surveyStatusOptions: [
          { value: '-1', label: '草稿' },
          { value: '0', label: '现行' },
          { value: '1', label: '停用' },
        ],
        // 成本调查表数据
        costSurveyData: [],
        surveyDetailsData: [],
        costSurveyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        costSurveyColumns: [
          {
            prop: 'surveyTemplateName',
            label: '成本调查表',
            align: 'center',
            // slotName: 'surveyTemplateName',
          },
          {
            prop: 'year',
            label: '年度',
            width: 100,
            align: 'center',
          },
          {
            prop: 'status',
            label: '状态',
            width: 100,
            align: 'center',
            formatter: (row) => {
              return this.surveyStatusOptions.find(
                (item) => item.value === row.status
              ).label
            },
          },
          {
            label: '操作',
            width: 200,
            align: 'center',
            slotName: 'action',
          },
        ],
        selectCostSurvey: [],
        costSurveyDialogVisible: false,
        selectCostSurveyData: [],
        selectCostSurveyRow: [],
        selectCostSurveyPagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 内容编辑弹窗相关
        contentEditDialogVisible: false,
        contentEditDialogTitle: '内容维护',
        contentEditDisabled: true,
        policyFilesOptions: [],
        policyColumns: [
          {
            prop: 'projectName',
            label: '政策文件',
            align: 'center',
          },
          {
            prop: 'documentNumber',
            label: '文号',
            align: 'center',
          },
        ],
        contentEditForm: {
          tableName: '',
          formStyle: '固定表',
          // 单记录列表
          tableHeaders: [],
          // 固定表列表
          fixedTable: [],
          // 动态表列表
          dynamicTable: [],
        },
      }
    },
    computed: {
      legalColumns() {
        return [
          {
            prop: 'informationType',
            label: '资料类别',
            width: 150,
            align: 'center',
            formatter: (row) => {
              return this.getDictName('materialType', row.informationType)
            },
          },
          {
            prop: 'informationName',
            label: '资料名称',
            align: 'center',
          },
          {
            prop: 'formatRequired',
            label: '格式要求',
            width: 150,
            align: 'center',
            formatter: (row) => {
              return this.getDictName('formatAsk', row.formatRequired)
            },
          },
          {
            prop: 'orderNum',
            label: '资料排序',
            width: 150,
            align: 'center',
          },
          {
            prop: 'isRequired',
            label: '是否必填',
            width: 100,
            align: 'center',
            formatter: (row) => (row.isRequired == 0 ? '是' : '否'),
          },
          {
            label: '操作',
            width: 260,
            align: 'center',
            slotName: 'action',
          },
        ]
      },
      // 表格列配置
      selectCostSurveyColumns() {
        return [
          // {
          //   prop: 'catalogId',
          //   label: '监审类别',
          // },
          {
            prop: 'surveyTemplateName',
            label: '调查表名称',
          },
          {
            prop: 'templateType',
            label: '模版类型',
            width: '100px',
            formatter: (row) => {
              return row.templateType == '1'
                ? '单记录'
                : row.templateType == '2'
                ? '固定表'
                : '动态表'
            },
          },
          {
            prop: 'storageTable',
            label: '调查表数据存储表',
          },
          {
            prop: 'status',
            label: '状态',
            width: '100px',
            formatter: (row) => {
              return row.status == '-1'
                ? '草稿'
                : row.status == '0'
                ? '启用'
                : '停用'
            },
          },
          {
            prop: 'createTime',
            label: '创建时间',
            slotName: 'createTime',
            width: '100px',
          },
        ]
      },
      formatterSelectFilesData() {
        return this.distinct(
          this.policyFilesData,
          this.selectPolicyFilesData,
          'documentNumber'
        )
      },
    },

    mounted() {
      this.getCategoryOpt()
      this.fetchData()
    },
    methods: {
      distinct(arr1, arr2, key) {
        let result = []
        arr1.forEach((item) => {
          arr2.forEach((item2) => {
            if (item[key] !== item2[key]) {
              result.push(item2)
            }
          })
        })
        return result
      },
      // 列表视图相关方法
      handleReset() {
        this.searchForm = {
          categoryId: '',
          auditType: '',
          catalogName: '',
          pageNum: 1,
          pageSize: 10,
        }
        this.total = 0
        this.fetchData()
      },
      // 分页大小变化
      handleSizeChange(val) {
        this.searchForm.pageSize = val
        this.fetchData()
      },
      // 当前页变化
      handleCurrentChange(val) {
        this.searchForm.pageNum = val
        this.fetchData()
      },
      // 获取目录类别
      getCategoryOpt() {
        getCategory().then((res) => {
          this.catalogNmaes = res.value || []
        })
      },
      // 获取数据
      // 获取数据
      fetchData() {
        this.loading = true
        getCatalogList({ ...this.searchForm })
          .then((res) => {
            this.tableListData = res.value || []

            // 确保 tableListData 是数组
            if (!Array.isArray(this.tableListData)) {
              this.tableListData = []
            }

            // 移除不需要的属性
            this.tableListData = this.removeItemFromTree(this.tableListData)
            this.tableData - []
            // 直接返回所有顶级目录的子项元素，扁平化处理
            // 先清空数组，避免数据积累
            this.tableData = []
            // 使用Set来跟踪已添加的ID，避免重复项
            const addedIds = new Set()
            this.tableListData.forEach((item) => {
              if (
                item.parentId === '0' &&
                item.children &&
                item.children.length > 0
              ) {
                // 处理顶级目录的子项
                item.children.forEach((child) => {
                  if (child.id && !addedIds.has(child.id)) {
                    addedIds.add(child.id)
                    this.tableData.push(child)
                  }
                })
              } else if (item.parentId != '0') {
                // 处理非顶级目录项
                if (item.id && !addedIds.has(item.id)) {
                  addedIds.add(item.id)
                  this.tableData.push(item)
                }
              }
            })
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      },
      removeItemFromTree(treeData) {
        // 边界条件检查
        if (!treeData || !Array.isArray(treeData)) {
          return []
        }

        // 创建新数组，避免修改原数据
        return treeData.map((item) => {
          // 创建当前节点的副本
          const newItem = { ...item }

          // 如果有hasChildren属性则删除
          if ('hasChildren' in newItem) {
            delete newItem.hasChildren
          }

          // 递归处理子节点 先检查children是否存在且为数组
          if (
            newItem.children &&
            Array.isArray(newItem.children) &&
            newItem.children.length > 0
          ) {
            newItem.children = this.removeItemFromTree(newItem.children)
          }

          return newItem
        })
      },
      // 根据行数据的状态返回不同的类名
      getRowClassName({ row }) {
        if (row.status === 0) {
          return 'disabled-text' // 停用状态的类名
        } else if (row.status === 1) {
          return 'info-text' // 启用状态的类名
        }
        return ''
      },
      changeName(row) {
        if (!row.catalogName) return
        validateName({ name: row.catalogName, parentId: row.parentId }).then(
          (res) => {
            this.isNameExist = res.value
          }
        )
      },
      // 查看详情
      handleViewDetail(row) {
        this.editContentDialogTitle = '查看成本监审内容（项目）'
        getCatalogDetail(row.id).then((res) => {
          this.contentForm = res.value
          this.IsEditContent = true
          // 确保 auditType 始终是数组
          let auditTypeValue = []
          if (Array.isArray(row.auditType)) {
            auditTypeValue = row.auditType
          } else if (typeof row.auditType === 'string') {
            auditTypeValue = row.auditType ? row.auditType.split(',') : []
          }

          // 对 priceLevel 做同样处理
          let priceLevelValue = []
          if (Array.isArray(row.priceLevel)) {
            priceLevelValue = row.priceLevel
          } else if (typeof row.priceLevel === 'string') {
            priceLevelValue = row.priceLevel ? row.priceLevel.split(',') : []
          }
          this.contentForm = {
            ...this.contentForm,
            catalogId: row.id,
            parentName: this.getParentName(row.parentId),
            auditType: auditTypeValue,
            priceLevel: priceLevelValue,
          }
          // 重置表单验证状态
          this.$nextTick(() => {
            if (this.$refs.contentForm) {
              this.$refs.contentForm.clearValidate()
            }
          })
          this.contentDialogVisible = true
        })
      },
      handleAdd(row) {
        if (row) {
          this.editForm = {
            parentId: row.id,
            parentName: row.catalogName || '根目录',
            nodeType: 'lx',
            catalogName: '',
            remark: '',
          }
        } else {
          this.editForm = {
            parentId: this.tableListData[0].id || '', // 根目录的id,
            parentName: '根目录',
            nodeType: 'lx',
            catalogName: '',
            remark: '',
          }
        }
        this.title = '添加成本监审类别'
        this.editDialogVisible = true
      },
      // 修改类别
      handleEdit(row) {
        this.editForm = {
          parentId: row.parentId,
          catalogId: row.id,
          nodeType: row.nodeType,
          id: row.id,
          code: row.code,
          catalogName: row.catalogName,
          remark: row.remark,
          parentName: this.getParentName(row.parentId) || '根目录',
        }
        this.title = '修改成本监审类别'
        this.editDialogVisible = true
      },
      // 获取父级名称的辅助方法
      getParentName(parentId) {
        if (!parentId) return '根目录'

        const findParent = (data, visited = new Set()) => {
          // 防止循环引用导致的无限递归
          if (visited.has(parentId)) {
            return null
          }

          for (let item of data) {
            // 避免处理自身导致的循环
            if (visited.has(item.id)) continue

            if (item.id === parentId) {
              return item.catalogName
            }

            if (item.children && item.children.length) {
              visited.add(item.id)
              const found = findParent(item.children, visited)
              visited.delete(item.id)
              if (found) return found
            }
          }
          return null
        }

        // 从完整的树数据中查找
        const result = findParent(this.tableListData)
        return result || '根目录'
      },
      // 添加子类
      handleAddChild(row) {
        this.editForm = {
          parentId: row.id,
          parentName: row.catalogName || '根目录',
          catalogName: '',
          nodeType: 'lx',
          remark: '',
          auditType: row.auditType,
        }
        this.title = '添加成本监审类别'
        this.editDialogVisible = true
      },
      // 添加内容
      handleAddContent(row) {
        this.editContentDialogTitle = '添加成本监审内容（项目）'
        this.IsEditContent = false
        this.contentForm = {
          id: row.id,
          parentId: row.parentId,
          code: row.code,
          parentName: this.getParentName(row.parentId),
          catalogName: row.catalogName,
          auditType: row.auditType ? row.auditType.split(',') : [],
          pricingDept: '',
          remark: '',
          priceLevel: [],
        }
        // 重置表单验证状态
        this.$nextTick(() => {
          if (this.$refs.contentForm) {
            this.$refs.contentForm.clearValidate()
          }
        })
        this.contentDialogVisible = true
      },
      // 修改内容
      handleEditContent(row) {
        this.editContentDialogTitle = '修改成本监审内容（项目）'
        getCatalogDetail(row.id).then((res) => {
          this.contentForm = res.value
          this.IsEditContent = true
          // 确保 auditType 始终是数组
          let auditTypeValue = []
          if (Array.isArray(row.auditType)) {
            auditTypeValue = row.auditType
          } else if (typeof row.auditType === 'string') {
            auditTypeValue = row.auditType ? row.auditType.split(',') : []
          }

          // 对 priceLevel 做同样处理
          let priceLevelValue = []
          if (Array.isArray(row.priceLevel)) {
            priceLevelValue = row.priceLevel
          } else if (typeof row.priceLevel === 'string') {
            priceLevelValue = row.priceLevel ? row.priceLevel.split(',') : []
          }
          this.contentForm = {
            ...this.contentForm,
            catalogId: row.id,
            parentName: this.getParentName(row.parentId),
            auditType: auditTypeValue,
            priceLevel: priceLevelValue,
          }
          // 重置表单验证状态
          this.$nextTick(() => {
            if (this.$refs.contentForm) {
              this.$refs.contentForm.clearValidate()
            }
          })
          this.contentDialogVisible = true
        })
      },
      // 信息维护 - 切换视图
      handleInfoMaintain(row) {
        this.showInfoMaintain = true
        this.currentCatalogId = row.id
        this.currentCatalogName = row.catalogName
        this.handleTabClick()
      },
      // 返回列表
      backToList() {
        this.showInfoMaintain = false
        // 重置信息维护相关的数据
        this.activeTab = 'policyFiles'
        this.policyFilesData = []
        this.legalBasisData = []
        this.costSurveyData = []
      },
      // 启动/停用状态
      handleStatus(row) {
        const action = row.status === 1 ? '停用' : '启用'
        this.$confirm(`确认要${action}该数据吗?`, '操作确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            const statusValue = row.status === 1 ? 0 : 1
            changeCatalogstatus({
              id: row.id,
              status: statusValue,
            })
              .then((res) => {
                if (res.code === 200) {
                  this.$message.success(`${action}成功`)
                  this.fetchData()
                } else {
                  this.$message.error(res.message || `${action}失败`)
                }
              })
              .catch(() => {
                this.$message({
                  type: 'error',
                  message: ` ${action}失败!`,
                })
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消操作',
            })
          })
      },
      // 添加处理下拉菜单命令的方法
      handleDropdownCommand(command, row) {
        switch (command) {
          case 'editContent':
            this.handleEditContent(row)
            break
          case 'infoMaintain':
            this.handleInfoMaintain(row)
            break
          case 'status':
            this.handleStatus(row)
            break
          case 'delete':
            this.handleDelete(row)
            break
        }
      },
      // 删除
      handleDelete(row) {
        // 删除带子目录的类别，提示"请先删除所有子目录"，末级目录可直接删除
        if (row.children && row.children.length) {
          this.$message({
            type: 'warning',
            message: '请先删除所有子目录!',
          })
          return
        }

        this.$confirm('确认删除该数据吗?', '删除确认', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            deleteCatalog({ id: row.id })
              .then(() => {
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                })
                // 重新加载数据
                this.fetchData()
              })
              .catch(() => {
                this.$message({
                  type: 'error',
                  message: '删除失败!',
                })
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      // 提交表单
      submitForm(formName) {
        if (this.submitting) return // 防止重复提交
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submitting = true
            if (this.editForm.id) {
              // 修改
              editCatalogCategory(this.editForm)
                .then(() => {
                  this.$message.success('修改成功')
                  this.editDialogVisible = false
                  this.fetchData()
                })
                .finally(() => {
                  this.submitting = false
                })
            } else {
              // 添加
              addCatalogCategory(this.editForm)
                .then(() => {
                  this.$message.success('添加成功')
                  this.editDialogVisible = false
                  this.fetchData()
                })
                .finally(() => {
                  this.submitting = false
                })
            }
          } else {
            return false
          }
        })
      },
      // 提交内容表单
      submitContentForm(formName) {
        if (this.submitting) return // 防止重复提交
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let formData = {
              ...this.contentForm,
            }
            // 确保是数组后再进行 join 操作
            if (Array.isArray(formData.auditType)) {
              formData.auditType = formData.auditType.join(',')
            } else if (typeof formData.auditType === 'string') {
              // 如果已经是字符串，则保持不变
            } else {
              formData.auditType = ''
            }
            if (Array.isArray(formData.priceLevel)) {
              formData.priceLevel = formData.priceLevel.join(',')
            } else if (typeof formData.priceLevel === 'string') {
              // 如果已经是字符串，则保持不变
            } else {
              formData.priceLevel = ''
            }
            this.submitting = true
            if (this.IsEditContent) {
              // 修改
              editCatalogContent(formData)
                .then(() => {
                  this.$message.success('修改成功')
                  this.contentDialogVisible = false
                  this.fetchData()
                })
                .finally(() => {
                  this.submitting = false
                  this.IsEditContent = false
                })
            } else {
              addCatalogContent(formData)
                .then(() => {
                  this.$message.success('添加成功')
                  this.contentDialogVisible = false
                  this.fetchData()
                })
                .finally(() => {
                  this.submitting = false
                  this.IsEditContent = false
                })
            }
          } else {
            return false
          }
        })
      },

      // 信息维护视图相关方法
      // 标签页切换
      handleTabClick(tab) {
        // 可添加标签页切换时的逻辑
        switch (this.activeTab) {
          case 'policyFiles':
            this.loadPolicyFilesData()
            break
          case 'legalBasis':
            this.loadLegalBasisData()
            break
          case 'costSurvey':
            this.loadCostSurveyData()
            break
          default:
            break
        }
      },

      // 加载选项数据
      async loadOptionData() {},

      // 加载已关联政策文件数据
      loadPolicyFilesData() {
        getPolicyDoc({
          catalogId: this.currentCatalogId,
          page: this.policyPagination.currentPage,
          pageSize: this.policyPagination.pageSize,
        }).then((res) => {
          this.policyFilesData = res.value.records
          this.policyPagination.total = res.value.total
        })
      },
      // 政策文件相关方法
      handlePolicySelectionChange(val) {
        this.selectedPolicyFiles = val
      },
      // 添加政策文件
      handleAddPolicy() {
        this.getSelectPolicyFilesData()
        this.policyDialogTitle = '关联政策文件'
        this.policyDialogVisible = true
      },
      // 获取可选择的政策文件数据
      getSelectPolicyFilesData() {
        const params = {
          pageSize: this.selectPolicyPagination.pageSize,
          pageNum: this.selectPolicyPagination.currentPage,
          ...this.selectPolicySearchForm,
        }
        getInfoList(params).then((res) => {
          this.selectPolicyFilesData = res.value.records
          this.selectPolicyPagination.total = res.value.total
        })
      },
      // 重置关联政策文件筛选
      handleResetPolicy() {
        this.selectPolicySearchForm = {
          title: '',
          documentNumber: '',
        }
        ;(this.selectPolicyPagination = {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        }),
          this.getSelectPolicyFilesData()
      },
      // 重置选择政策文件搜索
      handleResetSelectPolicyFiles() {
        this.selectPolicySearchForm = {
          title: '',
          documentNumber: '',
        }
        this.selectPolicyPagination = {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        }
        this.getSelectPolicyFilesData()
      },
      // 选择政策文件
      selectPolicySelectionChange(val) {
        if (val.length > 1) {
          this.$message.warning('最多只能选择一个文件')
          return
        }
        this.selectedDocFiles = val
      },
      // 政策文件分页切换
      policyPaginationChange({ currentPage, pageSize }) {
        this.policyPagination.currentPage = currentPage
        this.policyPagination.pageSize = pageSize
        this.loadPolicyFilesData()
      },
      selectPolicyPaginationChange({ currentPage, pageSize }) {
        this.selectPolicyPagination.currentPage = currentPage
        this.selectPolicyPagination.pageSize = pageSize
        this.getSelectPolicyFilesData()
      },
      // 删除政策文件
      handleDeletePolicy() {
        if (this.selectedPolicyFiles.length === 0) {
          this.$message.warning('请先选择要取消关联的文件')
          return
        }
        this.$confirm(
          `确认取消关联选中的${this.selectedPolicyFiles.length}个文件?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            const ids = this.selectedPolicyFiles.map((row) => row.id)
            unassociatePolicyDoc({ ids }).then((res) => {
              this.$message.success('取消关联成功')
              this.loadPolicyFilesData()
            })
          })
          .catch(() => {
            this.$message.info('已取消取消关联')
          })
      },

      submitPolicyForm() {
        if (this.selectedDocFiles.length == 1) {
          associatePolicyDoc({
            catalogId: this.currentCatalogId,
            informationId: this.selectedDocFiles[0].id,
          }).then((res) => {
            if (res.code === 200) {
              this.$message.success('关联成功')
              this.policyDialogVisible = false
              // 重新加载数据
              this.loadPolicyFilesData()
            }
          })
        } else {
          this.$message.error('请选择一个文件')
        }
      },

      // 监审对象提交资料清单相关方法
      // 加载监审对象提交资料清单数据
      loadLegalBasisData() {
        getDocumentCatalog({
          catalogId: this.currentCatalogId,
          pageNum: this.legalBasisPagination.currentPage,
          pageSize: this.legalBasisPagination.pageSize,
        }).then((res) => {
          this.legalBasisData = res.value.records
          this.legalBasisPagination.total = res.value.total
        })
      },
      // 监审对象提交资料清单分页切换
      legalBasisPaginationChange({ currentPage, pageSize }) {
        this.legalBasisPagination.currentPage = currentPage
        this.legalBasisPagination.pageSize = pageSize
        this.loadLegalBasisData()
      },
      // 监审对象提交资料清单选择
      handleLegalSelectionChange(val) {
        this.selectLegalBasis = val
      },
      // 添加提交资料清单
      handleAddLegal() {
        this.legalDialogTitle = '添加提交资料清单'
        this.legalForm = {
          informationType: '',
          informationName: '',
          formatRequired: '',
          isRequired: '0',
          orderNum: 1,
        }
        this.legalDialogVisible = true
      },
      // 获取模板选项
      getTemplateOptions() {
        allcurrentCostSurveyList({
          pageNum: this.templatePagination.currentPage,
          pageSize: this.templatePagination.pageSize,
        }).then((res) => {
          this.templateData = res.value.records
          this.templatePagination.total = res.value.total
        })
      },
      handleTemplateClick() {
        this.getTemplateOptions()
        this.templateDialogVisible = true
      },
      templatePaginationChange({ currentPage, pageSize }) {
        this.templatePagination.currentPage = currentPage
        this.templatePagination.pageSize = pageSize
        this.getTemplateOptions()
      },
      templateSelectionChange(val) {
        if (val.length > 1) {
          this.$message.warning('最多只能选择一个模板')
          return
        }
        this.selectTemplateData = val
      },
      submitTemplateForm() {
        if (this.selectTemplateData.length == 1) {
          this.legalForm.templateId =
            this.selectTemplateData[0].surveyTemplateId
          this.legalForm.surveyTemplateName =
            this.selectTemplateData[0].surveyTemplateName
          this.templateDialogVisible = false
        } else {
          this.$message.error('请选择一个模板')
        }
      },
      // 修改提交资料清单
      handleEditLegal(row) {
        this.legalDialogTitle = '修改提交资料清单'
        this.legalForm = JSON.parse(JSON.stringify(row))
        this.legalDialogVisible = true
      },
      // 删除提交资料清单
      handleDeleteSingleLegal(row) {
        this.$confirm('确认删除该提交资料清单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            deleteDocumentCatalog(row.id).then((res) => {
              this.$message.success('删除成功')
              this.loadLegalBasisData()
            })
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },
      submitLegalForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.submitting = true
            if (this.legalForm.id) {
              updateDocumentCatalog({
                catalogId: this.currentCatalogId,
                ...this.legalForm,
              }).then((res) => {
                this.$message.success('修改成功')
                this.legalDialogVisible = false
                this.submitting = false
                this.loadLegalBasisData()
              })
            } else {
              addDocumentCatalog({
                catalogId: this.currentCatalogId,
                ...this.legalForm,
              }).then((res) => {
                this.$message.success('添加成功')
                this.legalDialogVisible = false
                this.submitting = false
                this.loadLegalBasisData()
              })
            }
          } else {
            return false
          }
        })
      },

      // 成本调查表相关方法
      // 加载成本调查表数据
      loadCostSurveyData() {
        getCostSurveyForms({
          catalogId: this.currentCatalogId,
          pageNum: this.costSurveyPagination.currentPage,
          pageSize: this.costSurveyPagination.pageSize,
        }).then((res) => {
          this.costSurveyData = res.value.records
          this.costSurveyPagination.total = res.value.total
        })
      },
      // 获取成本调查表选项
      getCostSurveyOptions() {
        getallCurrentCostSurveyList({}).then((res) => {
          this.selectCostSurveyData = res.value.records
          this.selectCostSurveyPagination.total = res.value.total
        })
      },
      handlePaginationChange({ currentPage, pageSize }) {
        this.costSurveyPagination.currentPage = currentPage
        this.costSurveyPagination.pageSize = pageSize
        this.loadCostSurveyData()
      },
      selectCostSurveyPaginationChange({ currentPage, pageSize }) {
        this.selectCostSurveyPagination.currentPage = currentPage
        this.selectCostSurveyPagination.pageSize = pageSize
        this.getCostSurveyOptions()
      },
      handleCostSurveySelectionChange(val) {
        this.selectCostSurvey = val
      },
      selectCostSurveySelectionChange(val) {
        if (val.length > 1) {
          this.$message.warning('只能选择一个成本调查表')
          return
        }
        this.selectCostSurveyRow = val
      },
      handleAddCostSurvey() {
        this.getCostSurveyOptions()
        this.costSurveyDialogVisible = true
      },
      handleDeleteCostSurvey() {
        if (this.selectCostSurvey.length === 0) {
          this.$message.warning('请先选择要删除的成本调查表')
          return
        }
        this.$confirm(
          `确认删除选中的${this.selectCostSurvey.length}个成本调查表?`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
          .then(() => {
            cleanByIds({
              ids: this.selectCostSurvey.map((item) => item.surveyId),
            }).then((res) => {
              this.$message.success('删除成功')
              this.loadCostSurveyData()
            })
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },
      submitCostSurveyForm() {
        if (this.selectCostSurveyRow.length == 1) {
          addCostSurvey({
            catalogId: this.currentCatalogId,
            surveyId: this.selectCostSurveyRow[0].surveyTemplateId,
          }).then((res) => {
            this.$message.success('关联成功')
            this.costSurveyDialogVisible = false
            this.loadCostSurveyData()
          })
        } else {
          this.$message.warning('请选择一个成本调查表')
        }
      },
      // 查看成本调查表内容弹窗
      handleViewCostSurvey(data) {
        // 设置表单数据
        this.contentEditForm = {
          surveyTemplateName: data.surveyTemplateName || '',
          templateType: data.templateType || '',
          data: data || {},
        }
        // 设置是否可编辑
        this.contentEditDisabled =
          data.disabled !== undefined ? data.disabled : true
        // 设置弹窗标题
        this.contentEditDialogTitle = data.title || '查看'
        // 显示弹窗
        this.contentEditDialogVisible = true
      },
      // 关闭内容编辑弹窗
      handleContentEditCancel() {
        this.contentEditDialogVisible = false
        // 重置表单数据
        this.contentEditForm = {
          tableName: '',
          formStyle: '单记录',
          tableHeaders: [],
          fixedTable: [],
          dynamicTable: [],
        }
      },

      // 文件下载方法
      async handleDownloadFile(fileId) {
        try {
          const response = await downloadFile({ fileId })
          // 创建下载链接并触发下载
          const url = window.URL.createObjectURL(new Blob([response]))
          const link = document.createElement('a')
          link.href = url
          link.setAttribute('download', `file_${fileId}`)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        } catch (error) {
          console.error('文件下载失败:', error)
          this.$message.error('文件下载失败')
        }
      },
      handleSelectionChange(data) {
        this.$emit('selection-change', data)
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import '@/styles/costAudit.scss';
  .catalog-manage-container {
    padding: 20px;
    .operation-bar {
      margin-bottom: 20px;
    }
    .divider-space {
      display: inline-block;
      margin: 0 4px;
    }

    .edit-form {
      padding: 0 20px;
    }
  }

  /* 信息维护视图样式 */
  .info-maintain-container {
    padding: 20px;
    .page-header {
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      gap: 15px;

      h3 {
        font-size: 18px;
        font-weight: 500;
        color: #303133;
        margin: 0;
      }
    }
  }
</style>
