<template>
  <div>
    <div class="head-container">
      <div>
        <el-button size="mini" @click="toAdd">
          <i class="iconfont icon-xinzeng" />
          新增
        </el-button>
        <el-button size="mini" :disabled="crud.selections.length !== 1" @click="toEdit(crud.selections[0])">
          <i class="iconfont icon-bianji" />
          编辑
        </el-button>
        <el-button slot="reference" size="mini" :disabled="crud.selections.length === 0" @click="toDelete(crud.selections)">
          <i class="iconfont icon-shanchu" />
          删除
        </el-button>
        <el-button :disabled="crud.selections.length === 0" size="mini" @click="doExport(crud.selections)">
          <i class="iconfont icon-daochu" />
          导出
        </el-button>
      </div>
      <div class="online-right-handle">
        <el-button size="mini" @click="handleUpload"><i class="iconfont icon-shangchuan2" />附件上传</el-button>
        <el-button size="mini" :disabled="crud.selections.length === 0" @click="toPublish(crud.selections)"><i class="iconfont icon-fabu" />发布</el-button>
        <el-button size="mini"><i class="iconfont icon-huifu" />取消发布</el-button>
      </div>
    </div>
    <el-table
      ref="table"
      :data="crud.data"
      row-key="id"
      style="width: 100%;"
      height="calc(100vh - 485px)"
      @cell-dblclick="tableDoubleClick"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" :reserve-selection="true" width="55" align="center" />
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column prop="username" label="文档名称" align="center" />
      <el-table-column prop="browser" label="创建人" align="center" />
      <el-table-column prop="createTime" label="加入时间" width="200">
        <template slot-scope="scope">
          <div>{{ scope.row.createTime | parseTime }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="状态" align="center" />
    </el-table>
    <pagination v-if="crud.data.length !== 0" />

    <el-dialog class="fileUpload-dialog" title="附件上传" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="uploadVisible">
      <div class="setting-dialog">
        <div class="upload-container">
          <i v-if="fileList.length === 0" class="iconfont icon-tianjiawenjian upload-icon" />
          <div v-for="item in fileList" :key="item.name" class="file-list">
            <i class="iconfont icon-xiaowenjian" />
            {{ item.name }}
            <i class="el-icon-close" @click="deleteFile(item)" />
          </div>
          <div class="upload-input">
            <input ref="fileInput" :key="key" type="file" :accept="'.zip'" @change="handleFileChange">
            <div class="upload-zip"><i class="iconfont icon-shangchuan2" />点击上传</div>
          </div>
          <div class="el-upload__tip">上传限制文件类型：zip</div>

        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="uploadVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUploadConfirm">保存</el-button>
        </div>
      </div>
    </el-dialog>

    <el-dialog class="detail-dialog" title="编研详情" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="onlineEditDetail" :before-close="handleCloseDialog">
      <div class="setting-dialog">
        <div class="detail-tab tab-content">
          <!-- tab -->
          <ul class="tab-nav">
            <li :class="{'active-tab-nav': onlineTabIndex == 0}" @click="changeOnlineTab(0)">文档正文</li>
            <li :class="{'active-tab-nav': onlineTabIndex == 1}" @click="changeOnlineTab(1)">文档附件</li>
          </ul>
          <div v-if="onlineTabIndex===0">文档正文</div>
          <el-table
            v-if="onlineTabIndex===1"
            ref="table"
            :data="detailArcData"
            row-key="id"
            style="width: 100%;"
            height="calc(100vh - 560px)"
          >
            <el-table-column type="index" label="序号" align="center" width="55" />
            <el-table-column prop="title" label="附件名称">
              <template>
                <div class="title-style"><span>文件</span>【档号】题名</div>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="格式" />
            <el-table-column prop="title" label="大小" />
            <el-table-column prop="title" label="操作者" />
            <el-table-column prop="title" label="加入时间" />
          </el-table>
        </div>
      </div>
    </el-dialog>
    <OnlineAdd ref="onlineAdd" />
  </div>
</template>

<script>

import CRUD, { presenter, crud } from '@crud/crud'
import pagination from '@crud/Pagination'
import OnlineAdd from './onlineAdd'
import { upload } from '@/utils/upload'
import { mapGetters } from 'vuex'

export default {
  name: 'OnlineEditing',
  components: { pagination, OnlineAdd },
  mixins: [presenter(), crud()],
  cruds() {
    return CRUD({
      url: 'api/log/initLog',
      title: '在线编研',
      optShow: {
        add: false,
        edit: false,
        del: false,
        download: false,
        reset: false,
        group: false
      }
    })
  },
  props: {
    activeIndex: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      selections: [],
      keyWord: null,
      options: [
        { value: 'username', label: '利用人' },
        { value: 'account', label: '利用事由' }
      ],
      optionVal: '',
      startTime: null,
      endTime: null,
      lendDetail: false,
      form: {
        user: '张三',
        process: '档案借阅流程-张三-2023-01-01',
        startDate: '2016-09-21 08:50:08',
        endDate: '2016-10-21 08:50:08',
        remark: '利用事由'
      },
      detailArcData: [],
      checkList: ['电子查看', '实体借阅'],
      onlineEditDetail: false,
      onlineTabIndex: 0,
      uploadVisible: false,
      fileList: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  watch: {
    activeIndex: function(newValue, oldValue) {
      console.log('newValue', newValue)
      this.crud.query.isType = newValue
      this.crud.toQuery()
    }
  },
  mounted() {
  },
  methods: {
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.query.isType = this.activeIndex
    },
    changeOnlineTab(data) {
      this.onlineTabIndex = data
    },
    toAdd() {
      this.$refs.onlineAdd.onlineTitle = '新增在线编研'
      this.$refs.onlineAdd.onlineAddVisible = true
    },
    toEdit() {
      this.$refs.onlineAdd.onlineTitle = '编辑在线编研'
      this.$refs.onlineAdd.onlineAddVisible = true
    },
    tableDoubleClick() {
      this.onlineEditDetail = true
    },
    toDelete(data) {
      if (data.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此操作将删除当前所选编研主题' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds
        }
        console.log(params)
      }).catch(() => {
      })
    },
    // 导出
    doExport(data) {
      if (data.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds
        }
        console.log(params)
        // exportFile(this.baseApi + '/api/collect/exportDate?' + qs.stringify(params, { indices: false }))
      }).catch(() => {
      })
    },
    toPublish(data) {
      if (data.length === 0) {
        this.$message({ message: '您还未勾选需要操作的条目，请先确认！', offset: 8 })
        return false
      }
      this.$confirm('此操作将发布当前所选文档' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const archivesIds = []
        this.selections.forEach(val => {
          archivesIds.push(val.id)
        })
        const params = {
          'categoryId': this.selectedCategory.id,
          'categoryLevel': this.collectLevel,
          'archivesIds': archivesIds
        }
        console.log(params)
      }).catch(() => {
      })
    },
    handleUpload() {
      if (this.crud.selections.length !== 1) {
        this.$message({ message: '只可勾选唯一目标条目，请先确认！', offset: 8 })
        return false
      }
      this.uploadVisible = true
    },
    handleFileChange(e) {
      const files = e.target.files
      this.file = files[0]
      this.key++
      const maxMessage = '上传文件大小不能超过 10MB，可使用大文件上传!'
      const maxSize = 10 * 1024 * 1024
      if (this.file && this.file.size > maxSize) {
        this.$message({ message: maxMessage, type: 'warning', offset: 8 })
        this.fileList = []
        e.target.value = ''
        return false
      }
      if (this.fileList.length !== 0) {
        const existingFile = this.fileList.some(file => file.name === this.file.name)
        if (existingFile) {
          this.$message({ message: '文件已存在', type: 'warning', offset: 8 })
          return false
        }
      }
      for (let i = 0; i < files.length; i++) {
        if (this.uploadType === 2) {
          this.fileList = []
          this.fileList.push(files[i])
        } else {
          this.fileList.push(files[i])
        }
      }
    },
    handleUploadConfirm() {
      if (this.fileList.length === 0) {
        this.$message({ message: '请先选择相关文件！', offset: 8 })
        return false
      }
      // 原文目录上传
      upload(this.baseApi + '/api/collect/catalogUpload',
        this.fileList[0]
      ).then(res => {
        if (res.data.code === 200) {
          // 暂不用写太详细的失败成功信息，只要200，就操作成功
          // this.$message.success('成功追加' + res.data.data + '附件')
          this.$message({ message: '操作成功', type: 'success', offset: 8 })
          // this.$emit('close-dialog')
          this.uploadVisible = false
        } else {
          this.$message({ message: '操作失败', type: 'error', offset: 8 })
        }
      })
    },
    handleCloseDialog(done) {
      this.lendDetail = false
      this.onlineEditDetail = false
      // 关闭弹框
      // done()
    }
  }
}
</script>

<style lang="scss" scoped>
.head-container{
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}
// ::v-deep .el-checkbox-group{
//   .el-checkbox{
//     margin-right: 10px !important;
//   }
// }
::v-deep .el-pagination{
  margin: 24px 0 10px 0 !important
}
</style>
