<template>
  <div class="container" v-if="!showPreview">
    <div class="statistics">
      <div class="left_box">
        <div class="dataNum">共查询到个相关结果</div>
      </div>
      <div class="right_box">
        <img
          src="@/assets/images/sort.png"
          @click="changeSort"
          v-if="isAsc == 'asc'"
          alt=""
        />
        <img
          src="@/assets/images/Frame_188.png"
          @click="changeSort"
          v-else
          alt=""
        />
        <img
          v-if="isList"
          src="@/assets/images/squre.png"
          alt=""
          @click="changeShow"
        />
        <img
          v-else
          src="@/assets/images/Frame_187.png"
          alt=""
          @click="changeShow"
        />
      </div>
    </div>
    <!-- 标签 -->
    <div class="tags">
      <!-- TODO 标签可以拖动位置 -->
      <!-- 
      <el-tabs v-if="false" v-model="clickCollect" class="demo-tabs tabSign">
        <el-tab-pane label="常用" name="first"></el-tab-pane>
        <el-tab-pane label="默认" name="second"></el-tab-pane>
        <draggable
          :list="toRaw(tabList)"
          ghost-class="ghost"
          chosen-class="chosenClass"
          animation="300"
        >
          <template #item="{ element }">
            <el-tab-pane>
              <template #label>
                <div
                  v-if="isChangeTabName !== element.labelId"
                  @click.right="tabClick($event, element)"
                >
                  {{ element.labelName }}
                </div>
                <div v-else>
                  <el-input
                    v-model="changeTabName"
                    size="mini"
                    @blur="reTabName"
                    maxlength="32"
                    :autofocus="true"
                  ></el-input>
                </div>
              </template>
            </el-tab-pane>
          </template>
        </draggable>
      </el-tabs> -->

      <el-tabs
        v-model="clickCollect"
        class="tabSign"
        @tab-change="tabchange"
        ref="tabs"
      >
        <!-- <el-tab-pane label="常用" name="first"></el-tab-pane> -->
        <el-tab-pane label="默认" name="second"></el-tab-pane>
        <el-tab-pane
          v-for="item in toRaw(tabList)"
          :key="item"
          :name="item.labelId"
        >
          <template #label>
            <div
              v-if="isChangeTabName !== item.labelId"
              @click.right="tabClick($event, item)"
            >
              {{ item.labelName }}
            </div>
            <div v-else>
              <el-input
                v-model="changeTabName"
                size="mini"
                @blur="reTabName"
                maxlength="32"
                :autofocus="true"
              ></el-input>
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加标签 -->
      <div class="addCollect">
        <div v-if="!isAddCollect">
          <el-icon color="#2E6BC8">
            <Plus />
          </el-icon>
          <span @click="toAddCollectFn">添加标签</span>
        </div>
        <div v-else>
          <el-input
            v-model="tabName"
            size="mini"
            @change="addCollectFn"
            maxlength="32"
            :autofocus="true"
          ></el-input>
        </div>
      </div>
    </div>
    <el-collapse v-model="activeNames">
      <div v-if="isList">
        <el-collapse-item name="folder">
          <template #title>
            <span class="collapseItem_title">文件夹</span>
          </template>
          <!-- 表格 -->
          <el-table
            :data="folderArr"
            style="width: 100%"
            height="250"
            :scrollbar-always-on="true"
            @row-contextmenu="fileRightTable"
          >
            <el-table-column fixed prop="date" label="名称" width="500">
              <template #default="scope">
                <div class="folderName">
                  <img
                    class="table_icon"
                    src="@/assets/images/fileBox.png"
                    alt=""
                    style=""
                  />
                  <span class="shouzhi">{{ scope.row.docDir.dirName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              prop="docDir.createTime"
              label="时间"
              width="200"
            />
            <el-table-column prop="docInfo.fileType" label="类型" width="180">
              <!-- <template #default="scope"> -->
              <div>文件夹</div>
              <!-- </template> -->
            </el-table-column>
          </el-table>
        </el-collapse-item>
        <el-collapse-item name="file">
          <template #title>
            <span class="collapseItem_title">文件</span>
          </template>
          <!-- 表格 -->
          <el-table
            :data="fileArr"
            style="width: 100%"
            height="250"
            :scrollbar-always-on="true"
            @row-contextmenu="fileRightTable"
          >
            <el-table-column fixed prop="date" label="名称" width="500">
              <template #default="scope">
                <div class="fileName">
                  <img
                    class="table_icon"
                    :src="setIcon(scope.row.docInfo.fileType)"
                    alt=""
                    style=""
                  />
                <span class="shouzhi"> {{ scope.row.docInfo.fileName }}</span>  
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="时间" width="200" />
            <el-table-column prop="docInfo.fileType" label="类型" width="180" />
            <el-table-column prop="docInfo.fileSize" label="大小" width="160">
              <template #default="scope">
                <div>{{ scope.row.docInfo.fileSize }} KB</div>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </div>
      <div v-else>
        <el-collapse-item name="folder">
          <template #title>
            <span class="collapseItem_title">文件夹</span>
          </template>
          <!-- 平铺 -->
          <el-scrollbar style="height: 37vh;">
            <div class="tile_box">
              <div
                class="file_box"
                @click.right="fileRight($event, item)"
                v-for="item in folderArr"
                :key="item"
              >
                <img
                  class="big_file_img"
                  src="@/assets/images/fileBox.png"
                  alt=""
                />
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.docDir.dirName"
                  placement="top"
                >
                  <span>{{ item.docDir.dirName }}</span>
                </el-tooltip>
              </div>
            </div>
          </el-scrollbar>
        </el-collapse-item>
        <el-collapse-item name="file">
          <template #title>
            <span class="collapseItem_title">文件</span>
          </template>
          <!-- 平铺 -->
          <el-scrollbar style="height: 37vh;">
            <div class="tile_box">
              <div
                class="file_box"
                @click.right="fileRight($event, item)"
                v-for="item in fileArr"
                :key="item"
              >
                <img
                  class="big_file_img"
                  :src="setIcon(item.docInfo.fileType)"
                  alt=""
                />
                <el-tooltip
                  class="box-item"
                  effect="dark"
                  :content="item.docInfo.fileName"
                  placement="top"
                >
                  <span>{{ item.docInfo.fileName }}</span>
                </el-tooltip>
              </div>
            </div>
          </el-scrollbar>
        </el-collapse-item>
      </div>
    </el-collapse>
  </div>
  <!-- 右键唤出的菜单 -->
  <!-- TODO 默认就是不搜索标签 -->
  <div
    class="right_menu shouzhi"
    v-if="visible"
    :style="{ left: left + 'px', top: top + 'px',margin:'0' }"
  >
    <div class="menu_item" @click="reName">
      <img src="@/assets/images/textbox.png" alt="" />
      <span>重命名</span>
    </div>
    <div class="menu_item" @click="delTabs">
      <img src="@/assets/images/trash.png" alt="" />
      <span>删除</span>
    </div>
  </div>
  <div v-else class="preview">
    <!-- TODO 预览功能后续实现-->
    <!-- <FileEdit
      :docId="thisRData.docInfo.docId"
      :copyRow="thisRData"
      :historyPrew="historyPrew"
      :historycopyRow="historycopyRow"
      :onlyView="onlyView"
    ></FileEdit> -->
  </div>
  <RightMenu v-if="showFlieRM" :fileRightXY="fileRightXY"></RightMenu>
</template>

<script setup>
import Sortable from "sortablejs";
// import { setIcon } from "@/utils/index.js";
import draggable from "vuedraggable";
import FileEdit from "@/views/myfile/components/FileEdit.vue";
import { onMounted, ref, watch, nextTick } from "vue";
import { toRaw } from "@vue/reactivity";
import {
  listLabel,
  addLabel,
  delLabel,
  updateLabel,
  sortLabel,
} from "@/api/biz/label.js";
import { listFavorite, listFavoriteById } from "@/api/biz/favorite.js";
import RightMenu from "@/components/RightMenu/index.vue";
const activeNames = ref(["folder", "file"]);
const clickCollect = ref("second"); //当前标签
const isAddCollect = ref(false); //是否在添加标签
const tabName = ref(""); //新增的标签名
const changeTabName = ref(""); //修改的标签名
const tabList = ref([]);
const isAsc = ref("asc");
const tableData = [];
const visible = ref(false); //显示右键菜单
const top = ref(0);
const left = ref(0);
const thisTab = ref({}); //当前右键的标签
const isChangeTabName = ref(0); //存放修改状标签的id
const folderArr = ref(); //文件夹数组
const fileArr = ref(); //文件数组
const isList = ref(false); //控制显示方式
const showPreview = ref(false); //预览
const fileRightXY = ref({}); //右键菜单坐标
const showFlieRM = ref(false); //右键菜单显示
const thisRData = ref(); //当前右键的文件
//----引入图片----
import file_DOC from "../../assets/images/fileType/file_DOC.png";
import file_pdf from "../../assets/images/fileType/file_pdf.png";
import file_PPT from "../../assets/images/fileType/file_PPT.png";
import file_TXT from "../../assets/images/fileType/file_TXT.png";
import file_XLSX from "../../assets/images/fileType/file_XLSX.png";
import file_pic from "../../assets/images/fileType/file_pic.png";
import file_audio from "../../assets/images/fileType/file_audio.png";
import file_video from "../../assets/images/fileType/file_video.png";
import file_zip from "../../assets/images/fileType/file_zip.png";
// -------
onMounted(async () => {
  await getList();
  await getCollectList();
  await tabchange('second')
  // rowDrop();
  // 添加监听，点击其他地方关闭菜单
  window.addEventListener("click", closeMenu, true);
  window.addEventListener("click", closeFlieRMenu, true);
});
// tab右键事件
const tabClick = (e, item) => {
  e.preventDefault();
  e.stopPropagation();
  // console.log("e", e);
  // console.log("item", toRaw(item));
  thisTab.value = item;
  //  唤出右键菜单，思路：获取鼠标位置来定位菜单
  visible.value = true;
  top.value = e.pageY;
  left.value = e.pageX;
};
// file右键事件
const fileRight = (e, item) => {
  e.preventDefault();
  e.stopPropagation();
  // console.log("e", e);
  // console.log("item", toRaw(item));
  //  唤出右键菜单，思路：获取鼠标位置来定位菜单
  thisRData.value = item;
  console.log("thisRData", thisRData.value);
  showFlieRM.value = true;
  fileRightXY.value.top = e.pageY;
  fileRightXY.value.left = e.pageX;
};
// folder右键事件
const fileRightTable = (item, col, e) => {
  e.preventDefault();
  e.stopPropagation();
  // console.log("e", e);
  // console.log("item", toRaw(item));
  //  唤出右键菜单，思路：获取鼠标位置来定位菜单
  thisRData.value = item;
  console.log("thisRData", thisRData.value);
  showFlieRM.value = true;
  fileRightXY.value.top = e.pageY;
  fileRightXY.value.left = e.pageX;
};
// 关闭右键菜单
const closeMenu = () => {
  // console.log("close");
  visible.value = false;
};
// 关闭右键菜单
const closeFlieRMenu = () => {
  // console.log("close");
  showFlieRM.value = false;
};
//添加标签
const toAddCollectFn = async () => {
  isAddCollect.value = true;
};
const addCollectFn = async () => {
  if (!tabName.value) {
    isAddCollect.value = false;
    return;
  }

  const list = toRaw(tabList.value);
  let order = 0;
  if (list.length > 0) {
    order = getBigOrder(list);
  }

  const res = await addLabel({
    labelName: tabName.value,
    orderNum: order,
  });
  if (res.code == 200) {
    isAddCollect.value = false;
    tabName.value = "";
    getList();
  }
};
//获取标签数据
const getList = async () => {
  const res = await listLabel();
  console.log("tabList =", res);
  if (res.rows.length > 0) {
    let dates = JSON.parse(JSON.stringify(res.rows));
    dates.sort(sortArr("orderNum"));
    tabList.value = [...dates];
    // console.log("tabList", tabList.value);
    // console.log("dates", dates);
  }
};
// 删除标签
const delTabs = async () => {
  let tabDetail = toRaw(thisTab.value);
  const res = await delLabel(tabDetail.labelId); //直接传id
  // console.log("delres = ", res);
  getList();
};
// TODO 按标签获取收藏数据，实现文件夹收藏功能，文件夹右键菜单和文件右键菜单样式统一
//获取收藏数据
const getCollectList = async () => {
  const res = await listFavorite();
  console.log("collectres = ", res);
  if (res.code === 200 && res.rows.length > 0) {
    tableData.value = res.rows;
  }
};
// 修改便签名
const reName = async () => {
  console.log("thisTab", toRaw(thisTab.value));
  let tabDetail = toRaw(thisTab.value);
  changeTabName.value = tabDetail.labelName;
  isChangeTabName.value = tabDetail.labelId;
};
const reTabName = async () => {
  let tabDetail = toRaw(thisTab.value);
  const res = await updateLabel({
    labelId: tabDetail.labelId,
    labelName: changeTabName.value,
  });
  await getList();
  isChangeTabName.value = 0;
  console.log("rename", res);
};
//拖拽事件
// const rowDrop = () => {
//   const el = document.querySelector(".tabSign .el-tabs__nav"); //找到想要拖拽的那一列
//   // console.log('el',el);
//   const _this = toRaw(JSON.parse(JSON.stringify(tabList.value))); //否则下面遍历会出错
//   // console.log("_this", _this);
//   Sortable.create(el, {
//     filter: "#tab-first,#tab-second", //限制哪些可以拖动
//     preventOnFilter: true,
//     onChoose: function (/**Event*/ evt) {
//       evt.oldIndex;
//       // console.log("evt", evt);
//     },
//     //结束拖拽事件
//     async onEnd({ newIndex, oldIndex, to }) {
//       //拿到交换前后对应的index
//       const ni = newIndex - 3;
//       const oi = oldIndex - 3;
//       let list = toRaw(tabList.value);
//       list = list.filter((item) => item); //筛除空数据
//       console.log("list", list);
//       console.log("newIndex", ni);
//       console.log("oldIndex", oi);
//       const newList = list.map((item, index) => {
//         console.log("item", item);
//         if (oi > ni) {
//           // 从后往前，需要将oi和ni之间的+1
//           if (index === oi) {
//             item.orderNum = _this[ni].orderNum;
//             // console.log("oiitem", item);
//           } else if (ni < index < oi) {
//             item.orderNum += 1;
//           }
//         } else if (oi < ni) {
//           // 从前往后，需要将oi和ni之间的-1
//           if (index === oi) {
//             item.orderNum = _this[ni].orderNum;
//             // console.log("oiitem", item);
//           } else if (oi < index < ni) {
//             item.orderNum -= 1;
//           }
//         }

//         return item;
//       });
//       console.log("newList", newList);

//       const res = await sortLabel(newList);
//       console.log("res", res);
//       await getList();
//     },
//   });
// };

const tabchange = async (labelId) => {
  console.log("labelId", toRaw(labelId));
  const query = {
    labelId,
    isAsc: isAsc.value,
    orderByColumn: "createTime",
  };
  let res;
  if (labelId === "second") {
    res = await listFavoriteById(-1);
    console.log("res", res);
    // return;
  } else {
    // 获取当前标签下的数据
    res = await listFavoriteById(labelId);
  }

  // console.log("----res", res);
  folderArr.value = res.filter((item) => item.isFolder === "Y");
  fileArr.value = res.filter((item) => item.isFolder === "N");
  console.log("folderArr", folderArr.value);
  console.log("fileArr", fileArr.value);
};
const changeShow = () => {
  isList.value = !isList.value;
};
const changeSort = async () => {
  isAsc.value == "asc" ? (isAsc.value = "desc") : (isAsc.value = "asc");
  // console.log("res", res);
};

// 工具函数
//获取新增标签时要赋予的ordername
const getBigOrder = (arr) => {
  let num = 0;
  arr.forEach((item) => {
    if (item.orderNum > num) {
      num = item.orderNum;
    }
  });
  return num + 1;
};
//数组排序
const sortArr = (field) => {
  return function (a, b) {
    return a[field] - b[field];
  };
};

const setIcon = (fileType) => {
  switch (fileType) {
    case ".docx":
      return file_DOC;
      break;
    case ".pdf":
      return file_pdf;
      break;
    case ".ppt":
      return file_PPT;
      break;
    case ".txt":
      return file_TXT;
      break;
    case ".xlsx":
      return file_XLSX;
      break;
    case ".csv":
      return file_XLSX;
      break;
    case ".png":
      return file_pic;
      break;
    case ".mp3":
      return file_audio;
      break;
    case ".mp4":
      return file_video;
      break;
    case ".zip":
      return file_zip;
      break;
    default:
      return file_DOC;
      break;
  }
};
</script>

<style lang="scss" scoped>
@import "@/assets/styles/my-common.scss";
.shouzhi {
  margin-left: 5px;
}
.container {
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  .statistics {
    width: 100%;
    height: 40px;
    background-color: #d9e0f0;
    padding-left: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #6f85b5;
    .left_box {
      display: flex;
      align-items: center;
      .dataNum {
        margin-left: 4px;
        font-size: 14px;
        font-weight: 400;
      }
    }
    .right_box {
      width: 50px;
      display: flex;
      justify-content: space-between;
      margin-right: 30px;
      img {
        cursor: pointer;
      }
    }
  }
  .tags {
    display: flex;
    width: 100%;
    height: 40px;
    box-sizing: border-box;
    border-top: 1px solid #c1cce3;
    border-bottom: 1px solid #c1cce3;
    background-color: #f5f7f9;
  }
  .addCollect {
    margin-left: 16px;
    cursor: pointer;
    height: 100%;
    line-height: 40px;
    font-size: 14px;
    color: #2e6bc8;
    font-weight: 400;
    vertical-align: middle;
  }
}
.right_menu {
  width: 100px;
  position: absolute;
  padding: 8px;
  box-shadow: 0px 2px 10px 1px rgba(199, 203, 216);
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #c1cce3;
  background-color: #fff;
  z-index: 10000;
  .menu_item {
    width: 100%;
    height: 40px;
    border-radius: 4px 4px 4px 4px;
    display: flex;
    align-items: center;
    &:hover {
      background-color: #f5f7f9;
    }
    span {
      margin-left: 4px;
    }
  }
}

// tag间距
::v-deep .el-tabs__item {
  padding: 0 16px !important;
  color: #505870 !important;
  font-weight: 400 !important;
}
::v-deep .el-tabs--top .el-tabs__item.is-top:last-child {
  padding-right: 0 !important;
}
// tag选中颜色
::v-deep .el-tabs__item.is-active {
  color: #2e6bc8 !important;
  font-weight: normal;
  font-family: Inter-SemiBold;
}
::v-deep .el-tabs__active-bar {
  background-color: #2e6bc8;
}

.table_icon {
  height: 27px;
  width: 27px;
  vertical-align: middle;
}
::v-deep .el-collapse-item__content {
  padding-bottom: 0;
}
::v-deep .el-collapse-item__header {
  background-color: #ebeff6 !important;
  width: 100% !important;
  height: 24px !important;
}
::v-deep .el-collapse-item__arrow {
  position: relative;
  color: #2e6bc8;
  right: 97%;
}
::v-deep .el-table td.el-table__cell {
  border: none;
  font-size: 14px !important;
  font-weight: 400 !important;
  color: #000 !important;
}
::v-deep .el-table__row {
  height: 35px !important;
}
::v-deep .el-table .el-table__header-wrapper th {
  border-bottom: none;
  border-right: 1px solid #c1cce3;
  background-color: #fff !important;
  color: #505870;
  font-size: 14px;
}
.collapseItem_title {
  position: relative;
  left: 60px;
  color: #2e6bc8;
  font-family: Inter-Medium;
  font-size: 12px;
}
// 表格右边3个靠右对齐
::v-deep .el-table__header thead tr th {
  font-family: Inter-Medium;
  font-size: 14px;
  color: #505870;
  text-align: right;
  &:nth-child(1) {
    text-align: left;
  }
}
::v-deep .el-table__body tbody [class*="column_"] {
  text-align: right;
  &:nth-child(4n + 1) {
    text-align: left;
  }
}

//表格文本超出隐藏
:deep(.fileName) {
  /*第一步： 溢出隐藏 */
  overflow: hidden;
  /* 第二步：让文本不会换行， 在同一行继续 */
  white-space: nowrap;
  /* 第三步：用省略号来代表未显示完的文本 */
  text-overflow: ellipsis;
}
//表格文本超出隐藏
:deep(.folderName) {
  /*第一步： 溢出隐藏 */
  overflow: hidden;
  /* 第二步：让文本不会换行， 在同一行继续 */
  white-space: nowrap;
  /* 第三步：用省略号来代表未显示完的文本 */
  text-overflow: ellipsis;
}
//平铺
.tile_box {
  width: 100%;
  height: 300px;
  display: flex;
  flex-wrap: wrap;
  .file_box {
    width: 116px;
    min-height: 138px;
    // border: 1px solid #000;
    display: flex;
    flex-direction: column;
    align-items: center;
    .big_file_img {
      width: 100px;
      height: 100px;
    }
    span {
      width: 100%;
      text-align: center;
      font-size: 14px;
      font-weight: 400;
      line-height: 22px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      text-overflow: ellipsis;
      -webkit-line-clamp: 2; //例如超过3行显示省略号
      overflow: hidden;
    }
  }
}
</style>