<template>
  <div class="rrr">
    <!--工具栏-->
    <div class="head-container">
      <div class="head-archives-top">
        <div class="head-search">
          <!-- 搜索 -->
          <el-input v-model="query.blurry" clearable size="small" placeholder="请输入关键词" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
          <el-select 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>
          <rrOperation />
        </div>
        <el-checkbox 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-permission="permission.download" :loading="crud.downloadLoading" :disabled="!crud.data.length" size="mini" icon="el-icon-download" @click="crud.doExport">导出</el-button>
        </template>
        <template v-slot:rightButtonGroup>
          <div class="archives-handler-btn">
            <el-button class="packing-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">
        <ul class="archives-tab">
          <li :class="{'active': archivesTabIndex == 0}" @click="changeActiveTab(0)">基本信息</li>
          <li v-if="isEditOrAdd !== 'add'" :class="{'active': archivesTabIndex == 1}" @click="changeActiveTab(1)">上传附件</li>
        </ul>
        <PreviewForm v-if="formPreviewData.length && archivesTabIndex == 0" ref="previewForm" :is-disabled="false" :form-preview-data.sync="formPreviewData" :selected-category="selectedCategory" :arc-id="arcId" />
        <UploadFile v-if="archivesTabIndex==1" />
        <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 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">
      <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 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 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 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 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 />
  </div>
</template>

<script>
import { add, edit, del, getTableDisplayFields, getFormDisplayFields } from '@/api/archivesManage/archivesList'
import CRUD, { presenter, header, form } from '@crud/crud'
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'

export default {
  components: { crudOperation, rrOperation, pagination, PreviewForm, UploadFile },
  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: ['department,asc']
      })
    ]
  },
  data() {
    return {
      stateOptions: [ // 搜索 - 状态选择
        { key: '1', label: '全部' },
        { key: '2', label: '未装' },
        { key: '3', label: '未入' },
        { key: '4', label: '在库' },
        { key: '5', label: '待借' },
        { key: '6', label: '已借' }
      ],
      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
    }
  },
  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()
    }
  },
  mounted() {
  },
  methods: {
    // 获取数据前设置默认参数
    // [CRUD.HOOK.beforeRefresh]() {
    //   this.crud.query.id = this.dicPid
    // },
    // [CRUD.HOOK.afterRefresh](crud) {
    //   console.log(this.curd)
    //   // if (this.needRefreshTree) {
    //   //   this.$emit('treeRefresh', crud.data)
    //   // }
    // },
    [CRUD.HOOK.beforeRefresh]() {
      this.getTableDisplayFieldsLoading = true
      // 档案列表获取显示列
      getTableDisplayFields({ categoryId: this.selectedCategory.id }).then(data => {
        this.tableDisplayFields = data
        this.getTableDisplayFieldsLoading = false
        return true
      })
    },
    [CRUD.HOOK.beforeToCU](crud, form, btn) {
      this.isEditOrAdd = btn
      this.selectedData = crud.selections
      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 = []
      // 档案预编辑获取字段
      getFormDisplayFields({ categoryId: this.selectedCategory.id }).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 = this.selectedData[0]
          }
        })
        return true
      })
    },
    // [CRUD.HOOK.beforeToEdit](crud, form, btn) {
    //   console.log(this.crud)
    //   this.$nextTick(() => {
    //     console.log(this.$refs.previewForm)
    //   })
    // },
    changeActiveTab(index) {
      this.archivesTabIndex = index
    },
    handlerArchivesSubmit() {
      // let arcId
      // if (this.isEditOrAdd === 'add') {
      //   arcId = null
      //   this.tabDisabled = true
      // } else if (this.isEditOrAdd === 'edit') {
      //   arcId = this.selectedData[0].id
      //   this.tabDisabled = false
      // }
      this.$refs.previewForm.submitForm('addOrUpdateForm')
    },
    // 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()
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
@import "~@/assets/styles/archives-manage.scss";
.preview-dialog {
::v-deep .el-dialog {
    width: 940px !important;
    .el-dialog__body{
      padding: 0;
      height: calc(100vh - 174px);
    }
    .preview-content {
      overflow: hidden;
      overflow-y: auto;
      .el-textarea__inner {
        border: 1px solid #339cff;
        background-color: transparent;
      }
    }
    .el-dialog__header {
      width: 420px;
    }
    .dialog-footer{
      margin: 0 auto;
      padding: 15px 0 30px 0;
    }
  }
}
</style>
