<template>
  <div>
    <div class="collect-header">
      <h4 :class="classType">{{ collectTitle }} </h4>
      <div class="collect-filter">
        <treeselect
          v-if="selectedCategory.arrangeType === 3 && isTitleType !== 4 && isTitleType !== 6 && activeIndex !== 1"
          v-model="query.project_class"
          :options="projectOptions"
          style="width: 180px;"
          :flat="false"
          :multiple="false"
          :normalizer="normalizerProject"
          :default-expand-level="Infinity"
          :placeholder="projectPlaceholder"
          @input="handleSearch(collectLevel)"
          @select="handleSearch(collectLevel)"
        >
          <p
            slot="option-label"
            slot-scope="{node}"
            style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis; width: 100%; padding-left: 10px;"
            :title="node.label"
          >
            <template> {{ node.label }} </template>
          </p>
        </treeselect>
        <treeselect
          v-if="isTitleType !== 6 && isTitleType !== 2"
          v-model="query.archive_ctg_no"
          :options="classifyOptions"
          style="width: 180px;"
          :flat="false"
          :multiple="false"
          :normalizer="normalizer"
          placeholder="请选择档案分类"
          @input="handleSearch(collectLevel)"
          @select="handleSearch(collectLevel)"
        >
          <p
            slot="option-label"
            slot-scope="{node}"
            style="overflow: hidden;white-space: nowrap;text-overflow: ellipsis; width: 100%; padding-left: 10px;"
            :title="node.label"
          >
            <template> {{ node.label }} </template>
          </p>
        </treeselect>
      </div>
      <div v-if="isTitleType !== 6" class="head-search">
        <!-- 搜索 -->
        <el-input v-model="query.search" clearable size="small" :placeholder="placeholderType" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @keyup.enter.native="handleSearch(collectLevel)" @clear="handleSearch(collectLevel)" />
        <el-button class="filter-item filter-search" size="mini" type="success" icon="el-icon-search" @click="handleSearch(collectLevel)">搜索</el-button>
        <el-button class="filter-item filter-refresh" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置</el-button>
      </div>
      <div v-if="!isRecycle" class="collect-menu">
        <el-menu
          :default-active="activeMenuIndex"
          mode="horizontal"
          @select="handleSelect"
        >
          <el-submenu index="1">
            <template slot="title">
              <i class="iconfont icon-changgui" />
              <span>常规</span>
            </template>
            <el-menu-item-group class="collect-submenu-group">
              <el-menu-item v-if="isTitleType !== 6" index="1-1" @click="handleForm('add',0)">新增</el-menu-item>
              <el-menu-item v-if="isTitleType !== 6" index="1-2" @click="handleForm('edit',0)">编辑</el-menu-item>
              <el-menu-item v-if="isTitleType !== 4" index="1-3" @click="toDelete">删除</el-menu-item>
              <el-menu-item v-if="isTitleType === 4" index="1-4" @click="toMove">移出</el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group v-if="(isTitleType === 3 && selectedCategory.arrangeType === 1) || isTitleType === 4 || isTitleType === 6 || (isTitleType === 3 && activeIndex === 1)" class="collect-submenu-group submenu-tree">
              <template slot="title">原文上传</template>
              <el-menu-item index="1-5" @click="fileUpload(0)">普通上传</el-menu-item>
              <el-menu-item index="1-6" @click="fileUpload(1)">大文件上传</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu v-if="isTitleType !== 6" index="2">
            <template slot="title">
              <i class="iconfont icon-zhengli" />
              <span>整理</span>
            </template>
            <el-menu-item-group class="collect-submenu-group">
              <el-menu-item v-if="isTitleType !== 2" index="2-1" @click="handleBlukImport">批量导入</el-menu-item>
              <!-- 项目 / 案卷 / 卷内 / 文件-->
              <el-menu-item v-if="activeIndex !== 1 || (isTitleType === 3 && selectedCategory.arrangeType === 1 && activeIndex === 1)" index="2-2" @click="handleBlukEditing">批量修改</el-menu-item>
              <el-menu-item v-if="isTitleType === 3 && activeIndex === 0 && selectedCategory.arrangeType !== 1" index="2-3" @click="handleJnSeqAdjustment('anjuan')">案卷顺序调整</el-menu-item>
              <el-menu-item v-if="isTitleType === 3 && activeIndex === 0 && selectedCategory.arrangeType !== 1 " index="2-12" @click="handleJnSeqAdjustment('juannei')">卷内顺序调整</el-menu-item>
              <el-menu-item v-if="isTitleType === 3 && selectedCategory.arrangeType === 1" index="2-3" @click="handleJnSeqAdjustment('file')">文件顺序调整</el-menu-item>
              <el-menu-item v-if="isTitleType !== 2 && !(isTitleType === 3 && (selectedCategory.arrangeType === 1|| selectedCategory.arrangeType === 2) && activeIndex === 1) && isTitleType !== 4" index="2-4" @click="handleFileNumberUpdate(0)">档号更新</el-menu-item>
              <!-- 案卷 -->
              <el-menu-item v-if="isTitleType === 3 && activeIndex === 0 && selectedCategory.arrangeType !== 1 " index="2-5" @click="handleFileNumberUpdate(1)">卷内档号更新</el-menu-item>
              <el-menu-item v-if="isTitleType === 3 && activeIndex === 0 && selectedCategory.arrangeType !== 1" index="2-6" @click="handleUncoil">拆卷</el-menu-item>
              <el-menu-item v-if="isTitleType === 3 && activeIndex === 0 && selectedCategory.arrangeType !== 1" index="2-7" @click="handleCombineFile">合卷</el-menu-item>
              <el-menu-item v-if="isTitleType === 3 && selectedCategory.arrangeType !== 1" index="2-8" @click="handleInsertFile">插件</el-menu-item>
              <!-- 案卷 / 卷内 / 文件 -->
              <el-menu-item v-if="(isTitleType === 3 && selectedCategory.arrangeType === 1) || (isTitleType === 3 && activeIndex === 1) || (isTitleType === 4 ) " index="2-9" @click="handleCollectMoveFile">移动</el-menu-item>
              <!-- 案卷 -->
              <el-menu-item v-if="isTitleType === 3 && activeIndex === 0" index="2-10" @click="handleFiling">归档</el-menu-item>
              <!-- 文件 -->
              <el-menu-item v-if="(isTitleType === 3 && selectedCategory.arrangeType === 1) || (isTitleType === 3 && activeIndex === 1)" index="2-11" @click="handleReturn">退回预归档库</el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group v-if="isTitleType === 3 && activeIndex === 1 && selectedCategory.arrangeType !== 1" class="collect-submenu-group submenu-tree">
              <template slot="title">组卷</template>
              <el-menu-item index="2-12" @click="handleQuickPaper">快速组卷</el-menu-item>
              <el-menu-item index="2-13" @click="handlePaper">手工组卷</el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group v-if="isTitleType !== 4" class="collect-submenu-group submenu-tree">
              <template slot="title">档案装盒</template>
              <el-menu-item index="2-2" @click="handlePackingBox(0)">装盒</el-menu-item>
              <el-menu-item v-if="selectedCategory.arrangeType !== 1 " index="2-3" @click="handlePackingBox(1)">分卷装盒</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="3">
            <template slot="title">
              <i class="iconfont icon-gengduo" />
              <span>更多</span>
            </template>
            <el-menu-item-group class="collect-submenu-group">
              <el-menu-item v-if="isTitleType !== 6" index="3-1" @click="handleExport">导出</el-menu-item>
              <el-menu-item v-if="!(isTitleType === 3 && (selectedCategory.arrangeType === 3 || selectedCategory.arrangeType === 2) && activeIndex === 1) && (isTitleType !== 2 && isTitleType !== 6)" index="3-2" @click="handlePrint">打印</el-menu-item>
              <el-menu-item v-if="!(isTitleType === 3 && (selectedCategory.arrangeType === 3 || selectedCategory.arrangeType === 2) && activeIndex === 1) && (isTitleType !== 2 && isTitleType !== 6) && isTitleType !== 4" index="3-3" @click="handleFourTest">四性检测</el-menu-item>
              <el-menu-item v-if="isTitleType === 6" index="3-4" @click="handleOriginalDownload">下载</el-menu-item>
            </el-menu-item-group>
            <el-menu-item-group v-if="!(isTitleType === 3 && (selectedCategory.arrangeType === 3 || selectedCategory.arrangeType === 2) && activeIndex === 1) && (isTitleType !== 2 && isTitleType !== 4 && isTitleType !== 6)" class="collect-submenu-group submenu-tree">
              <template slot="title">电子文件目录</template>
              <el-menu-item index="3-5" @click="handleCatalogDownload">目录下载</el-menu-item>
              <el-menu-item index="3-6" @click="fileUpload(2)">目录上传</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </div>

      <div v-if="isRecycle && (isTitleType === 2 || isTitleType === 3)" class="collect-menu">
        <el-button class="filter-item" size="mini" type="success" @click="toRecover"><i class="iconfont icon-huifu" />恢复</el-button>
        <el-button class="filter-item" size="mini" type="success" @click="toCompletelyDelete"><i class="iconfont icon-shanchu" />彻底删除</el-button>
      </div>

      <!--新增 / 编辑 表单组件-->
      <!-- v-el-drag-dialog  -->
      <el-dialog :class="isAiAutoCategory ? 'preview-dialog ai-preview-dialog' :'preview-dialog'" :modal-append-to-body="false" :close-on-click-modal="false" append-to-body :before-close="handleClose" :visible="formVisible" :title="formTitle">
        <span class="dialog-right-top" />
        <span class="dialog-left-bottom" />
        <div class="setting-dialog">
          <!-- form @emitTableList="getTableList"  -->
          <div style="display: flex; justify-content: flex-start;">
            <PreviewForm
              v-if="formPreviewData.length"
              ref="previewForm"
              :is-has-code="true"
              :is-disabled="false"
              :form-preview-data.sync="formPreviewData"
              :selected-category="selectedCategory"
              :arc-id="arcId"
              :is-des-form-type="isDesFormType"
              :is-title-type="isTitleType"
              :collect-level="collectLevel"
              :category-menu="categoryMenu"
              @close-dialog="closeDialog"
              @handleForm="handleForm"
              @formLoadingShow="formLoadingShow"
              @repeatDataShow="repeatDataShow"
            />
            <div v-if="isAiAutoCategory" v-loading="aiResultCaLoading" style="flex: 1; margin-left: 10px; ">
              <pre ref="typingContainer" v-highlightjs="displayedText">{{ displayedText }}</pre>
            </div>
          </div>
          <div slot="footer" class="dialog-footer" style="margin-top: 85px !important;">
            <el-button v-if="formIsAddOrEdit==='add' && ((isTitleType === 3 && selectedCategory.arrangeType === 1) || isTitleType === 4 || isTitleType === 6 || (isTitleType === 3 && activeIndex === 1))" type="text" style="width: 84px; border-color: #0348f3; color: #0348f3; " @click="handleAiCategory">AI辅助著录</el-button>
            <el-button v-if="formIsAddOrEdit==='add'" type="primary" style="width: 140px; " @click="handlerArchivesSubmit(1)">保存并新增下一条</el-button>
            <el-button :loading="archivesBtnLoading" type="primary" @click="handlerArchivesSubmit(0)">保存</el-button>
          </div>
        </div>
      </el-dialog>

      <!-- AI辅助著录未处理已解析的文件 -->
      <el-dialog class="aiAssist-dialog" title="AI已解析文件" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="aIAssistEnterVisible" :before-close="handleAIClose">
        <div class="setting-dialog">
          <!-- @select="crud.selectChange"
            @select-all="crud.selectAllChange"
            @cell-dblclick="tableDoubleClick"
            @selection-change="crud.selectionChangeHandler" -->
          <el-table
            ref="table"
            v-loading="aiCategoryloading"
            class="archives-table"
            :data="aiCategoryData"
            row-key="id"
            height="calc(100vh - 300px)"
            :default-expanded-rows="expandedRows"
            @expand-change="handleExpandChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="expand">
              <template slot-scope="{row }">
                <el-table v-loading="row.childLoading" :data="row.children" class="child-table" :show-header="false">
                  <el-table-column width="100" align="center" />
                  <el-table-column prop="fileName" label="文件名称" show-overflow-tooltip min-width="200">
                    <template slot-scope="scope">
                      <i class="iconfont icon-attachment" />
                      <span style="margin-left: 10px">{{ scope.row.fileName }}</span>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column prop="fileType" label="格式" min-width="60" align="center" /> -->
                  <el-table-column prop="fileSize" label="大小" min-width="85" align="center">
                    <template slot-scope="scope">
                      {{ getFileSize(scope.row.fileSize) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="fileThumbnail" label="缩略图" min-width="60" align="center">
                    <template slot-scope="scope">
                      <div v-if="scope.row.fileType === 'jpg' || scope.row.fileType === 'jpeg' || scope.row.fileType === 'png' || scope.row.fileType === 'bmp'|| scope.row.fileType === 'gif'">
                        <i class="fileIcon icon-image" />
                      </div>
                      <div v-else-if="scope.row.fileType === 'xlsx' || scope.row.fileType === 'xls'">
                        <i class="fileIcon icon-excel" />
                      </div>
                      <div v-else-if="scope.row.fileType === 'docx' || scope.row.fileType === 'doc'">
                        <i class="fileIcon icon-word" />
                      </div>
                      <div v-else-if="scope.row.fileType === 'pdf'">
                        <i class="fileIcon icon-pdf" />
                      </div>
                      <div v-else-if="scope.row.fileType === 'ppt' || scope.row.fileType === 'pptx'">
                        <i class="fileIcon icon-ppt" />
                      </div>
                      <div v-else-if="scope.row.fileType === 'zip' || scope.row.fileType === 'rar'">
                        <i class="fileIcon icon-zip" />
                      </div>
                      <div v-else-if="scope.row.fileType === 'txt'">
                        <i class="fileIcon icon-txt" />
                      </div>
                      <div v-else>
                        <i class="fileIcon icon-other" />
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </template>
            </el-table-column>
            <el-table-column label="任务编号" prop="id" min-width="280" />
            <el-table-column label="文件数量" prop="fileNum" />
            <el-table-column label="创建人" prop="create_by" />
            <el-table-column label="创建时间" prop="update_time" align="center" width="160">
              <template slot-scope="scope">
                <div v-if="scope.row.update_time">{{ scope.row.update_time | parseTime }}</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="解析完成时间" prop="analysisTime" align="center" width="160">
              <template slot-scope="scope">
                <div v-if="scope.row.analysisTime">{{ scope.row.analysisTime | parseTime }}</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
            <el-table-column label="状态" prop="status" align="center" width="80">
              <template slot-scope="scope">
                <span v-if="!scope.row.isAnalysis" class="row-state row-warehousing state-active">解析中</span>
                <span v-else class="row-state row-binding  state-active">已解析</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" prop="status" align="center" width="140">
              <template slot-scope="scope">
                <el-button v-if="scope.row.isAnalysis" size="mini" class="check-btn" style="padding: 5px;" @click="getDoHandleEnterAnalysis(scope.row)">
                  <i class="iconfont icon-tianjiawenjian" />
                  新增档案
                </el-button>
              </template>
            </el-table-column>

          </el-table>
        </div>
      </el-dialog>

      <!--卷内移出 组件-->
      <el-dialog class="tip-dialog" title="提示" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="moveVisible">
        <div class="setting-dialog">
          <div class="tip-content">
            <p class="tipMsg">此操作将把所选条目放入未整理列表</p>
            <span>你是否还要继续?</span>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="moveVisible = false">取消</el-button>
            <el-button type="primary" @click.native="handleMoveConfirm">确定</el-button>
          </div>
        </div>
      </el-dialog>

      <!--档案号重复得list-->
      <el-dialog title="档号重复" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="repeatVisible" :before-close="handleRepeatClose">
        <div class="setting-dialog">
          <div v-if="repeatResponseData.delcount === 0" class="double-click-btn" style="position: static;  margin: -10px 0 10px 0;"><i class="iconfont icon-zhuyi-lan" /><span>建议修改当前输入的档号！</span></div>
          <div v-else class="double-click-btn" style="position: static;  margin: -10px 0 10px 0;"><i class="iconfont icon-zhuyi-lan" /><span>建议删除回收站相关数据 或者 修改当前输入的档号！</span></div>

          <el-table
            ref="table"
            v-loading="repeatLoading"
            class="archives-table"
            :data="repeatData"
            row-key="id"
          >
            <el-table-column label="所属门类" prop="categoryName" />
            <el-table-column v-if="repeatResponseData.delcount === 0" label="所属位置" prop="collectFormal">
              <template slot-scope="scope">
                <div v-if="scope.row.collectFormal === 1">收集库</div>
                <div v-if="scope.row.collectFormal === 2">归档中</div>
                <div v-if="scope.row.collectFormal === 3">管理库</div>
              </template>
            </el-table-column>
            <el-table-column v-else label="所属位置" prop="isDeleteMan">
              <template slot-scope="scope">
                <div v-if="scope.row.isDeleteMan">回收站</div>
              </template>
            </el-table-column>
            <el-table-column label="题名" prop="maintitle" show-overflow-tooltip min-width="130" />
            <el-table-column label="创建人" prop="createBy" />
            <el-table-column label="创建时间" prop="createTime" align="center" width="160">
              <template slot-scope="scope">
                <div v-if="scope.row.createTime">{{ scope.row.createTime | parseTime }}</div>
                <div v-else>-</div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-dialog>

      <!-- 原文上传 -->
      <UploadOriginal ref="uploadOriginalRef" :selected-category="selectedCategory" :arc-id="arcId" @close-dialog="closeDialog" />
      <!-- 大文件上传 -->
      <BigUpload ref="uploadBigRef" :selected-category="selectedCategory" :arc-id="arcId" @close-dialog="closeDialog" />
      <!-- 批量导入 -->
      <BlukImport ref="blukImportRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" />
      <!-- 批量修改 -->
      <BlukEditing ref="blukEditingRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" />
      <!-- 档案调整 -->
      <!-- <FileNumberAdjustment ref="fileNumberAdjustmentRef" :selected-category="selectedCategory" :collect-level="collectLevel" /> -->

      <!-- 案卷/文件/卷内 顺序调整 -->
      <FileSeqAdjustment ref="fileSeqAdjustmentRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" />

      <!-- 合卷 -->
      <CombineFile ref="combineFileRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" />
      <!-- 插件 -->
      <InsertFile ref="insertFileRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" />
      <!-- 移动 -->
      <CollectMoveFile ref="collectMoveFileRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" />

      <!-- 打印 -->
      <Print ref="printRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" />
      <!-- 四性检测 -->
      <FourTest ref="fourTestRef" :selected-category="selectedCategory" :collect-level="collectLevel" @close-dialog="closeDialog" />

      <!-- 快速组卷 -->
      <QuickPaper ref="quickPaperRef" :selected-category="selectedCategory" :arc-id="arcId" :collect-level="collectLevel" @close-dialog="closeDialog" />

      <!-- 归档 -->
      <ArchivesFilling ref="archivesFillingRef" :selected-category="selectedCategory" :collect-level="collectLevel" :selections="selections" @close-dialog="closeDialog" @handleFillingToFourTest="handleFillingToFourTest" />

      <!-- 装盒 / 分卷装盒 -->
      <PackingBox ref="packingBox" :selected-category="selectedCategory" :selections="selections" :total-sum-all="totalSumAll" @close-dialog="closeDialog" />
    </div>
    <div style="display: flex; justify-content: space-between; height: 30px; line-height: 30px; padding: 0 20px; ">
      <span v-if="(isTitleType !== 2 && selectedCategory.arrangeType === 3 ) || ((isTitleType === 4 || isTitleType === 6) && selectedCategory.arrangeType === 2) || (isTitleType === 6 && selectedCategory.arrangeType === 1)" style="font-size: 12px;">{{ test }}</span>
      <div v-if="isTitleType !== 2 && !isRecycle && isTitleType !== 6 && !(isTitleType === 3 && activeIndex === 1 && selectedCategory.arrangeType !== 1 )" class="mangement-fixed-top">
        <el-checkbox v-model="parentsData.fixedStatusBar" @change="statusBarChecked">隐藏状态栏</el-checkbox>
      </div>
    </div>
  </div>
</template>

<script>
import CRUD, { crud } from '@crud/crud'
import { collectionLibraryCrud } from '../mixins/index'
import { FetchInitCategoryInputFieldByPid, FetchCategoryMenu } from '@/api/system/category/category'
import { FetchDetailsById, collectDel, FetchRemoveArchivesSingle, FetchDeleteArchivesFile, FetchUpdateArchivesNo, FetchDisbandArchives, FetchReturnReDocument, FetchCompleteDelArchives, FetchRestoreArchives, FetchMaxItemNoByParentId } from '@/api/collect/collect'
import { FetchInitAssistEnter, FetchDoHandleEnterAnalysis, FetchInitAssistEnterTemp } from '@/api/ai/ai'
import { FetchArchivesClassTree } from '@/api/system/archivesClass'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import PreviewForm from '@/views/components/category/PreviewForm'
import UploadOriginal from './uploadOriginal/index'
import BigUpload from './uploadOriginal/bigUpload'
import BlukImport from './bulkImport/index'
import BlukEditing from './blukEditing/index'
import FileSeqAdjustment from './fileSeqAdjustment/index'
import CombineFile from './combineFile/index'
import InsertFile from './insertFile/index'
import CollectMoveFile from './collectMoveFile/index'
import Print from './print/index'
import FourTest from './fourTest/index'
import QuickPaper from './quickPaper/index'
import PackingBox from './packingBox/index'
import ArchivesFilling from './archivesFilling/index'
import qs from 'qs'
import { downloadFile, exportFile } from '@/utils/index'
import { mapGetters } from 'vuex'
import elDragDialog from '@/utils/dialog'

export default {
  name: 'CollectHeader',
  directives: {
    elDragDialog
  },
  components: { Treeselect, PreviewForm, UploadOriginal, BigUpload, BlukImport, BlukEditing, FileSeqAdjustment, CombineFile, InsertFile, CollectMoveFile, Print, FourTest, QuickPaper, PackingBox, ArchivesFilling },
  mixins: [collectionLibraryCrud, crud()],
  props: {
    selectedCategory: {
      type: Object,
      default: function() {
        return {}
      }
    },
    isTitleType: {
      type: Number,
      default: 2
    },
    selections: {
      type: Array,
      default: () => []
    },
    activeIndex: {
      type: Number,
      default: 0
    },
    isTabFile: {
      type: Boolean,
      default: false
    },
    isRecycle: {
      type: Boolean,
      default: false
    },
    test: {
      type: String,
      default: ''
    }
  },
  inject: ['parentsData'],
  data() {
    return {
      archivesBtnLoading: false,
      activeMenuIndex: '1',
      formVisible: false,
      formTitle: '项目',
      formPreviewData: [], // 预览界面data
      projectOptions: [],
      classifyOptions: [],
      moveVisible: false,
      recoverVisible: false,
      isDesFormType: 'arcives', // 区分是门类得还是档案得
      arcId: null,
      quickPaper: false,
      quickPaperArcId: [],
      totalSumAll: 0,
      categoryMenu: [],
      isAiAutoCategory: false,
      displayedText: '',
      formIsAddOrEdit: '',
      aIAssistEnterVisible: false,
      aiCategoryData: [],
      aiCategoryloading: false,
      childLoading: false,
      expandedRows: [],
      aiResultCaLoading: true, // ai分析得内容结果前得loading
      isDialogClosed: false, // 新增标志位，用于控制是否继续处理流式响应
      reader: null, // 用于存储响应体的读取器
      repeatVisible: false,
      repeatLoading: false,
      repeatResponseData: {},
      repeatData: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ]),
    collectTitle() {
      if (this.isTitleType === 2) {
        return '项目'
      } else if (this.isTitleType === 3) {
        if (this.selectedCategory.arrangeType === 1) {
          return '文件'
        } else {
          if (this.activeIndex === 1) {
            return '文件'
          } else {
            return '案卷'
          }
        }
      } else if (this.isTitleType === 4) {
        return '卷内'
      } else if (this.isTitleType === 6) {
        return '原文'
      }
      return ''
    },
    collectLevel() {
      if (this.isTitleType === 2) {
        return 1
      } else if (this.isTitleType === 3) {
        if (this.selectedCategory.arrangeType === 1) {
          return 3
        } else {
          if (this.activeIndex === 1) {
            if (this.quickPaper) {
              return 2
            } else {
              return 3
            }
          } else {
            return 2
          }
        }
      } else if (this.isTitleType === 4) {
        return 3
      } else if (this.isTitleType === 6) {
        return 4
      }
      return null
    },
    classType() {
      if (this.isTitleType === 2) {
        return ''
      } else if (this.isTitleType === 3) {
        if (this.selectedCategory.arrangeType === 1) {
          return 'is-juannei'
        } else {
          if (this.activeIndex === 1) {
            return 'is-juannei'
          } else {
            return 'is-anjuan'
          }
        }
      } else if (this.isTitleType === 4) {
        return 'is-juannei'
      } else if (this.isTitleType === 6) {
        return 'is-file'
      }
      return ''
    },
    placeholderType() {
      if (this.isTitleType === 2) {
        return '输入项目名称或编号'
      } else if (this.isTitleType === 3 || this.isTitleType === 4) {
        return '输入题名或档号'
      }
      return '输入项目名称或编号'
    },
    projectPlaceholder() {
      if (this.isTitleType === 2) {
        return '请选择项目分类'
      } else if (this.isTitleType === 3) {
        return '请选择项目阶段'
      }
      return '请选择项目分类'
    }
  },
  watch: {
    selectedCategory: function(newValue, oldValue) {
      if (newValue && newValue.id) {
        this.getInitArchivesClass()
      }
    },
    isTitleType: function(newValue, oldValue) {
      console.log('isTitleType', newValue)
    },
    activeIndex: function(newValue, oldValue) {
      if (newValue === 1) {
        this.parentsData.isTabFile = true
      } else {
        this.parentsData.isTabFile = false
      }
    }
  },
  created() {
  },
  mounted() {
    this.getInitArchivesClass()
    this.getCategoryDataTree()
  },
  methods: {
    getCategoryDataTree() {
      FetchCategoryMenu().then(res => {
        this.categoryMenu = res
      })
    },
    resetQuery() {
      this.query = {
        'search': null,
        'project_class': null,
        'archive_ctg_no': null
      }
      this.handleSearch(this.collectLevel)
    },
    // 筛选 - 档案分类
    getInitArchivesClass() {
      this.classifyOptions = []
      this.query = {
        'search': null,
        'project_class': null,
        'archive_ctg_no': null
      }
      const params = {
        'categoryId': this.selectedCategory.id
      }
      FetchArchivesClassTree(params).then((res) => {
        this.classifyOptions = JSON.parse(JSON.stringify(res))
      }).catch(err => {
        console.log(err)
      })
    },
    normalizer(node) {
      if (node.childArchivesClass === null) {
        delete node.childArchivesClass
      }
      return {
        id: node.code,
        label: `${node.name} - ${node.code}`,
        children: node.childArchivesClass
      }
    },
    handleSelect(key, keyPath) {
      console.log(key, keyPath)
    },
    // 著录界面-form/详情-api
    handleForm(type, isPaper) {
      this.formIsAddOrEdit = type

      if (type === 'add') {
        if (this.parentsData.parentsProjectId && this.isTitleType === 3) {
          console.log('项目下的案卷')
        } else {
          console.log('111')
          if (this.parentsData.parentsAnjuanRow && this.parentsData.parentsAnjuanRow.collect_formal === 2) {
            this.$message({ message: '当前档案处于归档流程中，不可操作新增，请先确认！', offset: 8 })
            return false
          }
        }
        this.arcId = null
        if (isPaper) {
          this.quickPaper = true
          this.formTitle = '新增案卷'
        } else {
          console.log('222')
          this.quickPaperArcId = []
          this.formTitle = '新增' + this.collectTitle
          this.quickPaper = false
        }
      } else if (type === 'edit') {
        this.quickPaper = false
        if (this.selections.length === 0) {
          this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
          return false
        } else if (this.selections.length > 1) {
          this.$message({ message: '编辑操作只可勾选唯一目标条目，请先确认！', offset: 8 })
          return false
        } else if (this.selections[0].collect_formal === 2) {
          this.$message({ message: '当前所选的档案处于归档流程中，不可操作编辑，请先确认！', offset: 8 })
          return false
        }
        this.arcId = this.selections[0].id
        this.formTitle = '编辑' + this.collectTitle
      }
      // this.form.dictionaryConfigId = {}
      // this.formPreviewData = []
      // 档案预编辑获取字段
      this.formVisible = true
      this.$nextTick(() => {
        this.getFormInfo(type)
      })
    },
    getFormInfo(type) {
      const currentPageSize = localStorage.getItem('currentPageSize')
      if (currentPageSize) {
        this.page.size = parseInt(currentPageSize)
      } else {
        this.page.size = 10
      }
      if (type === 'edit') {
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'id': this.arcId
        }
        FetchDetailsById(params).then(data => {
          // const showFiledAll = data.showFiled.filter(item => item.isSequence).sort((a, b) => a.isSequence - b.isSequence)
          const showFiledAll = data.showFiled
          this.$nextTick(() => {
            this.formPreviewData = showFiledAll
            this.isDesFormType = 'arcives'
            this.$nextTick(() => {
              this.$refs.previewForm.archivesType = 'edit'
              this.$refs.previewForm.addOrUpdateForm = data.echo
              this.$refs.previewForm.FetchNoFormatField(this.selectedCategory.id)
            })
          })
        })
      } else {
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel
        }
        FetchInitCategoryInputFieldByPid(params).then(data => {
          this.formPreviewData = data
          this.isDesFormType = 'arcives'

          this.$nextTick(() => {
            this.$refs.previewForm.archivesType = 'add'
            this.$refs.previewForm.activeIndex = this.activeIndex
            console.log('this.parentsData.parentsAnjuanRow ', this.parentsData.parentsAnjuanRow)
            console.log('this.collectTitle', this.collectTitle)
            const savePrevFromData = JSON.parse(localStorage.getItem('savePrevFromData'))
            console.log('savePrevFromData', savePrevFromData)

            if (savePrevFromData) {
              if ('record_no' in savePrevFromData && 'item_no' in savePrevFromData) {
                if (savePrevFromData.item_no && !isNaN(Number(savePrevFromData.item_no))) {
                  savePrevFromData.item_no = (parseInt(savePrevFromData.item_no) + 1).toString()
                }
              } else if ('record_no' in savePrevFromData) {
                if (savePrevFromData.record_no && !isNaN(Number(savePrevFromData.record_no))) {
                  savePrevFromData.record_no = (parseInt(savePrevFromData.record_no) + 1).toString()
                }
              } else if ('item_no' in savePrevFromData) {
                if (savePrevFromData.item_no && !isNaN(Number(savePrevFromData.item_no))) {
                  savePrevFromData.item_no = (parseInt(savePrevFromData.item_no) + 1).toString()
                }
              }
              // 查找 item_no 或 record_no 字段并进行补零操作
              const findAndPadField = (fieldName) => {
                const field = this.formPreviewData.find(item => item.fieldName === fieldName)
                if (field && field.isFilling) {
                  const fillingDigit = field.fillingDigit
                  if (savePrevFromData[fieldName]) {
                    savePrevFromData[fieldName] = savePrevFromData[fieldName].toString().padStart(fillingDigit, '0')
                  }
                }
              }

              findAndPadField('item_no')
              findAndPadField('record_no')

              this.$refs.previewForm.addOrUpdateForm = savePrevFromData
            } else if (this.collectTitle === '卷内' && this.parentsData.parentsAnjuanRow) {
              // 全宗fonds_no、门类archival_category_code、档案分类archive_ctg_no、年度archive_year、保管期限retention、案卷号record_no、责任者signer
              const rowAjData = this.parentsData.parentsAnjuanRow
              const fields = ['archive_ctg_no', 'archive_year', 'retention', 'record_no', 'signer']
              console.log('this.selectedCategory', this.selectedCategory)
              const result = { is_entity: 1, 'fonds_no': this.selectedCategory.fondsNo, 'archival_category_code': this.selectedCategory.code }

              fields.forEach(field => {
                if (rowAjData.hasOwnProperty(field)) {
                  result[field] = rowAjData[field]
                }
              })

              const params = {
                'archivesId': this.parentsData.parentsAnjuanRow.id
              }
              FetchMaxItemNoByParentId(params).then((res) => {
                if (res) {
                  const field = this.formPreviewData.find(item => item.fieldName === 'item_no')
                  if (field && field.isFilling) {
                    const fillingDigit = field.fillingDigit
                    result.item_no = (parseInt(res) + 1).toString().padStart(fillingDigit, '0')
                  } else {
                    result.item_no = this.incrementString(res)
                  }
                } else {
                  result.item_no = ''
                }
              }).catch(err => {
                console.log(err)
              })
              console.log('result', result)
              this.$refs.previewForm.addOrUpdateForm = result
            }

            this.$refs.previewForm.FetchNoFormatField(this.selectedCategory.id)
          })
        })
      }
    },
    incrementString(str) {
      const num = parseInt(str, 10)
      const incrementedNum = num + 1
      const numLength = str.length
      if (/^0+$/.test(str.replace(/\d/g, '0'))) {
        return incrementedNum.toString().padStart(numLength, '0')
      }
      return incrementedNum.toString()
    },
    // form - submit
    handlerArchivesSubmit(type) {
      this.$refs.previewForm.submitForm('addOrUpdateForm', this.selectedCategory.id, this.quickPaperArcId, type)
    },
    handlerArchivesSubmitAndAdd() {
      this.$refs.previewForm.submitForm('addOrUpdateForm', this.selectedCategory.id, this.quickPaperArcId)
    },
    formLoadingShow(loadingType) {
      this.archivesBtnLoading = loadingType
    },
    repeatDataShow(data) {
      this.repeatVisible = true
      this.repeatLoading = true
      this.repeatData = []
      if (data) {
        this.repeatResponseData = data
        this.repeatData.push(data.archivesSummary)
        setTimeout(() => {
          this.repeatLoading = false
        }, 500)
      }
    },
    handleRepeatClose() {
      this.repeatResponseData = {}
      this.repeatData = []
      this.repeatLoading = false
      this.repeatVisible = false
    },
    // 关闭
    handleClose(done) {
      this.formVisible = false
      this.quickPaper = false
      localStorage.removeItem('savePrevFromData')
      this.aiCategoryData = []
      this.isAiAutoCategory = false
      this.displayedText = '' // 清空 displayedText
      this.isDialogClosed = true // 设置标志位为 true
      if (this.reader) {
        this.reader.cancel() // 取消读取器，终止流式响应
      }
      done()
    },
    // 删除
    toDelete() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作删除，请先确认！', offset: 8 })
        return false
      }
      if (this.collectLevel === 4) {
        if (this.parentsData.parentsAnjuanRow && this.parentsData.parentsAnjuanRow.collect_formal === 2) {
          this.$message({ message: '当前档案处于归档流程中，不可操作删除，请先确认！', offset: 8 })
          return false
        }
      }
      let messageTip
      if (this.activeIndex === 1) {
        messageTip = '此删除将把会所选条目与其子集彻底删除'
      } else {
        messageTip = '此删除将把会所选条目与其子集放入回收站'
      }
      this.$confirm(messageTip + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        if (this.activeIndex === 1) {
          const archivesIds = []
          this.selections.forEach(val => {
            archivesIds.push(val.id)
          })
          const params = {
            'categoryId': this.selectedCategory.id,
            'categoryLevel': this.collectLevel,
            'archivesIds': archivesIds
          }
          FetchCompleteDelArchives(params).then((res) => {
            if (res.code !== 500) {
              this.$message({ message: res, type: 'success', offset: 8 })
              localStorage.removeItem('currentPageSize')
              localStorage.removeItem('currentPage')
              this.handleSearch(this.collectLevel)
            } else {
              this.$message({ message: '删除所选档案失败', type: 'error', offset: 8 })
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.handleDelConfirm()
        }
      }).catch(() => {
      })
    },
    // 卷内 - 移除
    toMove() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作删除，请先确认！', offset: 8 })
        return false
      }
      this.moveVisible = true
    },
    // 删除 - 确认
    handleDelConfirm() {
      if (this.collectLevel === 4) {
        const params = this.selections.map((item) => {
          const json = {}
          json.archivesId = item.archive_id
          json.categoryId = this.selectedCategory.id
          json.documentFileId = item.document_file_id
          json.documentId = item.document_id
          json.id = item.id
          return json
        })
        FetchDeleteArchivesFile(params).then((res) => {
          if (res === 'SUCCESS') {
            localStorage.removeItem('currentPageSize')
            localStorage.removeItem('currentPage')
            this.$message({ message: '删除成功', type: 'success', offset: 8 })
            this.handleSearch(this.collectLevel)
          } else {
            this.$message({ message: '删除所选电子原文失败', type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      } else {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds
        }
        collectDel(params).then((res) => {
          if (res.includes('成功')) {
            localStorage.removeItem('currentPageSize')
            localStorage.removeItem('currentPage')
            this.$message({ message: '删除成功', type: 'success', offset: 8 })
            this.handleSearch(this.collectLevel)
          } else {
            this.$message({ message: res, type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 卷内 - 移出 确认
    handleMoveConfirm() {
      const archivesIds = []
      this.selections.forEach(val => {
        archivesIds.push(val.id)
      })
      const params = {
        'categoryId': this.selectedCategory.id,
        'categoryLevel': this.collectLevel,
        'archivesIds': archivesIds,
        'parentsId': this.parentsData.parentsAnjuanId
      }
      FetchRemoveArchivesSingle(params).then((res) => {
        if (res === true) {
          localStorage.removeItem('currentPageSize')
          localStorage.removeItem('currentPage')
          this.$message({ message: '移出成功', type: 'success', offset: 8 })
          this.handleSearch(this.collectLevel)
        } else {
          this.$message({ message: '移出失败', type: 'error', offset: 8 })
        }
        this.moveVisible = false
      }).catch(err => {
        console.log(err)
      })
    },
    // 原文上传
    fileUpload(uploadType) {
      if (uploadType !== 2) {
        if (this.isTitleType !== 6) {
          if (this.selections.length === 0) {
            this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
            return false
          }
          if (this.selections.length > 1) {
            this.$message({ message: '上传操作只可勾选唯一目标条目，请先确认！', offset: 8 })
            return false
          }
          const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
          if (isHasFillFormal) {
            this.$message({ message: '您所选的条目有正在归档流程中，不可操作原文上传，请先确认！', offset: 8 })
            return false
          }
          this.arcId = this.selections[0].id
        } else {
          if (this.parentsData.parentsAnjuanRow && this.parentsData.parentsAnjuanRow.collect_formal === 2) {
            this.$message({ message: '当前档案处于归档流程中，不可操作原文上传，请先确认！', offset: 8 })
            return false
          }

          if (this.selectedCategory.arrangeType === 1) {
            this.arcId = this.parentsData.parentsAnjuanId
          } else {
            if (this.parentsData.isTabFile) {
              this.arcId = this.parentsData.parentsAnjuanId
            } else {
              this.arcId = this.parentsData.parentsJuanneiId
            }
          }
        }
      }
      if (uploadType === 0) {
        this.$refs.uploadOriginalRef.uploadTitle = '普通上传'
        this.$refs.uploadOriginalRef.uploadVisible = true
      } else if (uploadType === 1) {
        this.$refs.uploadBigRef.uploadBigVisible = true
      } else if (uploadType === 2) {
        this.$refs.uploadOriginalRef.uploadTitle = '原文目录上传'
        this.$refs.uploadOriginalRef.uploadVisible = true
      }
      if (this.$refs.uploadOriginalRef.uploadVisible) {
        this.$refs.uploadOriginalRef.uploadType = uploadType
        this.$refs.uploadOriginalRef.fileList = []
      }
    },
    // 批量导入
    handleBlukImport() {
      if (this.parentsData.parentsAnjuanRow && this.parentsData.parentsAnjuanRow.collect_formal === 2) {
        this.$message({ message: '当前档案处于归档流程中，不可操作批量导入，请先确认！', offset: 8 })
        return false
      }
      this.$nextTick(() => {
        this.$refs.blukImportRef.bulkImportVisible = true
        this.$refs.blukImportRef.getInitCategoryInputFieldByPid()
      })
    },
    // 批量修改
    handleBlukEditing() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作批量修改，请先确认！', offset: 8 })
        return false
      }
      this.$nextTick(() => {
        this.$refs.blukEditingRef.bulkEditingVisible = true
        this.$refs.blukEditingRef.getInitCategoryInputFieldByPid()
      })
    },
    // 案卷/文件/卷内顺序调整
    handleJnSeqAdjustment(type) {
      if (type === 'juannei') {
        if (this.selections.length === 0) {
          this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
          return false
        }
        if (this.selections.length > 1) {
          this.$message({ message: '卷内顺序调整操作只可勾选唯一目标条目，请先确认！', offset: 8 })
          return false
        }
        const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
        if (isHasFillFormal) {
          this.$message({ message: '您所选的条目有正在归档流程中，不可操作卷内顺序调整，请先确认！', offset: 8 })
          return false
        }
        this.$nextTick(() => {
          this.$refs.fileSeqAdjustmentRef.titleAdjustment = '卷内顺序调整'
          this.$refs.fileSeqAdjustmentRef.isJuannei = true
        })
      } else {
        if (this.selections.length < 2) {
          this.$message({ message: '请选择多个' + (type === 'file' ? '文件' : '案卷') + '后进行操作！', offset: 8 })
          return false
        }
        const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
        if (isHasFillFormal) {
          this.$message({ message: '您所选的条目有正在归档流程中，不可操作案卷/文件顺序调整，请先确认！', offset: 8 })
          return false
        }
        this.$nextTick(() => {
          if (type === 'anjuan') {
            this.$refs.fileSeqAdjustmentRef.titleAdjustment = '案卷顺序调整'
          } else {
            this.$refs.fileSeqAdjustmentRef.titleAdjustment = '文件顺序调整'
          }
          this.$refs.fileSeqAdjustmentRef.isJuannei = false
        })
      }
      this.$nextTick(() => {
        this.$refs.fileSeqAdjustmentRef.getDoArchivesAdjust()
      })
    },
    // 档号更新
    handleFileNumberUpdate(type) {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作档号更新，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此操作将会自动重新生成档号' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        // updateType 更新类别  1.档号更新  2.卷内档号更新
        let updateType
        if (type === 0) {
          updateType = 1
        } else {
          updateType = 2
        }
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds,
          'updateType': updateType
        }
        FetchUpdateArchivesNo(params).then((res) => {
          if (res.code !== 500) {
            this.$message({ message: '档号更新成功', type: 'success', offset: 8 })
            this.handleSearch(this.collectLevel)
          } else {
            this.$message({ message: res.message, type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    // 拆卷
    handleUncoil() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作拆卷，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('拆卷之后，对应的案卷数据将会自动删除' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'archivesIds': archivesIds
        }
        FetchDisbandArchives(params).then((res) => {
          if (res.code !== 500) {
            this.$message({ message: '拆卷成功', type: 'success', offset: 8 })
            this.handleSearch(this.collectLevel)
          } else {
            this.$message({ message: '拆卷失败', type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    // 合卷
    handleCombineFile() {
      if (this.selections.length < 2) {
        this.$message({ message: '合卷操作至少勾选2个案卷，请重试！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作合卷，请先确认！', offset: 8 })
        return false
      }
      this.$refs.combineFileRef.getTargetList()
    },
    // 插件
    handleInsertFile() {
      if (this.collectLevel === 3) {
        if (this.selections.length === 0) {
          this.$confirm('您未勾选条目，否则直接选择所有条目' + '<span>你是否还要继续？</span>', '提示', {
            confirmButtonText: '继续',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }).then(() => {
            this.$refs.insertFileRef.fileNoSelectionData = this.parentsData.$refs.anjuanEle.$refs.ajContent.$refs.tableList.anjuanData
            this.$refs.insertFileRef.getInsertViewTable()
          }).catch(() => {
          })
        } else {
          this.$refs.insertFileRef.getInsertViewTable()
        }
      } else {
        const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
        if (this.selections.length !== 1) {
          this.$message({ message: '插卷操作只可勾选唯一目标条目，请先确认！', offset: 8 })
          return false
        } else if (isHasFillFormal) {
          this.$message({ message: '您所选的条目有正在归档流程中，不可操作插件，请先确认！', offset: 8 })
          return false
        } else {
          this.$refs.insertFileRef.getInsertViewTable()
        }
      }
    },
    // 移动
    handleCollectMoveFile() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作移动，请先确认！', offset: 8 })
        return false
      }
      // if (this.isTitleType === 2) {
      //   this.$refs.collectMoveFileRef.parentsId = null
      // } else if (this.isTitleType === 3) {
      //   if (this.selectedCategory.arrangeType === 1) {
      //     this.$refs.collectMoveFileRef.parentsId = null
      //   } else {
      //     if (this.activeIndex === 1) {
      //       this.$refs.collectMoveFileRef.parentsId = null
      //     } else {
      //       this.$refs.collectMoveFileRef.parentsId = this.parentsData.parentsProjectId
      //     }
      //   }
      // } else if (this.isTitleType === 4) {
      //   this.$refs.collectMoveFileRef.parentsId = this.parentsData.parentsAnjuanId
      // } else if (this.isTitleType === 6) {
      //   if (this.selectedCategory.arrangeType === 1) {
      //     this.$refs.collectMoveFileRef.parentsId = this.parentsData.parentsAnjuanId
      //   } else {
      //     if (this.parentsData.isTabFile) {
      //       this.$refs.collectMoveFileRef.parentsId = this.parentsData.parentsAnjuanId
      //     } else {
      //       this.$refs.collectMoveFileRef.parentsId = this.parentsData.parentsJuanneiId
      //     }
      //   }
      // }
      this.$nextTick(() => {
        this.$refs.collectMoveFileRef.collectMoveFileVisible = true
        if (!this.isTitleType) {
        // 默认行为：如果 isTitleType 未定义，设置为 null
          this.setParentsId(this.$refs, null)
        } else if (this.isTitleType === 2 ||
           (this.isTitleType === 3 && this.selectedCategory.arrangeType === 1) ||
           (this.isTitleType === 3 && this.activeIndex === 1)) {
        // 统一处理 null 的情况
          this.setParentsId(this.$refs, null)
        } else if (this.isTitleType === 3) {
          this.setParentsId(this.$refs, this.parentsData?.parentsProjectId ?? null)
        } else if (this.isTitleType === 4) {
          this.setParentsId(this.$refs, this.parentsData?.parentsAnjuanId ?? null)
        } else if (this.isTitleType === 6) {
          if (this.selectedCategory.arrangeType === 1 || this.parentsData.isTabFile) {
            this.setParentsId(this.$refs, this.parentsData?.parentsAnjuanId ?? null)
          } else {
            this.setParentsId(this.$refs, this.parentsData?.parentsJuanneiId ?? null)
          }
        }
      })
    },
    setParentsId(safeRef, value) {
      if (safeRef && safeRef.collectMoveFileRef) {
        safeRef.collectMoveFileRef.parentsId = value
      } else {
        console.warn('collectMoveFileRef is not available')
      }
    },
    // 归档
    handleFiling() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，勿重复操作，请先确认！！', offset: 8 })
        return false
      }
      this.$refs.archivesFillingRef.archivesFillingVisible = true
    },
    handleFillingToFourTest(resultList) {
      this.$refs.fourTestRef.fourTestVisible = true
      this.$refs.fourTestRef.tableData = this.selections
      this.$refs.fourTestRef.updateTableData(resultList, this.selections)
      this.$refs.fourTestRef.isCheck = true
    },
    // 退回预归档库
    handleReturn() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作退回预归档库，请先确认！！', offset: 8 })
        return false
      }
      this.$confirm('此操作将把会所选条目退回到预归档库' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = this.selections.map(item => item.id)
        const params = {
          'categoryId': this.selectedCategory.id,
          'archivesIds': archivesIds
        }
        FetchReturnReDocument(params).then((res) => {
          if (res.code !== 500) {
            if (res === 0) {
              this.crud.notify('', CRUD.NOTIFICATION_TYPE.INFO)
              this.$message({ message: '当前数据中不包含预归档数据，无法返回', offset: 8 })
            } else {
              this.$message({ message: '已成功返回' + res + '条来自预归档的数据', type: 'success', offset: 8 })
            }
            this.handleSearch(this.collectLevel)
          } else {
            this.$message({ message: res.message, type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    // 导出
    handleExport() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds
        }
        exportFile(this.baseApi + '/api/collect/exportDate?' + qs.stringify(params, { indices: false }))
      }).catch(() => {
      })
    },
    // 打印
    handlePrint() {
      if (this.selections.length === 0) {
        this.$refs.printRef.form.printRange = '当页条目'
        let currentTableData = []
        if (this.collectLevel === 2) {
          currentTableData = this.parentsData.$refs.anjuanEle.$refs.ajContent.$refs.tableList.anjuanData
        } else if (this.collectLevel === 3) {
          if (this.isTitleType === 3) {
            currentTableData = this.parentsData.$refs.anjuanEle.$refs.ajContent.$refs.tableList.anjuanData
          } else {
            currentTableData = this.parentsData.$refs.juanneiEle.junneiData
          }
        }
        this.$refs.printRef.currentTable = JSON.parse(JSON.stringify(currentTableData))
      } else {
        this.$refs.printRef.form.printRange = '勾选条目'
      }
      this.$refs.printRef.printVisible = true
    },
    // 四性检测
    handleFourTest() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作四性检测，请先确认！', offset: 8 })
        return false
      }
      this.$refs.fourTestRef.fourTestVisible = true
      this.selections.forEach((item, index) => {
        this.$set(this.selections[index], 'reportResult', {})
      })
      this.$refs.fourTestRef.tableData = this.selections
    },
    // 目录下载
    handleCatalogDownload() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此操作将下载所选条目目录' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds
        }
        exportFile(this.baseApi + '/api/collect/catalogDownload?' + qs.stringify(params, { indices: false }))
      }).catch(() => {
      })
    },
    // 快速组卷
    handleQuickPaper() {
      this.$refs.quickPaperRef.quickVisible = true
    },
    // 手工组卷
    handlePaper() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }

      this.quickPaperArcId = this.selections.map(item => item.id)
      this.handleForm('add', 1)
    },
    // 装盒 / 分卷装盒
    handlePackingBox(type) {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      const isHasFillFormal = this.selections.some(item => item.collect_formal === 2)
      if (isHasFillFormal) {
        this.$message({ message: '您所选的条目有正在归档流程中，不可操作装盒，请先确认！！', offset: 8 })
        return false
      }
      if (this.selectedCategory.arrangeType === 2) {
        if (type === 1) {
          if (this.selections.length > 1) {
            this.$message({ message: '只可勾选唯一目标条目，请先确认！', offset: 8 })
            return false
          }
        }
        if (this.selections[0].child === 0) {
          this.$message({ message: '当前选中的档案无相关卷内文件，不可装盒！', type: 'error', offset: 8 })
          return
        }
      }
      if (this.selections[0].case_no) {
        this.$message({ message: '当前档案已装盒，请勿重复操作！', type: 'error', offset: 8 })
        return
      }
      // 后面与后端对接确定字段name
      // const existsNotEmpty = this.selections.some(item => item.caseNum)
      // if (existsNotEmpty) {
      //   this.$message('所选条目中存在已装盒档案，请勿重复操作！')
      //   return false
      // }
      this.$refs.packingBox.packingVisible = true
      this.$refs.packingBox.isPackingOrPartType = type
      this.$refs.packingBox.packFileCategory = this.parentsData.listCategory
      if (type === 0) {
        this.$refs.packingBox.packingTitle = '装盒'
      } else {
        this.$refs.packingBox.packingTitle = '分卷装盒'
        this.$refs.packingBox.getViewTable()
      }
      this.getTotalSumAll()
    },
    getTotalSumAll() {
      this.totalSumAll = 0
      this.selections.map((item) => { if (!isNaN(item.child)) this.totalSumAll += item.child })
      if (isNaN(this.totalSumAll)) {
        return 0
      }
      return this.totalSumAll
    },
    // 原文内的附件下载
    handleOriginalDownload() {
      if (this.selections.length > 1 || this.selections.length === 0) {
        this.$message({ message: '下载操作只可勾选唯一目标条目，请先确认！', offset: 8 })
        return false
      }
      const url = this.baseApi + '/downloadFile' + this.selections[0].file_path
      fetch(url).then(res => res.blob()).then(blob => {
        downloadFile(blob, this.selections[0].file_name.split('.')[0], this.selections[0].file_type)
      }).catch(() => {
        this.$message({ message: '下载文件失败！', type: 'error', offset: 8 })
      })
    },
    // 回收站 - 恢复
    toRecover() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此恢复将会把所选条目及其子集一并恢复' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds,
          'collectFormal': this.isTitleType === 2 ? 1 : null
        }
        FetchRestoreArchives(params).then((res) => {
          if (res.code !== 500) {
            localStorage.removeItem('currentPageSize')
            localStorage.removeItem('currentPage')
            if (res.includes('成功')) {
              this.$message({ message: res, type: 'success', offset: 8 })
            } else {
              this.$message({ message: res, type: 'error', offset: 8 })
            }
            this.handleSearch(this.collectLevel)
          } else {
            this.$message({ message: '恢复所选档案失败', type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    // 回收站 - 彻底删除
    toCompletelyDelete() {
      if (this.selections.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此删除将把会所选条目与其子集彻底删除' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds
        }
        FetchCompleteDelArchives(params).then((res) => {
          if (res.code !== 500) {
            localStorage.removeItem('currentPageSize')
            localStorage.removeItem('currentPage')
            this.$message({ message: res, type: 'success', offset: 8 })
            this.handleSearch(this.collectLevel)
          } else {
            this.$message({ message: '删除所选档案失败', type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    closeDialog(data) {
      this.formVisible = false
      this.quickPaper = false
      setTimeout(() => {
        this.handleSearch(this.collectLevel)
      })
    },
    handleAiCategory() {
      this.aIAssistEnterVisible = true
      this.aiCategoryloading = true
      const params = {
        'page': 0,
        'size': 10,
        'isHandle': 0
      }
      FetchInitAssistEnter(params).then(data => {
        data.forEach(function(item, index) {
          item.hasChildren = true
          item.children = null
          item.childLoading = false
        })
        this.aiCategoryData = data
        this.aiCategoryloading = false
      })
    },
    // 获取自动分析内容和提问
    getDoHandleEnterAnalysis(row) {
      this.isAiAutoCategory = true
      this.aIAssistEnterVisible = false
      const params = {
        'categoryId': this.selectedCategory.id,
        'anId': row.id
      }
      FetchDoHandleEnterAnalysis(params).then(data => {
        // const inputMessage = data.query + '需要提取得内容部分是' + data.context
        this.sendMessage(data.query, data.context)
      })
    },
    handleExpandChange(row, expandedRows) {
      if (expandedRows.length > 0) {
        // 展开行
        this.loadFile(row)
      } else {
        // 收起行
        row.children = null
      }
    },
    loadFile(row) {
      row.childLoading = true
      const params = {
        'anId': row ? row.id : null
      }
      FetchInitAssistEnterTemp(params).then(data => {
        row.children = data
        setTimeout(() => {
          row.childLoading = false
        }, 500)
      }).catch(error => {
        console.error('请求接口失败', error)
        setTimeout(() => {
          row.childLoading = false
        }, 500)
      })
    },
    handleAIClose() {
      this.aiCategoryData = []
      this.aIAssistEnterVisible = false
    },
    getFileSize(fileSize) {
      const fileSizeInKB = (fileSize / 1024).toFixed(2) + 'kB'
      const fileSizeInB = fileSize + 'B'
      return (fileSize / 1024) <= 0.01 ? fileSizeInB : fileSizeInKB
    },
    // 向deepseek发出提问和分析内容
    async sendMessage(prompt, context) {
      const linkSrc = process.env.NODE_ENV === 'production' ? window.g.AIDeepSeekUrl : process.env.VUE_APP_AIDEEPSEEK_API
      this.displayedText = ''
      this.isDialogClosed = false // 重置标志位
      try {
        // { 'role': 'system', 'content': '你是一个数据分析助手' },
        const messages = [
          { 'role': 'user', 'content': `${context}\n\n${prompt}` }
        ]
        const response = await fetch(linkSrc + '/api/generate', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            model: 'deepseek-r1:14b',
            // model: 'qwen:7b',
            prompt: messages[0].content,
            stream: true
          })
        })

        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`)
        }

        this.reader = response.body.getReader() // 存储读取器
        const decoder = new TextDecoder('utf-8')
        let done = false

        while (!done && !this.isDialogClosed) { // 检查标志位
          this.aiResultCaLoading = false
          const { done: isDone, value } = await this.reader.read()
          done = isDone
          if (done) break

          const chunk = decoder.decode(value)
          const lines = chunk.split('\n')

          lines.forEach(line => {
            if (line.trim() !== '') {
              try {
                const data = JSON.parse(line)
                if (data.response && !this.isDialogClosed) { // 再次检查标志位
                  this.displayedText += data.response
                }
              } catch (error) {
                console.error('解析JSON数据出错:', error)
              }
            }
          })

          // 滚动条始终保持在底部
          const container = this.$refs.typingContainer
          if (container) {
            container.scrollTop = container.scrollHeight
          }
        }
      } catch (error) {
        console.error('请求出错:', error)
        this.displayedText = '请求出错，请稍后再试。'
        this.aiResultCaLoading = false
      } finally {
        this.aiResultCaLoading = false
        if (!this.isDialogClosed) {
          // 去除 <think> 和 </think> 之间的内容
          const thinkStartIndex = this.displayedText.indexOf('<think>')
          const thinkEndIndex = this.displayedText.indexOf('</think>')
          let lastContent = this.displayedText
          if (thinkStartIndex !== -1 && thinkEndIndex !== -1) {
            lastContent = lastContent.slice(0, thinkStartIndex) + lastContent.slice(thinkEndIndex + '</think>'.length)
          }
          // 提取 JSON 部分
          const startIndex = lastContent.indexOf('{')
          const endIndex = lastContent.lastIndexOf('}')
          if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
            const jsonStr = lastContent.slice(startIndex, endIndex + 1)
            const jsonData = JSON.parse(jsonStr)
            console.log('提取并过滤后的 JSON 数据:', jsonData)
            jsonData.fonds_no = this.selectedCategory.fondsNo
            jsonData.archival_category_code = this.selectedCategory.code
            jsonData.is_entity = 1
            console.log('jsonData', jsonData)
            this.$refs.previewForm.addOrUpdateForm = jsonData
          }
        }
        this.reader = null // 清空读取器
      }
    },
    replaceSeparators(str) {
      return str.replace(/[，,、]/g, ' ')
    }
  }
}
</script>

<style lang='scss' scoped>
::v-deep .vue-treeselect__list-item{
  width: 220px;
}
::v-deep .vue-treeselect__menu {
  padding: 20px 0;
}
::v-deep .vue-treeselect__option--highlight{
  background: #f5f9fc !important;
  color: #0348f3 !important;
}
::v-deep .vue-treeselect__option-arrow-container .vue-treeselect__option-arrow{
  color: #1c1c1c !important;
}
::v-deep .vue-treeselect__placeholder{
  font-size: 14px;
}
::v-deep .vue-treeselect__label-container{
  font-size: 14px;
  height: 34px;
  line-height: 34px;
  color: #1c1c1c;
}
::v-deep .vue-treeselect__option.vue-treeselect__option--disabled{
  .vue-treeselect__label-container{
    color: #545b65 !important;
  }
}
::v-deep.vue-treeselect--has-value .vue-treeselect__single-value{
  font-size: 14px;
}
.ai-preview-dialog{
  ::v-deep .el-dialog{
    width: 1300px !important;
    .preview-content{
      width: 728px !important;
    }
  }
}
.aiAssist-dialog{
  ::v-deep .el-dialog{
    width: 1160px !important;
  }
}

pre {
  background-color: #f4f4f4;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  white-space: pre-wrap;
  word-wrap: break-word;
  height: calc(100vh - 330px);
  overflow: hidden;
  overflow-y: auto;
}
::v-deep .el-table.child-table tr{
  background-color: #f0f9eb;
}
</style>
