<template>
  <div class="app-container">
    <!-- 门类列表 -->
    <div class="container-main">
      <div class="elect-cont-left">
        <TreeList ref="treeList" @nodeClick="handleNodeClick" />
      </div>
      <div v-if="selectedDocument.isType!==1" class="elect-cont-right">
        <!--工具栏-->
        <div class="head-container" :style="isRecycle?'display:flex;justify-content: space-between; align-items: center;':'' ">
          <div class="head-search" :style="isRecycle?'margin: 0;':''">
            <!-- 搜索 -->
            <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-refresh" size="mini" type="warning" icon="el-icon-refresh-left" @click="resetQuery">重置</el-button>
          </div>
          <crudOperation v-if="!isRecycle" :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 === 0" @click="doPrint(crud.selections)"><i class="iconfont icon-dayin" />打印处理单</el-button>
              </div>
            </template>
          </crudOperation>
          <div v-if="isRecycle">
            <el-button size="mini" type="success" @click="toRecover(crud.selections)"><i class="iconfont icon-huifu" />恢复</el-button>
            <el-button size="mini" type="success" @click="toCompletelyDelete(crud.selections)"><i class="iconfont icon-shanchu" />彻底删除</el-button>
          </div>
        </div>
        <!--表格渲染-->
        <div class="container-right">
          <span class="right-top-line" />
          <span class="left-bottom-line" />
          <el-table
            ref="table"
            v-loading="crud.loading"
            class="archives-table"
            :data="crud.data"
            style="width: 100%;"
            @row-click="clickRowHandler"
            @select="crud.selectChange"
            @select-all="crud.selectAllChange"
            @selection-change="crud.selectionChangeHandler"
            @cell-dblclick="tableDoubleClick"
          >
            <el-table-column type="selection" align="center" width="55" />
            <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">
                <!-- 仅针对read_type字段添加特殊处理 -->
                <span
                  v-if="field.fieldName === 'read_type'"
                  :class="{
                    'row-state row-packing': scope.row.read_type === '未传阅',
                    'row-state row-warehousing state-active': scope.row.read_type === '传阅中',
                    'row-state row-binding state-active': scope.row.read_type === '已完成',
                  }"
                >
                  {{ scope.row[field.fieldName] }}
                </span>
                <span v-else>{{ scope.row[field.fieldName] }}</span>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination v-if="crud.data.length !== 0" />
        </div>
        <detail ref="archivesInfo" :selected-document="selectedDocument" />

        <!--新增 / 编辑 表单组件-->
        <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"
              @refreshTree="refreshTreeList"
            />
            <div slot="footer" class="dialog-footer" style="margin-top: 20px !important;">
              <el-button type="text" @click="closeDialog">取消</el-button>
              <el-button :loading="archivesBtnLoading" type="primary" @click="handlerArchivesSubmit">保存</el-button>
              <!-- @click="handlerArchivesSubmit" -->
              <el-button :loading="bindSaveLoading" type="primary">保存并绑定标签</el-button>
            </div>
          </div>
        </el-dialog>
        <!--表单组件-->
        <el-dialog class="tip-dialog" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body title="提示" :visible.sync="printVisible">
          <div class="setting-dialog">
            <div class="tip-content">
              <p class="tipMsg">此操作将打印所选公文库数据</p>
            </div>
            <el-radio-group v-model="printType" style="padding-left: 36px;">
              <el-radio :label="1">套打</el-radio>
              <el-radio :label="2">彩打</el-radio>
            </el-radio-group>
            <div slot="footer" class="dialog-footer">
              <el-button @click.native="printVisible = false">取消</el-button>
              <el-button type="primary" @click.native="handlePrint">确定</el-button>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
    <!-- 注册PDF对话框组件 -->
    <PdfDialog ref="pdfDialog" />
    <!-- <PdfViewer v-if="pdfSources.length !== 0" :pdf-sources="pdfSources" frame-height="600px" /> -->
  </div>
</template>

