<template>
  <div>
    <!--工具栏-->
    <div class="head-container">
      <div class="head-archives-top">
        <div class="head-search">
          <!-- 搜索 -->
          <el-select v-if="selectedCategory.isType === 3 || selectedCategory.isType === 5" v-model="query.enabled" clearable size="small" placeholder="状态" class="filter-item" style="width: 100px" @change="crud.toQuery">
            <i slot="prefix" class="iconfont icon-zhuangtai-fanbai" />
            <el-option v-for="item in stateOptions" :key="item.key" :label="item.label" :value="item.key" />
          </el-select>
          <el-input v-model="query[inputSelect]" clearable size="small" placeholder="请输入关键词" style="width: 200px;" class="input-prepend filter-item" @keyup.enter.native="crud.toQuery">
            <el-select slot="prepend" v-model="inputSelect" style="width: 80px" @change="querySelect">
              <el-option
                v-for="item in queryOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-input>
          <rrOperation />
        </div>
        <el-checkbox v-if="selectedCategory.isType !== 1 && selectedCategory.isType !== 2" v-model="fixedStatusBar">隐藏固定状态栏</el-checkbox>
      </div>
      <crudOperation :permission="permission">
        <template v-slot:right>
          <el-button v-permission="permission.del" icon="el-icon-delete" size="mini" :loading="crud.delAllLoading" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">删除</el-button>
          <el-button v-if="selectedCategory.isType !== 1 && selectedCategory.isType !== 2" v-permission="permission.download" :loading="crud.downloadLoading" :disabled="!crud.data.length" size="mini" icon="el-icon-download" @click="crud.doExport">导出</el-button>
          <el-button v-if="selectedCategory.isType === 4 || selectedCategory.isType === 5" :disabled="crud.selections.length !== 1" size="mini" icon="el-icon-download" @click="uploadFile">上传附件</el-button>
        </template>
        <template v-slot:rightButtonGroup>
          <div v-if="selectedCategory.isType === 3 || selectedCategory.isType === 5" class="archives-handler-btn">
            <el-button class="packing-btn iconfont icon-weibiaoti-2" type="primary" @click="packingVisible=true">装盒</el-button>
            <el-button v-if="selectedCategory.isType === 3" class="part-btn iconfont icon-weibiaoti-2" type="primary">分卷装盒</el-button>
            <!-- <el-button class="warehousing-btn iconfont icon-weibiaoti-2" type="primary">入库</el-button> -->
            <el-button class="lending-btn iconfont icon-weibiaoti-2" type="primary">借阅</el-button>
            <el-button class="binding-btn iconfont icon-weibiaoti-2" type="primary">绑定标签</el-button>
          </div>
        </template>
      </crudOperation>
    </div>
    <!--新增 / 编辑 表单组件-->
    <el-dialog class="preview-dialog" :modal-append-to-body="false" :close-on-click-modal="false" :before-close="crud.cancelCU" :visible="crud.status.cu > 0" :title="crud.status.title">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <!-- form -->
        <PreviewForm v-if="formPreviewData.length && archivesTabIndex == 0" ref="previewForm" :is-disabled="false" :form-preview-data.sync="formPreviewData" :selected-category="selectedCategory" :arc-id="arcId" />
        <div slot="footer" class="dialog-footer">
          <el-button :loading="crud.status.cu === 2" type="primary" @click="handlerArchivesSubmit">保存</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 上传附件 -->
    <el-dialog class="upload-dialog" :modal-append-to-body="false" :close-on-click-modal="false" :before-close="handleClose" :visible.sync="uploadFileVisible" title="上传附件">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <UploadFile :is-upload-detail="true" />
        <div slot="footer" class="dialog-footer">
          <el-button :loading="crud.status.cu === 2" type="primary" @click="uploadFileSave">保存</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 删除档案 -->
    <el-dialog title="删除档案" :visible.sync="deleteVisible" :before-close="handleClose">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <div class="dialog-delt">
          <p><span>确定删除当前档案吗？</span></p>
          <p v-if="selectedCategory.isType == 2">数据来源：项目 1条数据  案卷 4条数据</p>
          <p v-if="selectedCategory.isType == 3">数据来源：案卷 1条数据  卷内 2条数据</p>
          <p v-if="selectedCategory.isType == 4">数据来源：卷内 1条数据</p>
          <p v-if="selectedCategory.isType == 5">数据来源：卷内 1条数据</p>
          <p class="delt-tip"><span>提示：如果删除当前档案，此档案内所附带的文件会一并删除</span></p>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.native="handleDeltConfirm">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- table表格渲染 -->
    <el-table ref="table" v-loading="crud.loading || getTableDisplayFieldsLoading" class="archives-table" :data="crud.data" highlight-current-row style="width: 100%; " height="calc(100vh - 370px)" @selection-change="crud.selectionChangeHandler" @row-click="clickRowHandler" @cell-dblclick="tableDoubleClick">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <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-scope="scope">
          {{ scope.row[field.fieldName] }}
        </template>
      </el-table-column>
      <el-table-column v-if="selectedCategory.isType !== 1 && selectedCategory.isType !== 2" label="装盒" width="100" align="center" :fixed="fixedStatusBar?false:'right'">
        <!-- state-active 已装/已入/已借/已绑 -->
        <template slot-scope="scope">
          <!-- 未装 / 已装 -->
          <span class="row-state row-packing state-active">{{ scope.row.case_no ? '已装': '未装' }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="selectedCategory.isType !== 1 && selectedCategory.isType !== 2" label="入库" width="100" align="center" :fixed="fixedStatusBar?false:'right'">
        <template slot-scope="">
          <!-- 未入 / 已入 -->
          <span class="row-state row-warehousing">未入</span>
        </template>
      </el-table-column>
      <el-table-column v-if="selectedCategory.isType === 3 || selectedCategory.isType === 5" label="借阅" width="100" align="center" :fixed="fixedStatusBar?false:'right'">
        <template slot-scope="">
          <!-- 待借 / 不可借-用“—” 表示 / 已借 -->
          <span class="row-state row-lending">—</span>
        </template>
      </el-table-column>
      <el-table-column v-if="selectedCategory.isType === 3 || selectedCategory.isType === 5" label="标签" width="100" align="center" :fixed="fixedStatusBar?false:'right'">
        <template slot-scope="scope">
          <!-- 未绑 / 已绑 -->
          <span class="row-state row-binding">{{ scope.row.tid ? '已绑': '未绑' }}</span>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />

    <!-- 档案详情 -->
    <el-dialog class="upload-dialog" title="档案详情" :visible.sync="archivesInfoVisible" :before-close="handleClose">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <ArchivesInfo />
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click.native="handleDeltConfirm">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog class="upload-dialog" title="装盒" :visible.sync="packingVisible" :before-close="handleClose">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog">
        <Packing />
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { add, edit, del, getTableDisplayFields, getFormDisplayFields } from '@/api/archivesManage/archivesList'
import CRUD, { presenter, header, form } from '@crud/crud'
import { initData } from '@/api/data'
import crudOperation from '@crud/CRUD.operation'
import rrOperation from '@crud/RR.operation'
import pagination from '@crud/Pagination'
import PreviewForm from '@/views/components/category/PreviewForm'
import UploadFile from './module/uploadFile'
import ArchivesInfo from './module/archivesInfo'
import Packing from './module/packing'

export default {
  components: { crudOperation, rrOperation, pagination, PreviewForm, UploadFile, ArchivesInfo, Packing },
  mixins: [
    presenter(),
    header(),
    form({})
  ],
  props: {
    selectedCategory: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  cruds() {
    return [
      CRUD({
        title: '档案',
        url: 'api/archives/initArchivesView',
        query: { isdel: false },
        crudMethod: { add, edit, del },
        optShow: {
          add: true,
          edit: true,
          del: false,
          reset: false,
          download: false,
          group: false
        },
        queryOnPresenterCreated: false,
        sort: []
      })
    ]
  },
  data() {
    return {
      stateOptions: [ // 搜索 - 状态选择
        { key: '1', label: '全部' },
        { key: '2', label: '未装' },
        { key: '3', label: '未入' },
        { key: '4', label: '在库' },
        { key: '5', label: '待借' },
        { key: '6', label: '已借' }
      ],
      queryOption: [
        { value: 'maintitle', label: '题名' },
        { value: 'archive_no', label: '档号' },
        { value: 'archive_year', label: '年度' }
      ],
      inputSelect: '',
      permission: {
        add: ['admin', 'archivesList:add'],
        edit: ['admin', 'archivesList:edit'],
        del: ['admin', 'archivesList:del'],
        download: ['admin', 'archivesList:download']
      },
      fixedStatusBar: false, // table-右侧fixed
      deleteVisible: false, // 删除dialog
      deleteData: {}, // 删除选中data
      tableDisplayFields: [], // table-list-title字段
      getTableDisplayFieldsLoading: false, // table-loading
      formPreviewData: [], // 预览界面data
      isEditOrAdd: '',
      selectedData: null,
      archivesTabIndex: 0, // 新增
      tabDisabled: true,
      arcId: null, // 档案ID
      arrySort: [],
      uploadFileVisible: false, // 上传附件
      archivesInfoVisible: false, // 档案详情
      packingVisible: false // 装盒
    }
  },
  watch: {
    selectedCategory: function(newValue, oldValue) {
      // 案卷 卷内 文件
      if (newValue.isType === 3 || newValue.isType === 4 || newValue.isType === 5) {
        this.crud.query.categoryId = newValue.id
        this.crud.refresh()
      }
    },
    tableDisplayFields(val) {
      this.doLayout()
    }
  },
  created() {
    // 初始化带select的输入框的 - 搜索
    this.inputSelect = this.queryOption[0].value
  },
  mounted() {
  },
  methods: {
    // 搜索-select
    querySelect(val) {
      this.inputSelect = val
    },
    [CRUD.HOOK.beforeRefresh]() {
      this.getTableDisplayFieldsLoading = true
      // 档案列表获取显示列
      getTableDisplayFields({ categoryId: this.selectedCategory.id }).then(data => {
        this.tableDisplayFields = data
        this.getTableDisplayFieldsLoading = false
        this.tableDisplayFields.map(item => {
          if (item.queue) {
            this.arrySort.push(item.fieldName + ', ' + (item.displayOrder === 1 ? 'asc' : 'desc'))
          }
        })
        this.crud.sort = this.arrySort
        new Promise((resolve, reject) => {
          this.crud.loading = true
          // 请求数据
          initData(this.crud.url, this.crud.getQueryParams()).then(data => {
            const table = this.crud.getTable()
            if (table && table.lazy) { // 懒加载子节点数据，清掉已加载的数据
              table.store.states.treeData = {}
              table.store.states.lazyTreeNodeMap = {}
            }
            if (data) {
              this.crud.page.total = data.totalElements !== null ? data.totalElements : data.length
              this.crud.data = data.content ? data.content : data
              this.crud.resetDataStatus()
              resolve(data)
              // time 毫秒后显示表格
              setTimeout(() => {
                this.crud.loading = false
              }, this.crud.time)
            }
          }).catch(err => {
            this.crud.loading = false
            reject(err)
          })
        })
      })
      return false
    },
    [CRUD.HOOK.beforeToCU](crud, form, btn) {
      this.isEditOrAdd = btn
      this.selectedData = crud.selections
      this.archivesTabIndex = 0
      if (this.isEditOrAdd === 'add') {
        this.tabDisabled = true
        this.arcId = null
      } else if (this.isEditOrAdd === 'edit') {
        this.arcId = this.selectedData[0].id
        this.tabDisabled = false
      }
      this.form.dictionaryConfigId = {}
      this.formPreviewData = []
      // 档案预编辑获取字段
      const params = {
        categoryId: this.selectedCategory.id,
        archivesId: this.arcId
      }
      this.getFormInfo(params)
    },
    // 著录界面-form/详情-api
    getFormInfo(params) {
      getFormDisplayFields(params).then(data => {
        // this.formPreviewData = data.showFiled.filter((fields) => { return fields.isInput })
        this.formPreviewData = data.showFiled
        this.form.categoryId = this.selectedCategory.id
        this.$nextTick(() => {
          if (this.isEditOrAdd === 'edit') {
            this.$refs.previewForm.addOrUpdateForm = data.echo
          }
        })
      })
    },
    // form - submit
    handlerArchivesSubmit() {
      this.$refs.previewForm.submitForm('addOrUpdateForm')
    },
    // table - 双击查看详情
    tableDoubleClick(row) {
      this.archivesInfoVisible = true
      const params = {
        categoryId: this.selectedCategory.id,
        archivesId: row.id
      }
      this.getFormInfo(params)
    },
    // table - 当前选中得row
    clickRowHandler(row) {
      this.$refs.table.toggleRowSelection(row)
    },
    // 选择删除
    toDelete(data) {
      this.deleteData = data
      this.deleteVisible = true
    },
    // 确认删除
    handleDeltConfirm() {
      this.deleteVisible = false
      this.crud.delAllLoading = true
      // this.crud.doDelete(this.deleteData)
      const ids = []
      this.deleteData.forEach(val => {
        ids.push(val.id)
      })
      const params = {
        'ids': ids,
        'categoryId': this.selectedCategory.id
      }
      // 删除fetch
      del(params).then(res => {
        this.crud.delAllLoading = false
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
        this.crud.refresh()
      })
    },
    // 删除 - 关闭
    handleClose(done) {
      this.deleteData = {}
      done()
    },
    /* 重新渲染table组件 防止table-fixed 错位 配合watch-table数据 */
    doLayout() {
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    uploadFile() {
      this.uploadFileVisible = true
    },
    uploadFileSave() {
      this.uploadFileVisible = false
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/assets/styles/archives-manage.scss";
.preview-dialog {
::v-deep .el-dialog {
    .el-dialog__body{
      padding: 0;
    }
    .preview-content {
      width: auto !important;
      margin-right: 6px;
      overflow: hidden;
      overflow-y: auto;
      .el-textarea__inner {
        border: 1px solid #339cff;
        background-color: transparent;
      }
    }
    .dialog-footer{
      margin: 0 auto;
      padding: 15px 0 20px 0;
    }
  }
}
</style>
