<template>
  <div class="index-content">
    <div class="header">
      <Navbar :title="title" @leftclick="goback" class="selectNavBar"></Navbar>
    </div>
    <div class="content">
      <sort-header> </sort-header>
      <div class="fileList">
        <list
          ref="list"
          :fileData="fileListData"
          v-if="store.getters.listType === 'list'"
        >
        </list>
        <thumb v-else ref="list" :fileData="fileListData" > </thumb>
      </div>
      <div class="footer" :class="{ isDropOpen: isDropOpen }">
        <div class="footerLeft">
          <img
            src="@/assets/selectedFold.png"
            alt=""
            v-if="!store.getters.selectList.length && !isDropOpen"
          />
          <van-badge :content="store.getters.selectList.length" v-else>
            <img src="@/assets/selectedFoldActive.png" alt="" />
          </van-badge>
          <van-dropdown-menu
            class="footerLeftDropDown"
            active-color="#000"
            direction="up"
            v-if="store.getters.selectList.length||isDropOpen"
          >
            <van-dropdown-item
              @open="dropdownOpen"
              @close="isDropOpen = false"
              ref="dropdownItem"
            >
              <p class="title">已选：{{ store.getters.curDiskName }}
                 <span class="close" @click="closeDropdown">
                     <img src="@/assets/close.png" alt="" />
                </span></p>
              <van-checkbox-group v-model="checked" :max="6">
                <div
                  v-for="(item, index) in selectItemList"
                  :key="index"
                  class="listItem hoverP"
                  @click="changeSelect(item)"
                >
                  <div class="listItemLeft">
                     <img
                        class="img-icon hoverP"
                        :src="checked.includes(item.path) ? activeIcon : inactiveIcon"
                      />
                    <!-- <van-checkbox :name="item.path" checked-color="#f68484" @click.stop>
                      <template #icon="props">
                        <img
                          class="img-icon"
                          :src="props.checked ? activeIcon : inactiveIcon"
                        />
                      </template>
                    </van-checkbox> -->
                  </div>
                  <div class="listItemRight">
                    <div class="left">
                      <img src="@/assets/fold_sm.png" alt="" />
                    </div>
                    <div class="right">
                      <p class="name">{{ ellipsis(item.name, 30) }}</p>
                      <p class="date">
                        {{ shareDateFormat(item.mtime, 0, "YYYY/MM/DD") }}
                        <i class="time">{{
                          shareDateFormat(item.mtime, 0, "HH:mm")
                        }}</i>
                      </p>
                    </div>
                  </div>
                </div>
              </van-checkbox-group>
            </van-dropdown-item>
          </van-dropdown-menu>
        </div>
        <van-button
          type="primary"
          class="footerRight hoverP"
          :class="{ active: store.getters.selectList.length||loading,disabled: !store.getters.selectList.length}"
          @click="scan"
          :loading="loading"
          :loading-text="'文件添加中……'"
          >扫描去重</van-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, onMounted, onBeforeUnmount, toRefs, computed,ref,watch } from "vue";
import Navbar from "@/components/Navbar";
import sortHeader from "./components/head";
import list from "./components/filelist.vue";
import thumb from "./components/thumb";
import Cookies from "js-cookie";
import { useRouter } from "vue-router";
import { toastmes } from "@/utils/index";
import { Dialog } from "vant";
import { useStore } from "vuex";
import { ellipsis, shareDateFormat } from "@/utils/index";
import { addFiles, getStatus, getUserbyUserId } from "@/api/fileDeduplication";
export default {
  name: "selectFile",
  components: {
    Navbar,
    sortHeader,
    list,
    thumb,
  },

  setup(props, context) {
    const store = useStore();
   const dropdownItem = ref(null)
   const list = ref(null)
    const state = reactive({
      store,
      title:'选择文件',
      loading:false,
      isDropOpen: false,
      activeIcon: require("@/assets/selected.svg"),
      inactiveIcon: require("@/assets/un-select.svg"),
      shareDateFormat,
      selectItemList: store.getters.selectItemList, //已选中的文件夹的集合
      ellipsis,
      closeDropdown(){
         dropdownItem.value.toggle();
      },
      dropdownOpen() {
        state.isDropOpen = true;
        state.selectItemList = store.getters.selectItemList;
      },
      changeSelect(item){
        list.value.checkboxClick(item);
      },
      async scan() {
        if(!store.getters.selectList.length){
          return false
        }
        state.loading = true
        const statusRes = await getStatus({ kid: Cookies.get("kid") });
        if (statusRes.error_code !== 0) {
          toastmes(statusRes.error_msg, "fail");
        }
        // 0：空闲状态；1：处理状态；2：获取结果状态；3：错误状态；4：被占用状态
        if (statusRes.data.status===4) {
           await getUserbyUserId({ serverUserId: statusRes.data.userId }).then((res1) => {
              Dialog.alert({
                title: "提示",
                message: `“${res1.data.nickName}”正在进行文件去重操作，同一时间，仅支持一个去重任务。`,
                confirmButtonText: "我知道了",
              }).then(() => {
                // on close
              });
            });
            return 
        }
        let res = await addFiles({
          kid: Cookies.get("kid"),
          pathList: store.getters.selectList,
        });
        state.loading = false
        const { error_msg, error_code } = res;
        if (error_code !== 0) {
          toastmes(error_msg, "fail");
          return;
        }
        router.push({ path: "scan" });
      },
    });
    const router = useRouter();
    // 手势返回处理
    onMounted(() => {
      if (window.history && window.history.pushState) {
        history.pushState(null, null, document.URL);
        window.addEventListener("popstate", goback, false); //false阻止默认事件
      }
    });
    onBeforeUnmount(() => {
      window.removeEventListener("popstate", goback, false); //false阻止默认事件
    });
    const goback = () => {
      let pathList = store.getters.pathList.slice(0);
      if ([1,0].includes(pathList.length)) {
        router.push({ path: "index",query:{reGetStatus:1} });
      } else {
        if(pathList.length===2){
          store.commit("selectFile/SET_CUR_DISPLAY_NAME", []);
        }else{
          let list = curDisplayName.value.slice(0)
          list.pop()
          store.commit("selectFile/SET_CUR_DISPLAY_NAME", [...list]);
        }
       
        history.pushState(null, null, document.URL);
        const path = pathList[pathList.length - 2];
        store.commit("selectFile/SET_PATH", path);
        pathList.pop();
        store.commit("selectFile/SET_PATH_LIST", pathList);
        store.commit("selectFile/SET_FINISHED", false);
        store.commit("selectFile/SET_OFFSET", 0);
        const res = store.dispatch("selectFile/GET_FILE_LIST", {
          offset: 0,
          path: path,
        });
      }
    };
    // 磁盘空间列表数据
    const fileListData = computed(() => {
      return store.getters.fileListData;
    });
      // 当前展示路径
    const curDisplayName = computed(() => {
      return store.getters.curDisplayName;
    });
    // 当前展示路径
    watch(
      () => store.getters.curDisplayName,
      (newValue, oldValue) => {
        if(!newValue.length){
          state.title =  '选择文件'
        }else{
          let name =  newValue[newValue.length-1]
          if (!name) state.title = ''
          if (name.length>15) {
              state.title = name.replace(name.slice(5, name.length-10),'...')  
          }else{
            state.title = newValue[newValue.length-1]
          }
        }
      },
      { deep: true }
    );
    // 已选中的path的集合
    const checked = computed({
      get() {
        return store.getters.selectList;
      },
      set(value) {
        store.commit("selectFile/SET_SELECT_LIST", value);
      },
    });
    return {
      goback,
      ...toRefs(state),
      fileListData,
      dropdownItem,
      list,
      checked,
      curDisplayName
    };
  },
};
</script>

