<template>
  <div class="app-container">
    <!-- 门类列表 -->
    <div class="container-main">
      <div class="elect-cont-left">
        <TreeList @nodeClick="handleNodeClick" />
      </div>
      <div class="elect-cont-right">
        <!--工具栏-->
        <div class="head-container">
          <div class="head-search">
            <!-- 搜索 -->
            <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 />
          </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 === 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"
            @select="crud.selectChange"
            @select-all="crud.selectAllChange"
            @selection-change="crud.selectionChangeHandler"
          >
            <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">
                {{ scope.row[field.fieldName] }}
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <pagination v-if="crud.data.length !== 0" />
        </div>
        <!-- 批量成件 -->
        <batchFile ref="batchForm" :selected-document="selectedDocument" />
        <!-- 移动 -->
        <moveFile ref="moveForm" />
        <!-- 合并成件 -->
        <el-dialog class="dialog-middle" :modal-append-to-body="false" :close-on-click-modal="false" :before-close="handleClose" :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"
                  placeholder="请选择档案门类"
                  @select="handleSelectCategory"
                />
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="mergeVisible = false">取消</el-button>
              <el-button type="primary" @click="handleForm('add')">确定</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="handleClose" :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" :is-has-code="isHasCode" @close-dialog="closeDialog" />
            <div slot="footer" class="dialog-footer">
              <el-button type="text" @click="formVisible = false">取消</el-button>
              <el-button type="primary" @click="handlerArchivesSubmit">确定</el-button>
            </div>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import CRUD, { presenter, header } from '@crud/crud'
import { preLibraryCrud } from './mixins/index'
import { FetchCategoryMenu } 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 { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

export default {
  name: 'PrearchiveLibrary',
  components: { TreeList, PreviewForm, batchFile, moveFile, Treeselect, rrOperation, crudOperation, pagination },
  cruds() {
    return [
      CRUD({
        title: '预归档库', url: 'api/re-document/initPreDocument',
        crudMethod: { ...PrearchiveCrud },
        optShow: {
          add: false,
          edit: false,
          del: false,
          download: false,
          group: false,
          reset: true
        },
        queryOnPresenterCreated: false
      })
    ]
  },
  mixins: [presenter(), header(), preLibraryCrud],
  data() {
    return {
      permission: {
        add: ['admin', 'prearchiveLibrary:add'],
        edit: ['admin', 'prearchiveLibrary:edit'],
        del: ['admin', 'prearchiveLibrary:del'],
        sort: ['admin', 'prearchiveLibrary:sort']
      },
      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
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created() {
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.query.documentId = this.selectedDocument.id
      this.crud.query.sort = this.arrySort
    },
    handleNodeClick(data) {
      this.selectedDocument = data
      this.getInitDocumentsViewTable()
    },
    // 字段项
    getInitDocumentsViewTable() {
      PrearchiveCrud.FetchInitDocumentsViewTable({ documentId: this.selectedDocument.id }).then(data => {
        if (data) {
          this.arrySort = []
          this.tableDisplayFields = data
          const orderSortArry = this.tableDisplayFields.filter(item => item.displayOrder).sort((a, b) => a.displayOrder - b.displayOrder)
          orderSortArry.forEach(item => {
            if (item.displayOrderBy) {
              this.arrySort.push(item.fieldName + ',' + item.displayOrderBy)
            }
          })
          this.$nextTick(() => {
            this.crud.toQuery()
          })
        }
      })
    },
    // 著录界面-form/详情-api
    handleForm(type) {
      this.mergeVisible = false
      this.selectedCategory = this.selectedDocument
      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 => {
        const showFiledAll = data.showFiled.filter(item => item.displayOrder).sort((a, b) => a.displayOrder - b.displayOrder)
        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.addOrUpdateForm = data.echo
              const fileecho = []
              fileecho.push(data.fileecho)
              this.$refs.previewForm.fileOriginal = fileecho[0].file_name
              this.$refs.previewForm.fileJsonString = JSON.stringify(fileecho)
            }
          })
        })
      })
    },
    handlerArchivesSubmit() {
      this.$refs.previewForm.submitForm('addOrUpdateForm', this.selectedDocument.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 }))
      }).catch(() => {
      })
    },
    handleBatch() {
      this.$refs.batchForm.batchVisible = true
    },
    handelMerge() {
      this.mergeVisible = true
      this.getCategoryDataTree()
    },
    getCategoryDataTree() {
      FetchCategoryMenu().then(res => {
        this.categoryTree = this.filterData(res)
      })
    },
    handleSelectCategory(val) {
      // this.selectedCategoryName = val.cnName
    },
    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
      done()
    },
    closeDialog() {
      this.formVisible = false
    },
    handleMove() {
      this.$refs.moveForm.moveVisible = true
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
