<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          maxlength="100"
          show-word-limit
          clearable v-no-whitespace
          @keyup.enter.native="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新建文件夹</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleDownload(null)">批量下载</el-button>
      </el-col>
    </el-row>

    <!-- 列表 -->
    <el-table
      :data="tableData"
      ref="table"
      fit
      highlight-current-row
      style="width: 100%"
      row-key="coursewareId"
      :tree-props="{ children: 'children' }"
      @selection-change="handleSelectionChange"
      @select-all="handleSelectAll"
    >
      <el-table-column
        type="selection"
        :selectable="isSelectable"
        width="55">
      </el-table-column>
      <el-table-column label="课件库名称" prop="coursewareName" show-overflow-tooltip align="left" />
      <el-table-column label="类型" prop="fileType" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.fileType == 1">{{ '文件夹' }}</div>
          <div v-else-if="scope.row.fileType == 2">{{ '视频文件' }}</div>
          <div v-else-if="scope.row.fileType == 3">{{ 'excel文件' }}</div>
          <div v-else-if="scope.row.fileType == 4">{{ 'pdf文件' }}</div>
          <div v-else-if="scope.row.fileType == 5">{{ 'txt文件' }}</div>
          <div v-else-if="scope.row.fileType == 6">{{ 'word文件' }}</div>
          <div v-else-if="scope.row.fileType == 7">{{ 'ppt文件' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" prop="coursewareSize" align="center">
        <template slot-scope="scope">
          <div v-if="scope.row.fileType == 1">{{ '-' }}</div>
          <div v-else>{{ scope.row.coursewareSize }}</div>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="marl" align="center" show-overflow-tooltip />
      <el-table-column label="修改时间" prop="updateTime" align="center" />
      <el-table-column label="上传人员" prop="createUserName" align="center" />
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            type="text"
            v-if="scope.row.fileType == 1"
            size="mini"
            icon="el-icon-upload"
            @click="handleUpload(scope.row)"
          >
            上传
          </el-button>
          <el-popover placement="bottom" width="40" trigger="hover">
            <div style="display: flex; flex-direction: column; align-items: center">
              <el-button type="text" size="mini" @click="handleDownload(scope.row)" :loading="downLoading">
                下载
              </el-button>
              <el-button type="text" size="mini" @click="handleMove(scope.row)">移动</el-button>
              <el-button type="text" size="mini" @click="handleEdit(scope.row)">重命名</el-button>
              <el-button type="text" size="mini" @click="handleRemark(scope.row)">备注</el-button>
              <el-button type="text" size="mini" @click="handleDelete(scope.row)" style="color: #e47470">
                删除
              </el-button>
            </div>
            <el-button slot="reference" type="text" size="mini" icon="el-icon-s-operation">更多</el-button>
          </el-popover>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新建题库弹框 -->
    <el-dialog :title="questionTitle" :visible.sync="dialogQuestion" width="45%">
      <el-form :model="questionForm" ref="questionForm" size="small" label-width="80px" :rules="questionRules">
        <el-form-item :label="questionLabel">
          <!-- 使用树下拉 -->
          <el-input v-model="questionForm.selectedTree" placeholder="请选择位置" @focus="showTree = true" readonly  v-no-whitespace/>
          <el-tree
            v-show="showTree"
            :data="treeData"
            :props="defaultProps"
            @node-click="handleNodeClick"
            node-key="coursewareId"
            highlight-current
            default-expand-all
            class="tree"
          />
        </el-form-item>
        <el-form-item label="课件名称" prop="coursewareName" v-if="!isMove">
          <el-input
            v-model="questionForm.coursewareName"
            maxlength="100" v-no-whitespace
            show-word-limit
            placeholder="请输入课件名称"
            clearable
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleQuestion" v-preventReClick="5000">确 定</el-button>
        <el-button size="small" @click="dialogQuestion = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 修改课件名-弹框 -->
    <el-dialog :title="editAndRemark" :visible.sync="dialogVisible" width="25%">
      <el-form :model="dialogForm" ref="dialogForm" size="small" label-width="80px" :rules="rules">
        <el-form-item label="旧的名称" prop="oldCoursewareName" v-if="isEdit">
          <el-input v-model="dialogForm.oldCoursewareName" disabled  v-no-whitespace/>
        </el-form-item>
        <el-form-item label="新的名称" prop="coursewareName" v-if="isEdit">
          <el-input
            v-model="dialogForm.coursewareName"
            maxlength="100"
            show-word-limit v-no-whitespace
            placeholder="请输入文件名"
            clearable
          />
        </el-form-item>
        <el-form-item label="文件名称" prop="oldCoursewareName" v-if="isRemark">
          <el-input v-model="dialogForm.oldCoursewareName" disabled  v-no-whitespace/>
        </el-form-item>
        <el-form-item label="备注" prop="marl" v-if="isRemark">
          <el-input
            type="textarea"
            v-model="dialogForm.marl"
            placeholder="请输入备注"
            clearable v-no-whitespace
            maxlength="255"
            show-word-limit
            rows="5"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="handleSave" v-preventReClick="5000">确 定</el-button>
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!-- 上传弹框 -->
    <el-dialog ref="upload" title="上传文件" :visible.sync="uploadVisible" width="55%" style="height: 75vh"
               :destroy-on-close="true"
    >
      <div style="height: 50vh">
        <mini-file-upload file-url="" ref="miniUpload" parent-id="" :params-data="row" v-on:uploadSuccess="uploadSuccess" />
        <div style="height: 5vh; position: absolute;left: 82%;top: 87%">
          <span slot="footer" class="dialog-footer">
            <el-button size="small" type="primary" @click="startUpload" v-preventReClick="5000">确 定</el-button>
            <el-button size="small" @click="uploadVisible = false">取 消</el-button>
          </span>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCoursewareTreeTable,
  getCoursewareLibraryTree,
  addFolder,
  operFolderOrFile,
  uploadFiles,
  downLoadFile,
  downLoadCoursewareFile
} from '@/api/educationalTraining/resourceAdministration'
import axios from 'axios'
import { getToken } from '@/utils/auth'
import { download } from '@/utils/request'
import MiniFileUpload from '@/views/educationalTraining/resourceAdministration/coursewareStore/miniFileUpload.vue'

export default {
  components: { MiniFileUpload },
  data() {
    return {
      fullscreenLoading: false, // 上传loading
      uploadVisible: false, // 上传弹框
      fileList: [], // 上传文件列表
      // 是否显示搜索
      showSearch: true,
      // 查询参数
      queryParams: {
        // 关键字
        keyWord: ''
      },
      // 列表数据
      tableData: [],
      // 弹框
      dialogVisible: false,
      // 弹框表单
      dialogForm: {
        coursewareName: '', // 课件名
        oldCoursewareName: '', // 旧的名称
        marl: '' // 备注
      },
      isEdit: false, // 是否重命名
      isRemark: false, // 是否备注
      isMove: false, // 是否移动
      // 弹框表单验证
      rules: {
        coursewareName: [{ required: true, message: '请输入课件名', trigger: 'blur' }]
      },
      showTree: false, // 是否显示树
      treeData: [], // 树数据
      defaultProps: {
        children: 'children',
        label: 'coursewareName'
      },
      // 新建题库
      questionTitle: '新建题库', // 弹框标题
      dialogQuestion: false, // 是否显示弹框
      questionForm: {
        coursewareName: '', // 题库名称
        selectedTree: '', // 选中的树节点
        parentId: 0 // 父级id
      },
      questionRules: {
        coursewareName: [{ required: true, message: '请输入题库名称', trigger: 'blur' }]
      },
      questionLabel: '位置',
      row: {}, // 当前行
      editAndRemark: '重命名', // 弹框标题
      downLoading: false, // 下载loading
      coursewareIds: [], // 选中的课件id
      isSelect:false
    }
  },
  created() {
    this.getList()
  },
  mounted() {
  },
  methods: {
    isSelectable(row, index) {
      return ![1, 2].includes(Number(row.fileType));
    },
    handleSelectAll() {
      if (!this.isSelect){
        this.coursewareIds = this.getCoursewareIds(this.tableData);
        //设置可选状态的行  选中
        this.isSelect = true
      }else{
        this.$refs.table.clearSelection()
        this.coursewareIds = []
        this.isSelect = false
      }
    },
    getCoursewareIds(data) {
      let ids = [];
      data.forEach(node => {
        console.log('🚀 ~ getCoursewareIds ~ node:', node)
        if (node.coursewareId && Number(node.fileType) !== 1 && Number(node.fileType) !== 2) {
          this.$refs.table.toggleRowSelection(node, true);
          ids.push(node.coursewareId);
        }
        if (node.children && node.children.length > 0) {
          ids = ids.concat(this.getCoursewareIds(node.children));
        }
      });
      return ids;
    },
    handleSelectionChange(val) {
      this.coursewareIds = val.map(item => item.coursewareId).join(',')
      console.log('🚀 ~ handleSelectionChange ~ val:', this.coursewareIds)
    },
    // 搜索
    handleSearch() {
      this.getList()
      setTimeout(() => {
        this.tableData = this.filterTreeData(this.tableData, this.queryParams.keyWord)
      }, 200)
    },
    filterTreeData(data, keyword) {
      return data.reduce((acc, node) => {
        console.log('🚀 ~ filterTree ~ node:', node)
        const { id, parentId, children = [] } = node
        const pid = parentId == '0' ? 0 : parentId
        if (node.coursewareName.includes(keyword)) {
          acc.push({ ...node, pid })
        } else {
          const filteredChildren = this.filterTreeData(children, keyword)
          if (filteredChildren.length > 0) {
            acc.push({ ...node, pid, children: filteredChildren })
          }
        }
        return acc
      }, [])
    },
    // 重置
    handleReset() {
      console.log('重置')
      // 重置查询参数 resetFields
      this.$refs.queryForm.resetFields()
      this.getList()
    },
    // 获取列表
    async getList() {
      const res = await getCoursewareTreeTable()
      console.log('🚀 ~ getList ~ res-课题库-树:', res)
      this.tableData = res.data
      console.log('🚀 ~ getList ~ this.tableData-树:', this.tableData)
    },
    // 上传
    handleUpload(row) {
      console.log('上传', row)
      this.row = row
      this.fileList = []
      this.uploadVisible = true
    },
    // 上传前
    beforeUpload(file) {
      console.log('beforeUpload', file)
      // 文件大小限制
      const isLtFile = file.size / 1024 / 1024 < 200
      if (!isLtFile) {
        this.$message.error('文件大小不能超过200M')
      }
      return isLtFile
    },
    // 上传
    handleChange(file, fileList) {
      console.log('🚀 ~ handleChange ~ file, fileList:', file, fileList)
      // 限制上传文件大小 列表所有文件大小之和 不能超过500M
      let totalSize = 0
      fileList.forEach(item => {
        totalSize += item.size
      })
      const isLtFile = totalSize / 1024 / 1024 < 600
      if (!isLtFile) {
        this.$message.error('文件大小不能超过600M')
        fileList = []
        this.fileList = []
      } else if (fileList.length > 5) {
        this.$message.error('最多上传5个文件')
        // 将当前上传的文件 从 fileList 中删除
        this.fileList = fileList.slice(0, 5)
      } else {
        this.fileList = fileList
      }
      console.log('🚀 ~ handleChange ~ this.文件列表:', this.fileList)
    },
    // 删除
    handleRemove(file, fileList) {
      this.fileList = fileList
      console.log('🚀 ~ handleRemove ~ this.fileList:', this.fileList)
    },
    // 上传-确定
    handleUploading() {
      console.log('上传-确定', this.row)
      console.log('上传-文件列表', this.fileList)
      // 上传
      if (this.fileList.length === 0) {
        this.$message.error('请先选择文件')
        return
      }
      let formData = new FormData()
      this.fileList.forEach(file => {
        formData.append('file[]', file.raw)
      })
      formData.append('parentId', this.row.coursewareId)
      console.log('🚀 ~ handleUploading ~ formData:', formData.get('file[]'))
      console.log('🚀 ~ handleUploading ~ formData:', formData.get('parentId'))
      // loading
      this.fullscreenLoading = true

      uploadFiles(formData).then(res => {
        console.log('🚀 ~ handleUploading ~ res:', res)
        // 关闭弹框
        this.uploadVisible = false
        // 刷新列表
        this.getList()
        // 关闭loading
        setTimeout(() => {
          this.fullscreenLoading = false
        }, 100)
      })
    },
    // 下载
    async handleDownload(row) {
      this.downLoading = true
      console.log('下载', row)
      if (!row) {
        // 批量下载
        const params = {
          coursewareId: this.coursewareIds,
          fileType: 1
        }
        console.log('🚀 ~ handleDownload ~ params:', params)
        download('/exam/coursewareLibrary/downLoadFile', params, '课件库.zip').then(res => {
          console.log('🚀 ~ handleDownload ~ res:', res)
        })
        setTimeout(() => {
          this.downLoading = false
        }, 300)
        return
      }
      const params = {
        coursewareId: row.coursewareId,
        fileType: row.fileType
      }
      // dev-api/exam/coursewareLibrary/downLoadFile
      // 获取当前的 location.origin
      const origin = window.location.origin
      console.log('🚀 ~ handleDownload ~ origin:', origin)
      // window.open(
      //   // `${origin}/prod-api/exam/coursewareLibrary/downLoadFile?coursewareId=${row.coursewareId}&fileType=${row.fileType}`
      //   `${origin}/dev-api/exam/coursewareLibrary/downLoadFile?coursewareId=${row.coursewareId}&fileType=${row.fileType}`
      // )
      download('/exam/coursewareLibrary/downLoadFile', params, row.coursewareName + row.suffix).then(res => {
        console.log('🚀 ~ handleDownload ~ res:', res)
      })
      setTimeout(() => {
        this.downLoading = false
      }, 300)
      // let type = ''
      // if (row.fileType == 1) {
      //   // 文件夹-zip压缩包
      //   type = 'application/zip'
      // } else if (row.fileType == 2) {
      //   // 视频
      //   type = 'video/mp4'
      // } else if (row.fileType == 3) {
      //   // excel
      //   type = 'application/vnd.ms-excel'
      // } else if (row.fileType == 4) {
      //   // pdf
      //   type = 'application/pdf'
      // } else if (row.fileType == 5) {
      //   // txt
      //   type = 'text/plain'
      // } else if (row.fileType == 6) {
      //   // word
      //   type = 'application/msword'
      // }
      // downLoadFile(params).then(res => {
      //   console.log('🚀 ~ handleDownload ~ res-下载:', res)
      //   // 返回的是文件流, 使用blob处理
      //   // 创建 Blob 对象
      //   const blob = new Blob([res.data], { type: type })
      //   console.log('🚀 ~ downLoadFile ~ blob:', blob)
      //   const url = window.URL.createObjectURL(blob) // 创建一个指向该 Blob 的 URL
      //   console.log('🚀 ~ downLoadFile ~ url:', url)

      //   // 创建下载链接
      //   const link = document.createElement('a')
      //   link.href = url
      //   // link.download = fileName === '' ? filePath.split('/')[filePath.split('/').length - 1] : fileName
      //   link.download = '下载文件.pdf'
      //   document.body.appendChild(link)
      //   link.click()
      //   // window.URL.revokeObjectURL(url)
      //   // let fileName = link.href.split('/')[link.href.split('/').length - 1]
      //   // link.setAttribute('download', fileName) // 设置下载文件名

      //   // 触发下载
      //   // document.body.appendChild(link)
      //   // link.click()

      //   // 清理
      //   document.body.removeChild(link)
      //   window.URL.revokeObjectURL(url) // 释放内存
      // })
    },
    // 移动
    handleMove(row) {
      console.log('移动', row)
      this.row = row
      this.questionTitle = '移动文件'
      this.questionLabel = '移动到'
      this.questionForm.coursewareName = ''
      this.questionForm.parentId = 0
      this.isMove = true
      this.treeData = []
      this.questionForm.selectedTree = ''
      // 获取树
      this.getCoursewareLibraryTree({ coursewareId: row.coursewareId, fileType: row.fileType, type: 2 })
      // 打开弹框
      this.dialogQuestion = true
    },
    // 重命名
    handleEdit(row) {
      console.log('重命名', row)
      this.editAndRemark = '文件重命名'
      this.isEdit = true
      this.isRemark = false
      this.row = row
      this.dialogForm.oldCoursewareName = row.coursewareName
      this.dialogForm.coursewareName = ''
      this.dialogVisible = true
      setTimeout(() => {
        this.$refs.dialogForm.clearValidate()
      }, 100)
    },
    // 备注
    handleRemark(row) {
      console.log('备注', row)
      this.row = row
      this.editAndRemark = '文件备注'
      this.isEdit = false
      this.isRemark = true
      this.dialogForm.oldCoursewareName = this.row.coursewareName
      this.dialogForm.marl = row.marl
      this.dialogVisible = true
    },
    // 删除
    handleDelete(row) {
      console.log('删除', row)
      // 弹框提示
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确定
        operFolderOrFile({
          operType: 3,
          coursewareId: row.coursewareId,
          fileType: row.fileType,
          parentId: row.parentId
        }).then(res => {
          console.log('🚀 ~ handleDelete ~ res:', res)
          // 刷新列表
          this.getList()
        })
      })
    },
    // 保存修改
    handleSave() {
      console.log('保存修改')
      // 表单验证
      this.$refs.dialogForm.validate(valid => {
        if (valid) {
          // 保存修改
          console.log('保存修改', this.dialogForm)
          if (this.isEdit) {
            // 重命名
            operFolderOrFile({
              operType: 1,
              coursewareId: this.row.coursewareId,
              fileType: this.row.fileType,
              coursewareName: this.dialogForm.coursewareName,
              parentId: this.row.parentId
            }).then(res => {
              console.log('🚀 ~ handleSave ~ res:', res)
              // 关闭弹框
              this.dialogVisible = false
              // 刷新列表
              this.getList()
            })
          } else {
            // 备注
            operFolderOrFile({
              operType: 2,
              coursewareId: this.row.coursewareId,
              fileType: this.row.fileType,
              marl: this.dialogForm.marl
            }).then(res => {
              console.log('🚀 ~ handleSave ~ res:', res)
              // 关闭弹框
              this.dialogVisible = false
              // 刷新列表
              this.getList()
            })
          }
        }
      })
    },
    // 获取课件库树
    async getCoursewareLibraryTree(item) {
      const params = {
        coursewareId: item.coursewareId,
        fileType: item.fileType,
        type: item.type
      }
      const res = await getCoursewareLibraryTree(params)
      console.log('🚀 ~ getCoursewareLibraryTree ~ res-位置树:', res)
      this.treeData = res.data
    },
    // 树节点点击
    handleNodeClick(data) {
      console.log('handleNodeClick', data)
      this.questionForm.selectedTree = data.coursewareName
      this.questionForm.parentId = data.coursewareId
      this.showTree = false
    },
    // 新建题库
    handleAdd() {
      console.log('新建题库')
      this.questionTitle = '新建课件'
      this.questionLabel = '位置'
      this.isMove = false
      this.getCoursewareLibraryTree({ coursewareId: 0, fileType: 1, type: 1 })
      this.questionForm.coursewareName = ''
      this.questionForm.selectedTree = ''
      this.questionForm.parentId = 0
      this.dialogQuestion = true
      setTimeout(() => {
        this.$refs.questionForm.clearValidate()
      }, 100)
    },
    // 新建题库-确定
    handleQuestion() {
      console.log('新建题库-确定', this.questionForm)
      // 表单验证
      this.$refs.questionForm.validate(valid => {
        if (valid) {
          // 保存
          console.log('保存', this.questionForm)
          if (this.isMove) {
            // 移动
            operFolderOrFile({
              operType: 4,
              coursewareId: this.row.coursewareId,
              fileType: this.row.fileType,
              parentId: this.questionForm.parentId
            }).then(res => {
              console.log('🚀 ~ handleQuestion ~ res:', res)
              // 关闭弹框
              this.dialogQuestion = false
              // 刷新列表
              this.getList()
            })
          } else {
            // 新建
            addFolder(this.questionForm).then(res => {
              console.log('🚀 ~ handleQuestion ~ res:', res)
              // 关闭弹框
              this.dialogQuestion = false
              // 刷新列表
              this.getList()
            })
          }
        }
      })
    },
    startUpload() {
      this.$refs.miniUpload.startUpload()
    },
    uploadSuccess() {
      this.uploadVisible = false
      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.tree {
  margin-top: 10px;
  border: #cecece 1px solid;
  border-radius: 5px;
  overflow: hidden;
}

.upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.upload-demo {
  width: 100%;
  max-width: 500px;
}
</style>