<style lang="less" scoped>
.index-content {
  .fileList {
    height: calc(
      100vh - 57px - 44px - 88px
    ); //屏幕高度 - 导航栏高度 - 排序固定栏高度 - 底部
    overflow-y: scroll;
    overflow-x: hidden;
     &::-webkit-scrollbar {
      display: none;
    }
  }
  .selectNavBar{
     :deep(.van-nav-bar__title) {
       max-width: 80%;
     text-overflow: unset;
    }
  }
  .footer {
    width: 100%;
    height: 88px;
    box-sizing: border-box;
    display: flex;
    padding: 10px 54px 0 54px;
    background: linear-gradient(
      180deg,
      rgba(255, 255, 255, 0.8) 0%,
      #ffffff 100%
    );
    box-shadow: 0px 0px 32px 0px rgba(218, 41, 28, 0.2);
    border-radius: 32px 32px 0px 0px;
    &.isDropOpen {
      background: #fafafa;
      box-shadow: none;
      border: none;
      .footerRight {
        box-shadow: none;
      }
    }
    .footerLeft {
      width: 24px;
      height: 24px;
      margin-right: 20px;
      margin-top: 7px;
      position: relative;
      .footerLeftDropDown {
        position: absolute;
        width: 24px;
        height: 24px;
        top: 0;
        left: 0;
        z-index: 1;
        :deep(.van-dropdown-menu__item),
        :deep(.van-dropdown-menu__bar) {
          width: 24px;
          height: 24px;
          opacity: 0;
        }
        :deep(.van-dropdown-item) {
          bottom: 88px !important;
        }
        :deep(.van-dropdown-item__content) {
          background: #fafafa;
          border-radius: 16px 16px 0px 0px;
          padding: 15px 0 15px 15px;
        }
        .title {
          font-size: 15px;
          font-weight: 500;
          color: #303133;
          line-height: 22px;
          margin-bottom: 15px;
          position: relative;
          .close{
            width: 18px;
            height: 18px;
            position: absolute;
            right: 20px;
            top: 2px;
            cursor: pointer;
          }
        }
        .listItem {
          display: flex;
          min-height: 68px;
          margin-bottom: 10px;
          .listItemLeft {
            width: 21PX;
            height: 68PX;
            padding: 26px 5px 26px 0px ;
            box-sizing: border-box;
            .img-icon {
              width: 16PX;
              height: 16PX;
            }
          }
          .listItemRight {
            flex: 1;
            display: flex;
            background: #ffffff;
            border-radius: 8px;
            padding: 12px 0 12px 15px;
            box-sizing: border-box;
            .left {
              width: 20px;
              height: 20px;
              margin-top: 12px;
              margin-right: 20px;
            }
            .right {
              flex: 1;
              .name {
                font-size: 13px;
                color: #303133;
                line-height: 20px;
                margin-bottom: 8px;
              }
              .date {
                font-size: 11px;
                color: #909399;
                line-height: 16px;
              }
            }
          }
        }
      }
    }
    .footerRight {
      width: 223px;
      height: 38px;
      background: #d0d0ce;
      border-radius: 12px;
      font-size: 13px;
      color: #303133;
      line-height: 20px;
      text-shadow: 0px 0px 32px rgba(218, 41, 28, 0.2);
      &.active {
        background: linear-gradient(135deg, #ef8881 0%, #da291c 100%);
        color: #ffffff;
      }
    }
  }
}
</style>