<script>
import CRUD, { presenter, header } from '@crud/crud'
import { miodLibraryCrud } from './mixins/index'
import crudDocumentArchives, { FetchDelArchives, FetchCompleteDelArchives, FetchRestoreArchives, FetchInitDistributorByDocumentId } from '@/api/system/documentArchives'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import TreeList from './treeList'
import PreviewForm from '@/views/components/category/PreviewForm'
import detail from './module/detail'
import { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

// import html2canvas from 'html2canvas'
// import printJS from 'print-js'
// import PdfViewer from './module/pdfViewer'
import PdfDialog from './module/pdfDialog'

export default {
  name: 'MiodLibrary',
  components: { TreeList, PreviewForm, detail, rrOperation, crudOperation, pagination, PdfDialog },
  cruds() {
    return [
      CRUD({
        title: '收发文', url: 'api/documentArchives/initPreDocument',
        crudMethod: { ...crudDocumentArchives },
        optShow: {
          add: false,
          edit: false,
          del: false,
          download: false,
          group: false,
          reset: false
        },
        queryOnPresenterCreated: false
      })
    ]
  },
  provide() {
    return {
      parentsData: this
    }
  },
  mixins: [presenter(), header(), miodLibraryCrud],
  props: {
    isRecycle: {
      type: Boolean,
      default: false
    },
    isdel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      archivesBtnLoading: false,
      bindSaveLoading: false,
      permission: {
        add: ['admin', 'prearchiveLibrary:add'],
        edit: ['admin', 'prearchiveLibrary:edit'],
        del: ['admin', 'prearchiveLibrary:del'],
        sort: ['admin', 'prearchiveLibrary:sort']
      },
      tableDisplayFields: [], // table-list-title字段
      arrySort: [],
      selectedDocument: {},
      form: {},
      formVisible: false,
      formTitle: '新增文件',
      formPreviewData: [],
      selectedCategory: null,
      parentsId: null,
      arcId: null,
      isDesFormType: 'miodLibrary',
      isDisabled: false,
      isHasCode: false,
      printVisible: false,
      printType: 1,
      isHidden: false,
      formData: {
        receiveNo: '武交收〔2025〕12号',
        receiveDate: '2025年05月20日',
        urgency: '急件',
        senderUnit: '湖北省交通运输厅',
        senderNo: '鄂交发〔2025〕35号',
        secrecyLevel: '普通',
        tip: '请办公室尽快协调相关部门阅办',
        fileTitle: '关于加强交通运输安全生产管理的通知',
        recommendation: '建议转交运输科牵头办理，5个工作日内反馈意见',
        leaderApproval: '同意拟办意见，张XX 2025.05.20',
        departmentOpinion: '已阅，将于2025.05.25前反馈'
      },
      printTitle: '',
      pdfSources: [],
      printSelections: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  watch: {
    isdel: function(newValue, oldValue) {
    },
    isRecycle: function(newValue, oldValue) {
    }
  },
  created() {
  },
  methods: {

    refreshTreeList() {
      this.$refs.treeList.refreshData()
    },
    resetQuery() {
      if (this.selectedDocument.isType === 3) {
        this.crud.query.docDepartment = this.selectedDocument.label
        this.crud.query.archiveYear = null
        this.crud.query.search = null
      } else if (this.selectedDocument.isType === 4) {
        this.crud.query.docDepartment = null
        this.crud.query.archiveYear = this.selectedDocument.label
        this.crud.query.search = null
      } else {
        this.crud.query.search = null
        this.crud.query.docDepartment = null
        this.crud.query.archiveYear = null
      }
      this.crud.toQuery()
    },
    [CRUD.HOOK.beforeRefresh]() {
      if (this.selectedDocument.isType === 2) {
        this.crud.query.documentId = this.selectedDocument.id
      } else {
        this.crud.query.documentId = this.selectedDocument.documentId
      }
      this.crud.query.isdel = this.isdel
      // this.crud.query.ignore = false
      this.crud.query.fondsAffiliation = this.selectedDocument.fondsId
      this.crud.query.sort = this.arrySort
    },
    formLoadingShow(loadingType) {
      this.archivesBtnLoading = loadingType
    },
    handleNodeClick(data) {
      if (data.isType !== 1) {
        this.selectedDocument = data
        let documentId = null
        if (data.isType === 2) {
          documentId = data.id
        } else {
          documentId = data.documentId
        }
        this.getInitDocumentsViewTable(documentId)
      }
    },
    // table字段项
    getInitDocumentsViewTable(documentId) {
      crudDocumentArchives.FetchInitDocumentsViewTable({ documentId: documentId }).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(() => {
            if (this.selectedDocument.isType === 3) {
              this.crud.query.docDepartment = this.selectedDocument.label
              this.crud.query.archiveYear = null
            } else if (this.selectedDocument.isType === 4) {
              this.crud.query.docDepartment = null
              this.crud.query.archiveYear = this.selectedDocument.label
            } else {
              this.crud.query.search = null
              this.crud.query.docDepartment = null
              this.crud.query.archiveYear = null
            }
            this.crud.toQuery()
          })
        }
      })
    },
    handleForm(type) {
      const { selectedDocument, crud } = this

      if (!selectedDocument) {
        console.warn('selectedDocument 未定义，无法继续操作')
        return
      }

      this.selectedCategory = selectedDocument
      this.isDesFormType = 'miodLibrary'

      let documentId
      if (selectedDocument.isType === 2) {
        documentId = selectedDocument.id
      } else {
        documentId = selectedDocument.documentId
      }

      const params = { documentId }

      if (type === 'add') {
        this.formTitle = '新增文件'
        params.archivesId = null
      } else if (type === 'edit') {
        this.formTitle = '编辑文件'
        const { id: archivesId } = crud.selections[0]
        this.arcId = archivesId
        params.archivesId = archivesId
      }

      this.getFormInfo(params, type)
    },

    getFormInfo(params, type) {
      crudDocumentArchives.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) {
                this.$refs.previewForm.fileOriginal = data.fileecho.file_name || null
                this.$refs.previewForm.fileJsonString = JSON.stringify([data.fileecho])
              } else {
                this.$refs.previewForm.fileOriginal = ''
                this.$refs.previewForm.fileJsonString = ''
              }
              // 获取借阅者
              FetchInitDistributorByDocumentId(params).then(res => {
                if (res && res.length !== 0) {
                  this.$refs.previewForm.miodDeptsTags = res
                  const ids = res.map(item => item.id)
                  this.$set(this.$refs.previewForm.addOrUpdateForm, 'miodDepts', ids)
                } else {
                  this.$set(this.$refs.previewForm.addOrUpdateForm, 'miodDepts', null)
                }
              })
            } else {
              this.$refs.previewForm.archivesType = 'add'
            }
          })
        })
      })
    },
    handlerArchivesSubmit() {
      let documentId
      if (this.selectedDocument.isType === 2) {
        documentId = this.selectedDocument.id
      } else {
        documentId = this.selectedDocument.documentId
      }
      this.$refs.previewForm.submitForm('addOrUpdateForm', documentId)
    },
    clickRowHandler(row) {
      this.$refs.table.clearSelection()
      this.$refs.table.toggleRowSelection(row)
    },
    // 双击查看详情
    tableDoubleClick(row) {
      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)
        })
        let documentId
        if (this.selectedDocument.isType === 2) {
          documentId = this.selectedDocument.id
        } else {
          documentId = this.selectedDocument.documentId
        }

        const params = {
          'documentId': documentId,
          'archivesIds': ids
        }

        FetchDelArchives(params).then((res) => {
          console.log('res', res)
          if (res.code !== 500) {
            this.crud.notify('删除成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
            this.crud.refresh()
          } else {
            this.crud.notify('删除失败', CRUD.NOTIFICATION_TYPE.ERROR)
          }
          this.crud.delAllLoading = false
        }).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)
        })
        let documentId
        if (this.selectedDocument.isType === 2) {
          documentId = this.selectedDocument.id
        } else {
          documentId = this.selectedDocument.documentId
        }
        const params = {
          'documentId': documentId,
          'ids': ids
        }
        exportFile(this.baseApi + '/api/documentArchives/downloadDocumentArchives?' + qs.stringify(params, { indices: false }))
        this.crud.downloadLoading = false
      }).catch(() => {
        this.crud.downloadLoading = false
      })
    },
    doPrint(datas) {
      this.printVisible = true
      this.printSelections = datas
    },
    handlePrint() {
      this.printVisible = false
      let documentId
      if (this.selectedDocument.isType === 2) {
        documentId = this.selectedDocument.id
      } else {
        documentId = this.selectedDocument.documentId
      }
      const ids = this.printSelections.map(item => item.id)
      console.log('ids', ids)
      const params = {
        'archivesId': ids,
        'documentId': documentId,
        'printType': this.printType // 1 套打 2 彩打
      }
      this.$refs.pdfDialog.openDialog(params)
      // this.getHandleDocument()
    },
    async getHandleDocument() {
      try {
        // console.log('params', params)
        // FetchHandleDocument(params).then(async(res) => {
        //   console.log(res)
        //   this.pdfSources = res.map(item => {
        //     // 如果后端返回的是带前缀的Base64，可以直接使用
        //     return item.startsWith('data:application/pdf;base64,')
        //       ? item
        //       : `data:application/pdf;base64,${item}`
        //   })
        // })
      } catch (error) {
        console.error(error)
      }
    },
    // 回收站 - 恢复
    toRecover(datas) {
      if (datas.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此恢复将会把所选条目及其子集一并恢复' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        datas.forEach(val => {
          archivesIds.push(val.id)
        })

        let documentId
        if (this.selectedDocument.isType === 2) {
          documentId = this.selectedDocument.id
        } else {
          documentId = this.selectedDocument.documentId
        }
        const params = {
          'documentId': documentId,
          'archivesIds': archivesIds
        }
        console.log('params', params)
        FetchRestoreArchives(params).then((res) => {
          console.log('res', res)
          if (res.code !== 500) {
            if (res.includes('成功')) {
              this.$message({ message: res, type: 'success', offset: 8 })
              this.crud.refresh()
              this.refreshTreeList()
            } else {
              this.$message({ message: res, type: 'error', offset: 8 })
            }
          } else {
            this.$message({ message: '恢复所选档案失败', type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    // 回收站 - 彻底删除
    toCompletelyDelete(datas) {
      if (datas.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此删除将把会所选条目与其子集彻底删除' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        datas.forEach(val => {
          archivesIds.push(val.id)
        })
        let documentId
        if (this.selectedDocument.isType === 2) {
          documentId = this.selectedDocument.id
        } else {
          documentId = this.selectedDocument.documentId
        }
        const params = {
          'documentId': documentId,
          'archivesIds': archivesIds
        }
        console.log('params', params)
        FetchCompleteDelArchives(params).then((res) => {
          if (res.code !== 500) {
            this.$message({ message: res, type: 'success', offset: 8 })
            this.crud.refresh()
            this.refreshTreeList()
          } else {
            this.$message({ message: '删除所选档案失败', type: 'error', offset: 8 })
          }
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
      })
    },
    closeDialog() {
      this.formVisible = false
      this.$refs.previewForm.miodDeptsTags = []
      this.$refs.previewForm.miodDeptsSelections = []
      this.$refs.previewForm.deptsValid = false
      if (this.$refs.previewForm.$refs['addOrUpdateForm']) {
        this.$refs.previewForm.$refs['addOrUpdateForm'].clearValidate()
        this.$refs.previewForm.$refs['addOrUpdateForm'].resetFields()
      }
    }
  }
}
</script>
<style>
@media print {
  html,body{
   height: inherit;
  }
  .print-container {
    position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  }
  @page {
    size: A4;
    margin: 2cm;
  }
}
</style>
<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;

}
.elect-cont-right .container-right {
  min-height: calc(100vh - 284px);
}
.dialog-footer .el-button.el-button--primary,
.el-message-box__btns .el-button.el-button--primary{
  width: auto;
  height: auto;
  line-height:normal;
  padding: 6px 20px;
}

.tip-dialog{
  ::v-deep .el-dialog{
    width: 504px;
    .setting-dialog{
      padding: 10px 10px 0 10px;
    }
    .tip-content{
      padding-left: 34px;
      font-size: 14px;
      line-height: 24px;
      color: #0C0E1E;
      background: url("~@/assets/images/icon/tip-icon.png") no-repeat left top;
      background-size: 24px 24px;
      padding-bottom: 20px;
      span{
        font-size: 12px;
        color: #ED4A41;
      }
    }
  }
  .dialog-footer{
    margin-top: 27px;
  }
}
.intoExamine{
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  z-index: 99;
}
/* 基础样式 */
.print-container {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  z-index: 99;
  padding: 0 0 40px 0;
}

/* 标题样式 */
.print-title {
  font-size: 22pt;
  font-family: "华文中宋";
  color: #ff0000;
  margin: 20px 0;
}

/* 表格样式 */
.official-table {
  border-collapse: collapse;
  width: 100%;
}

.label-cell, .content-cell {
  border: 1px solid #ff0000;
  padding: 8px;
}

.label-cell {
  background: #ffffff;
  text-align: center;
  font-size: 12pt;
  color: #ff0000;
  vertical-align: middle;
}

.content-cell {
  background: #ffffff;
  font-size: 12pt;
  vertical-align: top;
}

.content-left {
  text-align: left;
}

.content-center {
  text-align: center;
}

.header-cell {
  border: none;
  padding: 20px 0;
  text-align: center;
}

.header-text {
  font-family: "华文中宋";
  font-size: 22pt;
  color: #ff0000;
  margin: 0;
}
</style>
