<template>
  <el-container class="box" v-loading="loading">
    <el-header>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="item in breadcrumbList" :key="item.path" class="selectFileBreadcrumb" @click.native="breadcrumbClick(item)">{{ item.name }}</el-breadcrumb-item>
      </el-breadcrumb>
    </el-header>
    <div class="main" @contextmenu.prevent="boxRightClick" @click="close">
      <div class="selectFileMain">
        <div v-for="(item, index) in list" :key="index" class="filesBox" @click="is_index = item.name" :class="{ 'isselect': is_index == item.name }" @dblclick="itemClick(item)" @contextmenu.prevent.stop="itemRightClick(item, $event)">
          <i :class="item.icon" class="fileIcon" v-if="item.type !== 'image'" style="width: 100px; height: 100px"></i>
          <el-image v-else :src="item.url" fit="fit" class="imageFile"></el-image>
          <div class="fileName">{{ item.name }}</div>
        </div>
        <el-card class="box-card" v-if="position.show" :style="{ 'top': position.top + 'px', 'left': position.left + 'px' }">
          <p class="card-item" v-for="(item, index) in operateList" :key="index" @click="positionClick(item)">{{ item.label }}</p>
        </el-card>
      </div>
    </div>
    <input @change="inputChage" ref="fileInput" type="file" v-show="false">
    <el-dialog :title="dialogInfo.title" :visible.sync="dialogInfo.dialogVisible" :width="dialogInfo.width">
      <dynamicForm ref="dynamicForm" v-if="formFiled && dialogInfo.dialogVisible" :filed="formFiled" :data="formData" @save="formSave"></dynamicForm>
    </el-dialog>
  </el-container>
</template>

