<template>
  <div class="app-container">
    <!-- 门类列表 -->
    <div class="container-main">
      <div class="elect-cont-left">
        <TreeList @nodeClick="handleNodeClick" />
      </div>
      <div class="elect-cont-right" style="position: relative;">
        <!--工具栏-->
        <div class="head-container">
          <div class="head-search" style=" align-items: center;">
            <!-- 搜索 -->
            <el-input v-model="query.search" clearable size="small" placeholder="输入题名搜索" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
            <rrOperation />
            <el-button class="filter-item filter-search" size="mini" type="success" icon="el-icon-search" @click="showAdvancedSearch">高级检索</el-button>
            <el-button class="filter-item filter-refresh" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置</el-button>

            <div v-if="crud.query.intelligenceSearch" class="advanced-search-result">
              <span style="font-size: 12px; color: #666;">高级检索：</span>
              <span style="font-size: 12px; color: #409EFF; margin-right: 10px; cursor: pointer;" @click="showAdvancedSearch">{{ advancedSearchDisplayText }}</span>
            </div>
          </div>
          <crudOperation :permission="permission">
            <template v-slot:left>
              <!-- 新增 -->
              <el-button size="mini" @click="handleForm('add')"><i class="iconfont icon-xinzeng" />新增</el-button>
              <!-- 修改 -->
              <el-button size="mini" :disabled="crud.selections.length !== 1" @click="handleForm('edit')"><i class="iconfont icon-bianji" />编辑</el-button>
              <!-- 删除btn 多选 -->
              <el-button size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)"><i class="iconfont icon-shanchu" />删除</el-button>
              <el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length === 0" @click="doExport(crud.selections)">
                <i class="iconfont icon-daochu" />
                导出
              </el-button>
            </template>
            <template v-slot:rightButtonGroup>
              <div>
                <!-- <el-button size="mini" :disabled="crud.selections.length !== 1" @click="handleTestFile(1)"><i class="iconfont icon-shangchuan2" />原文上传</el-button> -->
                <el-button size="mini" :disabled="crud.selections.length === 0" @click="handleBatch(crud.selections)"><i class="iconfont icon-piliangchengjian" />批量成件</el-button>
                <el-button size="mini" :disabled="crud.selections.length === 0" @click="handelMerge(crud.selections)"><i class="iconfont icon-hebingchengjian" />合并成件</el-button>
                <el-button size="mini" :disabled="crud.selections.length === 0" @click="handleMove"><i class="iconfont icon-yidong" />移动</el-button>
              </div>
            </template>
          </crudOperation>
        </div>
        <!--表格渲染-->
        <div class="container-right">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <el-table
            ref="table"
            v-loading="crud.loading"
            :data="crud.data"
            style="width: 100%;"
            @row-click="clickRowHandler"
            @select="crud.selectChange"
            @select-all="crud.selectAllChange"
            @selection-change="crud.selectionChangeHandler"
            @cell-dblclick="tableDoubleClick"
            @mousedown.native="onMouseDown"
            @mouseup.native="onMouseUp"
          >
            <el-table-column type="selection" align="center" width="55" />
            <el-table-column label="序号" width="55" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <span>{{ (crud.page.page-1) * crud.page.size + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="原文" prop="filesNum" width="55" align="center">
              <template slot-scope="scope">
                {{ scope.row.filesNum === '' ? 0 : scope.row.filesNum }}
              </template>
            </el-table-column>
            <el-table-column v-for="field in tableDisplayFields" :key="field.id" :label="field.fieldCnName" :align="field.displayformatType" :width="field.displayLength" show-overflow-tooltip>
              <template slot="header">
                <el-tooltip
                  class="item"
                  effect="dark"
                  :content="field.fieldCnName"
                  placement="top-start"
                >
                  <span>{{ field.fieldCnName }}</span>
                </el-tooltip>
              </template>
              <template slot-scope="scope">
                {{ scope.row[field.fieldName] }}
              </template>
            </el-table-column>
          </el-table>

          <!--分页组件-->
          <pagination v-if="crud.data.length !== 0" />

        </div>

        <File ref="fileEle" :selected-document="selectedDocument" />

        <detail ref="archivesInfo" :selected-document="selectedDocument" />
        <!-- 批量成件 -->
        <batchFile ref="batchForm" :selected-document="selectedDocument" @refresh="crud.refresh" />
        <!-- 移动 -->
        <moveFile ref="moveForm" :selected-document="selectedDocument" @refresh="crud.refresh" />
        <!-- 合并成件 -->
        <el-dialog class="dialog-middle" :modal-append-to-body="false" :close-on-click-modal="false" :before-close="closeDialog" :visible="mergeVisible" title="合并成件">
          <span class="dialog-right-top" />
          <span class="dialog-left-bottom" />
          <div class="setting-dialog">
            <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
              <el-form-item label="档案门类" prop="categoryId">
                <treeselect
                  v-model="form.categoryId"
                  :options="categoryTree"
                  style="width: 400px;"
                  :normalizer="normalizer"
                  flat
                  :multiple="false"
                  :default-expand-level="6"
                  placeholder="请选择档案门类"
                  @select="handleSelectCategory"
                />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="closeDialog">取消</el-button>
              <el-button type="primary" @click="handleFormMerge()">确定</el-button>
            </div>
          </div>
        </el-dialog>

        <!--新增 / 编辑 表单组件-->
        <el-dialog class="preview-dialog" :modal-append-to-body="false" :close-on-click-modal="false" append-to-body :before-close="closeDialog" :visible="formVisible" :title="formTitle">
          <span class="dialog-right-top" />
          <span class="dialog-left-bottom" />
          <div class="setting-dialog">
            <PreviewForm
              ref="previewForm"
              :form-preview-data.sync="formPreviewData"
              :selected-category="selectedCategory"
              :parents-id="parentsId"
              :arc-id="arcId"
              :is-des-form-type="isDesFormType"
              :is-disabled="isDisabled"
              :selected-document="selectedDocument"
              :is-has-code="isHasCode"
              @close-dialog="closeDialog"
              @formLoadingShow="formLoadingShow"
            />
            <div slot="footer" class="dialog-footer" :style="{ marginTop: isDesFormType === 'mergeFile' ? '85px !important' : '20px !important' }">
              <el-button type="text" @click="closeDialog">取消</el-button>
              <el-button :loading="archivesBtnLoading" type="primary" @click="handlerArchivesSubmit">确定</el-button>
            </div>
          </div>
        </el-dialog>

        <!--高级检索模态框-->
        <AdvancedSearchModal
          :visible.sync="advancedSearchVisible"
          :selected-document="selectedDocument"
          :initial-conditions="advancedSearchConditions"
          @search="handleAdvancedSearch"
        />
      </div>
    </div>
  </div>
</template>

<script>
import CRUD, { presenter, header } from '@crud/crud'
import { preLibraryCrud } from './mixins/index'
import { FetchMenuByFondsId, FetchInitCategoryInputFieldByPid } from '@/api/system/category/category'
import PrearchiveCrud from '@/api/prearchiveLibrary/prearchiveLibrary'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import TreeList from './treeList'
import PreviewForm from '@/views/components/category/PreviewForm'
import batchFile from './module/batchFile'
import moveFile from './module/moveFile'
import detail from './module/detail'
import File from './file/index'
import AdvancedSearchModal from './advancedSearchModal'

import { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

export default {
  name: 'PrearchiveLibrary',
  components: { TreeList, PreviewForm, batchFile, moveFile, detail, Treeselect, rrOperation, crudOperation, pagination, File, AdvancedSearchModal },
  cruds() {
    return [
      CRUD({
        title: '预归档库', url: 'api/re-document/initPreDocument',
        crudMethod: { ...PrearchiveCrud },
        optShow: {
          add: false,
          edit: false,
          del: false,
          download: false,
          group: false,
          reset: false
        },
        queryOnPresenterCreated: false
      })
    ]
  },
  provide() {
    return {
      parentsData: this
    }
  },
  mixins: [presenter(), header(), preLibraryCrud],
  data() {
    return {
      archivesBtnLoading: false,
      permission: {},
      tableDisplayFields: [], // table-list-title字段
      arrySort: [],
      selectedDocument: {},
      mergeVisible: false,
      categoryTree: [],
      form: {},
      loadSource: [],
      rules: {
        target: [
          { required: true, message: '请选择档案门类', trigger: 'input' }
        ]
      },
      formVisible: false,
      formTitle: '新增文件',
      formPreviewData: [],
      selectedCategory: null,
      parentsId: null,
      arcId: null,
      isDesFormType: 'prearchiveLibrary',
      isDisabled: false,
      isHasCode: false,
      selectedCategoryMerge: null,
      timer: null,
      mousedownTime: 0,
      mousedownX: 0,
      mousedownY: 0,
      fileOriginal: null,
      fileOneVisible: false,
      advancedSearchVisible: false,
      advancedSearchConditions: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ]),
    // 格式化高级检索条件显示文案
    advancedSearchDisplayText() {
      if (!this.advancedSearchConditions || this.advancedSearchConditions.length === 0) {
        return ''
      }
      return this.advancedSearchConditions.map(item => {
        if (item.field) {
          // 字段条件
          let keywordDisplay = item.keyWord
          if (item.symbol === '包含' || item.symbol === '不包含') {
            keywordDisplay = `'%${item.keyWord}%'`
          } else if (item.keyWord && isNaN(parseInt(item.keyWord))) {
            keywordDisplay = `'${item.keyWord}'`
          }
          return `${item.field} ${item.symbol} ${keywordDisplay}`
        } else if (item.connector) {
          // 连接符
          return item.connector
        } else if (item.bracket) {
          // 括号
          return item.bracket
        }
        return ''
      }).join(' ')
    }
  },
  created() {
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.query.documentId = this.selectedDocument.id
      this.crud.query.fondsAffiliation = this.selectedDocument.fondsId
      this.crud.query.sort = this.arrySort
    },

    formLoadingShow(loadingType) {
      this.archivesBtnLoading = loadingType
    },
    handleNodeClick(data) {
      this.selectedDocument = data
      this.getInitDocumentsViewTable()
    },
    // 显示高级检索弹窗
    showAdvancedSearch() {
      this.advancedSearchVisible = true
    },
    // 处理高级检索
    handleAdvancedSearch(data) {
      this.advancedSearchVisible = false
      this.crud.query.intelligenceSearch = data.sql
      this.advancedSearchConditions = data.conditions || []
      this.crud.toQuery()
    },
    // 清除高级检索条件
    clearAdvancedSearch() {
      this.crud.query.intelligenceSearch = null
      this.advancedSearchConditions = []
      this.crud.toQuery()
    },
    // 重置查询
    resetQuery() {
      this.advancedSearchConditions = []
      this.crud.resetQuery()
    },
    // 字段项
    getInitDocumentsViewTable() {
      PrearchiveCrud.FetchInitDocumentsViewTable({ documentId: this.selectedDocument.id }).then(data => {
        if (data) {
          this.arrySort = []
          this.tableDisplayFields = data
          const orderSortArry = this.tableDisplayFields.filter(item => item.queue).sort((a, b) => a.queue - b.queue)
          orderSortArry.forEach(item => {
            if (item.displayOrderBy) {
              this.arrySort.push(item.fieldName + ',' + item.displayOrderBy)
            }
          })
          this.$nextTick(() => {
            this.crud.toQuery()
          })
        }
      })
    },
    // 著录界面-form/详情-api
    handleForm(type) {
      if (this.$refs.previewForm) {
        this.$refs.previewForm.resetForm()
      }
      // 清空formPreviewData
      this.formPreviewData = []

      this.mergeVisible = false
      this.selectedCategory = this.selectedDocument
      this.isDesFormType = 'prearchiveLibrary'
      let params
      if (type === 'add') {
        this.formTitle = '新增文件'
        params = {
          documentId: this.selectedDocument.id,
          archivesId: null
        }
      } else if (type === 'edit') {
        this.formTitle = '编辑文件'
        this.arcId = this.crud.selections[0].id
        params = {
          documentId: this.selectedDocument.id,
          archivesId: this.crud.selections[0].id
        }
      }
      this.getFormInfo(params, type)
    },
    getFormInfo(params, type) {
      PrearchiveCrud.FetchDoeditDocument(params).then(data => {
        console.log('data', data)
        const showFiledAll = data.showFiled.filter(item => item.isSequence).sort((a, b) => a.isSequence - b.isSequence)
        this.$nextTick(() => {
          this.formPreviewData = showFiledAll
          this.formVisible = true
          this.$nextTick(() => {
            this.$refs.previewForm.fileOriginal = null
            this.$refs.previewForm.fileJsonString = null
            if (type === 'edit') {
              this.$refs.previewForm.archivesType = 'edit'
              this.$refs.previewForm.addOrUpdateForm = data.echo
              // if (data.fileecho) {
              //   const fileecho = []
              //   fileecho.push(data.fileecho)
              //   this.$refs.previewForm.fileOriginal = fileecho[0].file_name
              //   this.$refs.previewForm.fileJsonString = JSON.stringify(fileecho)
              // } else {
              //   this.$refs.previewForm.fileOriginal = ''
              //   this.$refs.previewForm.fileJsonString = ''
              // }

              const fileecho = data.fileecho
              let fileOriginal = ''
              let fileJsonString = ''

              if (Array.isArray(fileecho) && fileecho.length > 0) {
                fileOriginal = fileecho
                  .filter(item => item && item.file_name)
                  .map(item => item.file_name)
                  .join(',')
                fileJsonString = JSON.stringify(fileecho)
              } else if (typeof fileecho === 'object' && fileecho !== null && Object.keys(fileecho).length > 0) {
                fileOriginal = fileecho.file_name || ''
                fileJsonString = JSON.stringify([fileecho])
              }

              // 赋值给表单
              this.$refs.previewForm.fileOriginal = fileOriginal
              this.$refs.previewForm.fileJsonString = fileJsonString
              console.log('fileJsonString', JSON.parse(fileJsonString))
              console.log('fileJsonString', JSON.parse(fileJsonString).length)
            } else {
              this.$refs.previewForm.archivesType = 'add'
            }
          })
        })
      })
    },
    handleFormMerge() {
      console.log('this.selectedDocumentmMerge', this.selectedDocument)
      this.selectedCategory = this.selectedCategoryMerge

      this.selectedCategory.fondsId = this.selectedDocument.fondsId
      this.selectedCategory.fondsNo = this.selectedDocument.fondsNo
      this.selectedCategory.fondName = this.selectedDocument.fondsName
      console.log('this.selectedCategory', this.selectedCategory)
      // let categoryLevel
      // if (this.selectedCategoryMerge.arrangeType === 1) {
      //   categoryLevel = 3
      // } else if (this.selectedCategoryMerge.arrangeType === 2) {
      //   categoryLevel = 2
      // } else {
      //   categoryLevel = 1
      // }
      FetchInitCategoryInputFieldByPid({
        categoryId: this.selectedCategoryMerge.id,
        categoryLevel: 3,
        istype: 2
      }).then((data) => {
        // // 1. 过滤并排序有isSequence的字段
        // const showFiledAll = data.filter(item => item.isSequence).sort((a, b) => a.isSequence - b.isSequence)

        // // 2. 查找fieldName为is_entity的字段
        // const entityField = data.find(item => item.fieldName === 'is_entity')

        // // 3. 如果找到该字段，就添加到列表末尾
        // if (entityField) {
        //   showFiledAll.push(entityField)
        // }

        this.$nextTick(() => {
          this.formPreviewData = data
          this.formVisible = true
          this.mergeVisible = false
          this.isDesFormType = 'mergeFile'
          this.$nextTick(() => {
            this.$refs.previewForm.archivesType = 'add'
            this.$refs.previewForm.mergeFileArcIds = this.crud.selections.map(item => item.id)
            this.$refs.previewForm.mergeFileCategory = this.selectedCategoryMerge.id
          })
        })
      })
    },
    handlerArchivesSubmit() {
      this.$refs.previewForm.submitForm('addOrUpdateForm', this.selectedDocument.id)
    },
    clickRowHandler(row) {
      // this.$refs.table.clearSelection()
      // this.$refs.table.toggleRowSelection(row)

      if (this.timer) {
        clearTimeout(this.timer)
      }

      const clickTime = Date.now()
      const clickX = event.clientX
      const clickY = event.clientY
      const timeDiff = clickTime - this.mousedownTime
      const distance = Math.sqrt(
        Math.pow(clickX - this.mousedownX, 2) + Math.pow(clickY - this.mousedownY, 2)
      )
      // 时间差较短且鼠标移动距离较小，判定为点击操作
      if (timeDiff < 300 && distance < 10) {
        this.timer = setTimeout(() => {
          this.parentsId = row.id
          this.openJuannei('所属文件：' + row.maintitle, this.parentsId, row)
        }, 300)
      }
    },
    openJuannei(data, parentId, parentRow) {
      this.$refs.fileEle.fileDrawer = true
      this.$nextTick(() => {
        this.$refs.fileEle.test = data
        this.$refs.fileEle.parentInfo = parentRow
        this.$refs.fileEle.getFile()
      })
    },
    onMouseDown(event) {
      this.mousedownTime = Date.now()
      this.mousedownX = event.clientX
      this.mousedownY = event.clientY
    },
    onMouseUp() {
      // 可以在这里添加更多逻辑，比如清除临时数据等
    },
    // 双击查看详情
    tableDoubleClick(row) {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      console.log('tableDoubleClick', row)
      this.$refs.archivesInfo.archivesInfoVisible = true
      this.$refs.archivesInfo.archivesTabIndex = 0
      this.$refs.archivesInfo.parentInfo = row
      this.$refs.archivesInfo.getDetial(row.id)
    },
    // 删除
    toDelete(datas) {
      this.$confirm('此操作将删除当前所选预归档数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        this.crud.delAllLoading = true
        const ids = []
        datas.forEach(val => {
          ids.push(val.id)
        })
        const params = {
          'documentId': this.selectedDocument.id,
          'ids': ids
        }
        PrearchiveCrud.del(params).then(() => {
          this.crud.notify('删除成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          this.crud.delAllLoading = false
          this.crud.refresh()
        }).catch(err => {
          this.crud.delAllLoading = false
          console.log(err)
        })
      }).catch(() => {
      })
    },
    // 导出
    doExport(datas) {
      this.crud.downloadLoading = true
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const ids = []
        datas.forEach(val => {
          ids.push(val.id)
        })
        const params = {
          'documentId': this.selectedDocument.id,
          'ids': ids
        }
        exportFile(this.baseApi + '/api/re-document/download?' + qs.stringify(params, { indices: false }))
        this.crud.downloadLoading = false
      }).catch(() => {
        this.crud.downloadLoading = false
      })
    },
    preUplpadClose() {
      this.$refs.preUploadRefs.handleClearData()
    },
    handleSuccessResource(filePath, fileName, jsonArrayToSend) {
      console.log('handleSuccessResource', filePath)
      console.log('handleSuccessResource', fileName)
      console.log('handleSuccessResource', jsonArrayToSend)
      console.log('handleSuccessResource', jsonArrayToSend[0].fileJsonString)
      this.fileOriginal = fileName

      const fileJson = JSON.parse(jsonArrayToSend[0].fileJsonString)
      fileJson[0].file_path = '/' + filePath
      fileJson[0].is_quote = null
      fileJson[0].last_modified = jsonArrayToSend[0].last_modified
      this.fileJsonString = JSON.stringify(fileJson)
    },
    handleTestFile(type) {
      if (type === 1) {
        this.fileUpload(1)
      } else {
        this.arcId = this.crud.selections[0].id
        this.fileOneVisible = true
      }
    },
    handleErrorResource(res) {
      console.log('handleErrorResource', res)
    },
    // 原文上传
    fileUpload(uploadType) {
      console.log('dddd')
      console.log('this.selectedDocument', this.selectedDocument)
      this.arcId = this.crud.selections[0].id
      this.$refs.uploadBigRef.updateUploadOptions(uploadType)
      this.$refs.uploadBigRef.fileList = []
      // if (this.$refs.uploadOriginalRef.uploadVisible) {
      //   this.$refs.uploadOriginalRef.uploadType = uploadType
      //   this.$refs.uploadOriginalRef.fileList = []
      // }
    },
    // 批量成件
    handleBatch() {
      this.$refs.batchForm.batchVisible = true
      this.$refs.batchForm.selectionsArc = this.crud.selections
      this.$nextTick(() => {
        this.$refs.batchForm.getMateByDocumentId()
      })
    },
    // 合并成件
    handelMerge() {
      this.mergeVisible = true
      this.getCategoryDataTree()
    },
    // 移动
    handleMove() {
      this.$refs.moveForm.moveVisible = true
      this.$refs.moveForm.moveArc = this.crud.selections
    },
    getCategoryDataTree() {
      const params = {
        'fondsId': this.selectedDocument.fondsId
      }
      FetchMenuByFondsId(params).then(res => {
        this.categoryTree = this.filterData(res)
        console.log('this.categoryTree222', this.categoryTree)
      })
    },
    handleSelectCategory(val) {
      this.selectedCategoryMerge = val
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.cnName,
        children: node.children,
        isDisabled: node.isType !== 2
      }
    },
    // handleClose(done) {
    //   this.mergeVisible = false
    //   this.formVisible = false
    //   this.$refs.previewForm.preUplpadClose()
    //   done()
    // },
    closeDialog() {
      // this.fileOneVisible = false
      this.mergeVisible = false
      this.formVisible = false
      if (this.$refs.previewForm.$refs['addOrUpdateForm']) {
        this.$refs.previewForm.$refs['addOrUpdateForm'].clearValidate()
        this.$refs.previewForm.$refs['addOrUpdateForm'].resetFields()
      }
      this.$refs.previewForm.fileOriginal = null
      this.$refs.previewForm.fileJsonString = null
      this.$refs.previewForm.preUplpadClose()
    }
  }
}
</script>

<style lang='scss' scoped>
@import "~@/assets/styles/collect-reorganizi.scss";

@mixin management-fixed-style{
  [data-theme="dark"] & {
    background-color: #031435 !important;
    -webkit-box-shadow: -5px 5px 10px 1px rgba(15,164,222,.16);
    box-shadow: -5px 5px 10px 1px rgba(15,164,222,.16);
  }
  [data-theme="light"] & {
    background-color: #fff;
  }
}
.el-table {
  ::v-deep .el-table__fixed-right {
    @include management-fixed-style;
  }
}
.preview-dialog .el-dialog .preview-content {
  height: calc(100vh - 264px) !important;
}

.dialog-middle{
  ::v-deep .el-dialog{
    width: 536px;
  }
}
</style>
