<template>
  <div class="documentCompletion-data">
    <el-tabs v-model="activeName" class="p-4" @tab-click="handleClick">
      <el-tab-pane label="文件夹" name="first">
        <el-button type="success" :disabled="toolStart" @click="handleFile(3)"
          ><el-icon><Plus /></el-icon>新建文件夹</el-button
        >
        <el-button type="primary" :disabled="toolStart" @click="handleFile(2)"
          ><el-icon><Upload /></el-icon>上传文件</el-button
        >
        <el-card style="margin-top: 10px">
          <div class="breadcrumb-img">
            <el-breadcrumb>
              <el-breadcrumb-item @click="onBreadcrumb(item)" v-for="(item, i) of breadcrumbList" :key="i">
                <span title="点击打开文件夹" style="cursor: pointer">{{ item.fileName }}</span>
              </el-breadcrumb-item>
            </el-breadcrumb>
            <div class="tool-All">
              <div v-if="!toolStart">
                <el-button type="primary" v-hasPermi="['project:project:remove']" @click="onBatchAll">
                  <el-icon><Menu /></el-icon>批量操作</el-button
                >
              </div>
              <div v-if="toolStart">
                <el-button type="warning" @click="onBatchAll">
                  <el-icon><Tools /></el-icon>取消操作</el-button
                >
                <el-button type="danger" @click="onDeleteAll">
                  <el-icon><Delete /></el-icon>删除</el-button
                >
              </div>
            </div>
          </div>
        </el-card>
        <el-card style="margin-top: 10px">
          <div class="file_detail" id="file_detail1">
            <el-row class="row-bg" v-if="fileList.length">
              <el-col :span="2" v-for="(item, i) of fileList" :key="i">
                <div :class="{ file_style: true }">
                  <div @click="onNav(item)" title="点击打开文件" @contextmenu="onContextmenu($event, item, i)">
                    <img src="../../../assets/icons/svg/file1.png" v-if="item.fileType == '2'" alt="" />
                    <img src="../../../assets/icons/svg/file.png" v-else-if="item.fileType == '1'" alt="" />
                    <el-image
                      v-else-if="item.fileType == '3'"
                      style="width: 100%; height: 100%"
                      :src="item.filePath"
                      :zoom-rate="1.2"
                      :max-scale="7"
                      :min-scale="0.2"
                      :initial-index="4"
                      :preview-src-list="[item.filenPathCoding]"
                      fit="cover"
                    />
                    <img :src="'/icon/' + item.fileType + '.png'" v-else />
                  </div>
                  <span @click="onFileName(item)" title="点击重命名">{{ item.fileName }}</span>
                  <div :class="{ fileActive: toolStart }" v-if="toolStart" @click="onToolAll(item)"></div>
                  <div class="checkbox-box" v-if="toolStart">
                    <el-checkbox v-model="item.checkbox" size="large" />
                  </div>
                </div>
              </el-col>
            </el-row>
            <el-empty :image-size="200" description="暂无文件" v-else />
            <div class="right_box" id="right_box">
              <div v-for="(item, i) of list" :key="i" @click="item.callback($event)">
                {{ item.name }}
              </div>
            </div>
          </div>
        </el-card>
      </el-tab-pane>
      <el-tab-pane label="回收站" name="second">
        <RecyclingStation ref="RecyclingStationRef"></RecyclingStation>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script lang="ts">
import { toRefs, reactive, onMounted, ref, defineComponent, computed, getCurrentInstance, toRaw, nextTick, onBeforeUnmount } from 'vue';
import { ElMessageBox, ElMessage, ElLoading } from 'element-plus';
import {
  documentCompletionTreeStructure,
  documentCompletionDelete,
  documentCompletionAdd,
  documentCompletionEdit,
  newFolder,
  uniFileDownload
} from '@/api/safety/documentSafetyMeeting/index';
import { useUserStoreHook } from '@/store/modules/user';

// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
// 回收站
import RecyclingStation from '@/views/safety/documentSafetyMeeting/RecyclingStation/index.vue';
export default defineComponent({
  name: 'index',
  components: {
    RecyclingStation
  },
  setup() {
    const { proxy } = <any>getCurrentInstance();
    const RecyclingStationRef = ref();
    // 字典选项数据
    const {} = proxy.useDict();
    // 文件下载
    const onExport = (event) => {
      event.stopPropagation();
      // 文件下载 state.typeFile: 2、文件夹 1、文件
      if (state.typeFile == '2') {
        window.open(state.relativePath, '_black');
      } else {
        uniFileDownload({ relativePath: state.relativePath, type: state.typeFile }).then((res) => {
          if (res.code == 200) {
            window.open(res.data.Path, '_black');
          }
        });
      }
    };
    // 文件删除
    const onDeleteFile = (event) => {
      event.stopPropagation();
      setDel([state.delId]);
    };
    const state = reactive({
      fileList: [],
      activeName: 'first',
      breadcrumbList: [{ id: 0, fileName: '目录' }], //菜单列表
      projectId: currentProject.value?.id,
      parentPid: '0', //父级的id 默认为0
      fileType: 0, //文件 或压缩文件
      list: [
        { id: 1, name: '文件下载', callback: onExport, auth: 'api/v1/system/documentSafetyMeeting/safetyDataUniFileDownload' },
        { id: 2, name: '文件删除', callback: onDeleteFile, auth: 'api/v1/system/documentSafetyMeeting/delete' }
      ],
      relativePath: '', //文件下载需要相对路径
      delId: '', //删除需要的id
      toolStart: false,
      imageType: ['jpg', 'png', 'jpeg'],
      wordType: ['docx', 'doc', 'pdf', 'xls', 'xlsx', 'pptx', 'ppt'],
      typeFile: ''
    });
    onMounted(() => {
      // 全局设置阻止右键点击
      document.addEventListener('contextmenu', function (event) {
        event.preventDefault();
      });
      let file_detail_box = document.getElementById('file_detail1');
      // 监听当前元素点击事件  并关闭弹框
      file_detail_box.addEventListener('click', () => {
        let box = document.getElementById('right_box');
        box.style.display = 'none';
      });
      // 默认第一级 父级pid为0
      getdocumentCompletionTreeStructure();
      // 压缩文件上传

      proxy.mittBus.on('bigUploader.uploadFileSuccess' + 1010, (res: any) => {
        const { filename, totalSize, url, identifier, fileType } = res;
        let arr = filename.split('.');
        let fileType1 = arr[arr.length - 1];
        if (fileType1 == 'zip' || fileType1 == 'rar') {
          state.fileType = 1;
        } else {
          //除了压缩 其他文件
          state.fileType = 2;
        }
        let obj = {
          filePath: {
            url,
            name: filename,
            size: totalSize,
            fileType: '.' + fileType1 //后缀名
          },
          file: ''
        };
        documentCompletionAdd(obj).then((res: any) => {
          if (res.code == 200) {
            ElMessage({
              type: 'success',
              message: '上传成功'
            });
            getdocumentCompletionTreeStructure(); //获取当前当前文件夹的文件数据
          } else {
            ElMessage({
              type: 'error',
              message: res.message
            });
          }
        });
      });
    });
    onBeforeUnmount(() => {
      // 取消订阅特定事件
      proxy.mittBus.off('bigUploader.uploadFileSuccess' + 1010);
    });
    const getdocumentCompletionTreeStructure = () => {
      const loading = ElLoading.service({
        lock: true,
        text: '正在查询文件……',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      documentCompletionTreeStructure({ projectId: currentProject.value?.id, pid: state.parentPid }).then((res: any) => {
        loading.close();
        if (res.code == 200) {
          state.fileList = res.data || [];
          if (state.fileList.length) {
            state.fileList.map((item) => {
              return {
                ...item,
                checkbox: false
              };
            });
          }
        }
      });
    };
    const handleFile = (type) => {
      state.fileType = type;
      if (type == 3) {
        // 新建文件夹
        ElMessageBox.prompt('填写文件夹名', '新建文件夹', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        })
          .then(({ value }) => {
            // pid 父级
            newFolder({ fileName: value, pid: state.parentPid == '0' ? '' : state.parentPid, projectId: state.projectId }).then((res: any) => {
              if (res.code == 200) {
                getdocumentCompletionTreeStructure();
                ElMessage({
                  type: 'success',
                  message: '添加成功'
                });
              } else {
                ElMessage({
                  type: 'error',
                  message: res.data
                });
              }
            });
          })
          .catch(() => {});
      } else {
        // 竣工图
        proxy.mittBus.emit('bigUploader.uploadFile', { type: 100, types: 1010, accept: [] });
      }
      return;
    };
    // 页面跳转
    const onNav = (item) => {
      // 通过后缀判断该文件是什么类型
      // 图片格式 jpg、png、jpeg、
      // word文档格式:docx、doc、pdf、xls、xlsx、pptx、ppt
      // 其他全文件夹
      if (item.fileType == '3') {
        // 可以预览图片
        return;
      } else if (item.fileType == '2') {
        // 打开文件夹
        state.parentPid = item.id;
        state.breadcrumbList.push(item); //路径设置
        state.fileList = [];
        // 获取对应文件夹的数据
        getdocumentCompletionTreeStructure();
      } else {
        window.open(item.filenPathCoding, '_black');
        return;
      }
    };
    const onFileName = (item) => {
      // 修改文件名称
      ElMessageBox.prompt('文件名称修改', '重命名', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputValue: item.name
      })
        .then(({ value }) => {
          // 确定
          documentCompletionEdit({ id: item.id, name: value, type: item.type }).then((res: any) => {
            if (res.code == 200) {
              item.name = value;
              getdocumentCompletionTreeStructure();
              ElMessage({
                type: 'success',
                message: '修改成功'
              });
            } else {
              ElMessage({
                type: 'error',
                message: res.message
              });
            }
          });
        })
        .catch(() => {});
    };
    const handleClick = (val) => {
      if (state.activeName == 'second') {
        getdocumentCompletionTreeStructure();
      } else {
        RecyclingStationRef.value.getDocumentDataList();
      }
    };
    const onBreadcrumb = (item) => {
      if (item.fileName == '目录') {
        state.parentPid = '0';
        state.breadcrumbList = [{ id: 0, fileName: '目录' }]; //菜单列表
        // 最初目录
        getdocumentCompletionTreeStructure();
      } else {
        let arr = [];
        let array = state.breadcrumbList;
        for (let index = 0; index < array.length; index++) {
          arr.push(array[index]);
          if (array[index].fileName == item.fileName) {
            break;
          }
        }
        state.breadcrumbList = arr;
        // 通过 当前点击的文件进行获取数据
        // 重复点击不用再次获取
        if (item.id == state.parentPid) return;
        state.parentPid = item.id;
        getdocumentCompletionTreeStructure();
      }
    };
    // 批量操作数据
    const onBatchAll = () => {
      state.toolStart = !state.toolStart;
    };
    const setDel = (ids) => {
      let msg = '你确定要删除所选数据？';
      if (ids.length === 0) {
        ElMessage.error('请选择要删除的数据。');
        return;
      }
      ElMessageBox.confirm(msg, '温馨提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(ids);

          documentCompletionDelete(ids).then((res) => {
            if (res.code == 200) {
              let box = document.getElementById('right_box');
              box.style.display = 'none'; //显示div盒子
              ElMessage.success('删除成功');
              getdocumentCompletionTreeStructure();
            } else {
              ElMessage.error(res.msg);
            }
          });
        })
        .catch(() => {});
    };
    // 批量删除
    const onDeleteAll = () => {
      //获取所有已经选中的数据
      let selectList = [];
      if (state.fileList.length) {
        state.fileList.map((item) => {
          if (item.checkbox) {
            selectList.push(item.id);
          }
        });
        if (!selectList.length) {
          ElMessage.warning('请选择需要删除的文件');
          return;
        }
        setDel(selectList);
      }
    };
    // 批量选择
    const onToolAll = (row) => {
      row.checkbox = !row.checkbox;
    };
    const onContextmenu = (event, item, i) => {
      state.typeFile = item.fileType;
      state.relativePath = item.filenPath;
      state.delId = item.id;
      let len = (100 / 12) * (i % 12) + 4 + '%';
      let box = document.getElementById('right_box');
      box.style.top = event.clientY - 250 + 'px'; //鼠标点击时给div定位Y轴
      box.style.left = len; //鼠标点击时给div定位X轴
      box.style.display = 'block'; //显示div盒子
    };
    return {
      proxy,
      handleFile,
      onFileName,
      onNav,
      handleClick,
      RecyclingStationRef,
      onBreadcrumb,
      onBatchAll,
      onDeleteAll,
      onExport,
      onDeleteFile,
      onToolAll,
      onContextmenu,
      ...toRefs(state)
    };
  }
});
</script>
<style lang="scss">
.documentCompletion-data {
  .el-card__body {
    padding: 10px !important;
  }

  .breadcrumb-img {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    padding-right: 10px;
    .tool-All {
      display: flex;
      align-items: center;
      > div {
        display: flex;
        align-items: center;
      }
    }
    .batch {
      width: 24px;
    }
  }
  .file_detail {
    position: relative;
    width: 100%;
    height: 66vh;
    overflow: auto;
    .right_box {
      position: absolute;
      z-index: 999;
      background-color: rgb(0 0 0 / 56%);
      width: 120px;
      height: 100px;
      top: 0;
      left: 0;
      display: none;
      border-radius: 6px;
      padding: 14px 4px;
      > div {
        font-size: 16px;
        font-weight: bold;
        color: #fff;
        padding: 8px 20px;
        cursor: pointer;
        font-family: revert;
        border-radius: 5px;
      }
      > div:hover {
        background-color: rgb(0 0 0 / 80%);
      }
    }
    .file_style {
      // height: 100px;
      width: 90px;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 10px;
      box-sizing: border-box;
      animation: 0.5s ease;
      position: relative;
      margin-bottom: 10px;
      > div {
        width: 100%;
        // height: 70%;
        height: 80px;
        > img {
          width: 100%;
          height: 100%;
        }
      }
      .checkbox-box {
        position: absolute;
        top: -8px;
        left: 60px;
        z-index: 1000;
      }
      > span {
        font-size: 12px;
        width: 100%;
        display: block;
        text-align: center;
        // display: flex;
        // align-items: center;
        // justify-content: center;
        word-wrap: break-word;
      }
    }
    .file_style:hover {
      background-color: rgba(189, 189, 189, 0.322);
      border-radius: 5px;
    }
    .fileActive {
      display: block;
      top: 0;
      position: absolute;
      z-index: 999;
      left: 0;
      width: 100%;
      height: 100% !important;
      border-radius: 5px;
      background-color: rgba(189, 189, 189, 0.322);
    }
  }
}
.colBlock {
  display: block;
}
.colNone {
  display: none;
}
</style>