<script>
import { openFiles, addFile, editFile, delFile, managerUpload } from "@/api/files/upload";
export default {
  name: 'SelectFile',
  props: {},
  components: {},
  computed: {},
  data() {
    return {
      loading: false,
      is_index: '',
      path: '',
      breadcrumbList: [],
      isItem: {},
      list: [],
      position: {
        show: false
      },
      operateList: [],
      litemList: [
        { name: 'edit', label: '重命名' },
        { name: 'downloadFile', label: '下载' },
        { name: 'delete', label: '删除' },
      ],
      boxList: [
        { name: 'add', label: '新建文件夹' },
        { name: 'uploadFile', label: '上传文件' },
      ],
      dialogInfo: {
        title: "",
        dialogVisible: false,
        width: "50%",
      },
      formFiled: [],
      formData: {},
      add: false,
      is_item: {}
    };
  },
  async created() {
    this.path = '/';
    this.query();
  },
  methods: {
    async query(e) {
      const res = await openFiles({ path: this.path });
      this.list = res.data.map(e => {
        if (e.isDirectory) {
          e.icon = e.isEmpty == true ? 'el-icon-folder' : 'el-icon-folder-opened';
          e.type = 'folder'
        }
        if (!e.isDirectory) {
          if (e.name.includes('jpg') || e.name.includes('png') || e.name.includes('jpeg')) {
            e.icon = 'el-icon-picture';
            e.type = 'image'
          }
          if (!e.name.includes('jpg') && !e.name.includes('png')) {
            e.icon = 'el-icon-tickets'
            e.type = 'file'
          }
          
        }
        return e;
      });
    },
    // 双击
    async itemClick(item) {
      if (item.isDirectory) {
        this.path = this.path == '/' ? `${item.path}${item.name}` : `${item.path}/${item.name}`;
        this.query(this.path)
        return;
      }
    },
    setBreadcrumb() {
      const list = this.path.split('/').filter(Boolean);
      this.breadcrumbList = list.map((name, index) => ({
        name: name,
        path: `/${list.slice(0, index + 1).join('/')}`,
      }));
      this.breadcrumbList.unshift({ name: '根目录', path: '/' });
    },
    // 点击面包屑
    breadcrumbClick(item) {
      this.path = item.path;
      this.query(this.path)
    },
    // 选项右键
    async itemRightClick(item, e) {
      this.is_item = item;
      this.operateList = item.directory ? this.litemList.filter(j => j.name !== 'downloadFile') : this.litemList;
      this.position = { show: true, top: e.pageY, left: e.pageX }
    },
    // 空白右键
    async boxRightClick(e) {
      this.is_item = {};
      this.operateList = this.boxList;
      this.position = { show: true, top: e.pageY, left: e.pageX }
    },
    // 关闭
    close() {
      this.position.show = false;
    },
    // 选项点击
    positionClick(e) {
      if (e.name == 'add') this.addFolder();
      if (e.name == 'uploadFile') this.uploadFile();
      if (e.name == 'edit') this.edit();
      if (e.name == 'delete') this.del();
      if (e.name == 'downloadFile') this.downloadFile();
      
    },
    // 创建文件夹
    async addFolder() {
      this.formFiled = [{ name: 'dirName', label: '文件夹名称', type: 'addFolder' }];
      this.dialogInfo.title = '创建文件夹'
      this.dialogInfo.dialogVisible = true;
      this.add = true;
    },
    // 上传文件
    async uploadFile() {
      this.$refs.fileInput.click();
    },
    async inputChage(e) {
      var data = new FormData();
      data.append('file', this.$refs.fileInput.files[0]);
      data.append('path', this.path);
      const res = await managerUpload(data);
      if (res.code == 200) {
        this.$modal.msgSuccess(`上传成功`);
        this.query();
        this.$refs.fileInput.value = null;
      }
    },
    // 修改
    async edit() {
      this.formFiled = [{ name: 'newName', label: '文件夹名称', type: 'edit' }];
      this.dialogInfo.title = '修改'
      this.add = false;
      this.dialogInfo.dialogVisible = true;
    },
    // 删除
    async del() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', { type: 'warning' })
      .then(async () => {
        const res = await delFile(this.is_item);
        if (res.code == 200) {
          this.$modal.msgSuccess(`删除成功`);
          this.query();
        }
      })
      .catch(_ => {});
    },
    // 下载
    downloadFile() {
      this.download(`/file-manager/download`, {
        path: this.path,
        fileName: this.is_item.name
      }, this.is_item.name)
    },
    // 表单保存
    async formSave(e) {
      console.log('表单保存');
      let res;
      // 添加
      if (this.add) res = await addFile({ ...e, path: this.path });
      // 修改
      if (!this.add) {
        const originName = this.is_item.name;
        res = await editFile({ ...e, path: this.path, originName });
      }
      if (res.code == 200) {
        this.$modal.msgSuccess(`${!this.add ? '修改' : '新增'}成功`);
        this.dialogInfo.dialogVisible = false;
        this.query();
      }
    },
  },
  watch: {
    path() {
      this.setBreadcrumb();
    }
  }
};
</script>
<style lang="scss" scoped>
  .box {
    width: 100%;
    .el-header {
      width: 100%;
      padding: 0;
      .el-breadcrumb {
        padding-left: 2em;
        border: 1px solid #c0ccda;
      }
      .selectFileBreadcrumb {
        text-align: left;
        line-height: 3em;
        cursor: pointer;
      }
    }
    .main {
      width: 100%;
      height: 80vh;
      overflow-y: auto;
    }
  }
  .selectFileMain {
    position: relative;
    // height: 100%;
    width: 100%;
    margin: 0 auto;
    display: flex;
    flex-wrap: wrap;
    // padding-bottom: 50px;
  }
  .fileName {
    width: 100%;
    text-align: center;
  }
  .filesBox {
    max-width: 100px;
    max-height: 120px;
    margin: 20px 18px;
    cursor: pointer;
  }
  .fileIcon {
    display: block;
    text-align: center;
    border-radius: 12px;
    line-height: 100px;
    background: #F5F7FA;
    font-size: 28px;
  }
  .imageFile {
    width: 100px;
    height: 100px;
    display: block;
    border-radius: 12px;
    overflow: hidden;
  }
  .isFileName {
    font-size: 12px;
    color: #999;
    line-height: 1.5em;
    width: 90%;
    margin: 0 auto;
  }
  .box-card {
    position: fixed;
    z-index: 9999;
  }
  
  .card-item {
    border-bottom: 1px solid #c0ccda;
    padding: 0 20px;
    margin: 0;
    line-height: 2em;
    cursor: pointer;
  }
  .isselect {
    color: red;
  }
</style>