<template>
  <div class="scan-content">
    <div class="header">
      <Navbar :title="'文件去重'" @leftclick="goback"></Navbar>
    </div>
    <div class="content">
      <!-- 扫描中 -->
      <div class="scanning statusItem" v-if="data.status === 1">
        <van-circle
          v-model:current-rate="currentRate"
          :rate="data.progress"
          :speed="100"
          layer-color="rgba(0, 0, 0, 0.02)"
          color="#67C23A"
          size="11.6875rem"
          :stroke-width="30"
          :text="text"
        />
        <p class="tips">
          正在扫描已选中的文件<br />
          不要走开<span class="loadingState">{{loadingState}}</span>
        </p>
        <van-button type="primary" class="whiteBtn cancel hoverP" @click="cancel"
          >取消扫描</van-button
        >
      </div>
       <!-- 扫描失败 -->
      <div class="fail statusItem" v-if="data.status === 3">
        <van-circle
          v-model:current-rate="currentRate"
          :rate="data.progress"
          :speed="100"
          layer-color="rgba(0, 0, 0, 0.02)"
          color="#F56C6C"
          size="11.6875rem"
          :stroke-width="30"
          :text="text"
        >
        <div class="failImg">
            <img
            src="@/assets/scanFail.png"
          />
        </div>
        </van-circle>
        <p class="tips">
          <p class="top">扫描查重失败</p>
          <p class="bottom"> 查重进度获取失败</p>
         
        </p>
        <van-button type="primary" class="normalBtn hoverP" @click="reStart"
          >重新扫描</van-button
        >
      </div>
       <!-- 扫描成功 -->
      <div class="fail statusItem"  v-if="data.status === 2">
        <van-circle
          v-model:current-rate="successRate"
          :rate="100"
          :speed="100"
          layer-color="rgba(0, 0, 0, 0.02)"
          color="#67C23A"
          size="11.6875rem"
          :stroke-width="30"
          :text="text"
        >
        <div class="successImg">
            <img
            src="@/assets/scanSuccess.png"
          />
        </div>
        </van-circle>
        <div v-if="data.totalCount=== 0" class="buttomBox">
           <p class="tips">
            <p class="top">扫描查重成功</p>
            <p class="bottom"> 当前没有重复文件</p>
           </p>
            <van-button type="primary" class="whiteBtn hoverP" @click="()=>{router.push({path:'index'})}"
              >我知道了</van-button>
        </div>
        <div v-else class="buttomBox">
           <p class="tips">
            <p class="top">{{totalCount}}个重复文件</p>
            <p class="bottom"> 占用空间 {{  convertBytes(data.totalSize)}}</p>
           </p>
            <van-button type="primary" class="normalBtn hoverP" @click="goClearFiles"
              >立即清理</van-button
            >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  reactive,
  onMounted,
  onBeforeUnmount,
  toRefs,
  computed,
  ref,
} from "vue";
import { convertBytes } from "@/utils/index";
import { useRouter } from "vue-router";
import Navbar from "@/components/Navbar";
import { Dialog } from "vant";
import { toastmes } from "@/utils/index";
import Cookies from "js-cookie";
import { useStore } from "vuex";
import { getStatus, cancelTask } from "@/api/fileDeduplication";
import useFileSelect from "@/views/Scan/useFileSelect";
export default {
  name: "scan",
  components: {
    Navbar,
  },
  setup(props, context) {
    const store = useStore();
    const state = reactive({
      store,
      cancel: () => {
        cancelConfirm();
      },
      reStart: () => {
        getScanStatus();
      },
      goClearFiles() {
        let status = state.data.originalTotalCount>2000?1:2 
        router.push({ path: "clearFiles",query:{isOverSize:status} });
      },
      loadingAnimate() {
        state.loadingState =
          state.loadingState.length < 3 ? (state.loadingState += ".") : ".";
      },
      loadingState: ".",
      data: {},
      convertBytes,
    });
    const currentRate = ref(0);
    const totalCount = ref(0);
    const successRate = ref(100);
    let timer = null;
    const text = computed(() => {
      let res = null;
      if (currentRate.value) {
        res = currentRate.value.toFixed(2) + "%";
      } else {
        res = (state.data.progress || 0).toFixed(2) + "%";
      }
      return res;
    });
    // 手势返回处理
    onMounted(() => {
      if (!store.getters.rootPath) {
        store.dispatch("selectFile/GET_DISK_LIST", { justGetDisk: true }); // 获取磁盘列表
      }
      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 router = useRouter();
    const goback = () => {
      if (state.data.status === 1) {
        cancelConfirm();
      } else {
        router.push({ path: "index", query: { reGetStatus: 1 } });
      }
    };
    const cancelConfirm = () => {
      Dialog.confirm({
        title: "提示",
        message: "正在扫描中，确认要取消吗？",
        className: "scanDialog",
        confirmButtonText:'确认',
        cancelButtonText:'取消',
      }).then(() => {
        cancelTask({ kid: Cookies.get("kid") })
          .then((res) => {
            const { data, error_code } = res;
            if (error_code !== 0) {
              toastmes(res.error_msg, "fail");
              return false;
            }
            clearTimeout(timer);
            router.push({ path: "index", query: { reGetStatus: 1 } });
          })
          .catch(() => {
            state.data.status = 3;
            router.push({ path: "index", query: { reGetStatus: 1 } });
          });
      });
    };
    const getScanStatus = () => {
      getStatus({ kid: Cookies.get("kid") })
        .then((res) => {
          const { data, error_code } = res;
          if (error_code !== 0) {
            toastmes(res.error_msg, "fail");
          }
          if (data.status === 1) {
            // currentRate.value = data.progress - 0;
            clearTimeout(timer);
            timer = setTimeout(() => {
              state.loadingAnimate();
              getScanStatus();
            }, 2000);
          } else if (data.status === 3) {
            // currentRate.value = data.progress - 0;
          } else if (data.status === 2) {
            let num = 0;
            let fileSetList = [];
            state.data.progress = 100
            state.data.status = 1
            totalCount.value = data.totalCount
            if (data.fileSetList.length) {
              for (let i = 0; i < data.fileSetList.length; i++) {
                let cur = data.fileSetList[i];
                for (let j = 0; j < cur.length; j++) {
                  let childItem = cur[j];
                  num += 1;
                  if (num > 2000) {
                    break;
                  }
                  if (fileSetList[i]) {
                    fileSetList[i].push(childItem);
                  } else {
                    fileSetList[i] = [childItem];
                  }
                }
                if (num > 2000) {
                  break;
                }
              }
              data.fileSetList = fileSetList;
            }
            data.originalTotalCount = data.totalCount
            data.totalCount = data.fileSetList.length
            const { getDownLoadUrls } = useFileSelect(store);
            getDownLoadUrls(data);
          } else {
            toastmes("未查询到进行中的任务", "fail");
            router.push({ path: "index", query: { reGetStatus: 1 } });
          }
          if(data.status === 2){
             setTimeout(()=>{
              state.data = data;
            },1000)
          }else{
             state.data = data;
          }
        })
        .catch((err) => {
          state.data.status = 3;
        });
    };
    if (router.currentRoute.value.query.reGetStatus !== "1") {
      getScanStatus();
    } else {
      state.data.status = 2;
      state.data.totalCount = 0;
      totalCount.value = 0
    }

    return {
      goback,
      ...toRefs(state),
      text,
      totalCount,
      currentRate,
      successRate,
      getScanStatus,
      router,
      timer,
      cancelConfirm,
    };
  },
};
</script>

<style lang="less" scoped>
.scan-content {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  .header {
    height: 57px;
    :deep(.navbar),
    :deep(.van-nav-bar),
    :deep(.van-nav-bar__content) {
      background: rgba(0, 0, 0, 0);
    }
  }
  .content {
    flex: 1;
    overflow-y: scroll;
    padding-top: 114px;
    &::-webkit-scrollbar {
      display: none;
    }
    .statusItem {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      .buttomBox{
         display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
      .loadingState {
        display: inline-block;
        width: 1em;
        text-align: left;
      }
      .van-circle {
        display: flex;
        justify-content: center;
        align-items: center;
        .failImg {
          width: 45px;
          height: 45px;
        }
        .successImg {
          width: 57px;
          height: 42px;
        }
      }
    }
    .tips {
      margin-top: 30px;
      color: #303133;
      line-height: 22px;
      font-size: 15px;
      text-align: center;
      .top {
        font-size: 17px;
        font-weight: 500;
        color: #303133;
        line-height: 24px;
        margin-bottom: 15px;
      }
      .bottom {
        font-size: 15px;
        color: #909399;
        line-height: 22px;
        margin-bottom: 91px;
      }
    }
    .normalBtn {
      width: 130px;
      height: 50px;
      background: linear-gradient(135deg, #ef8881 0%, #da291c 100%);
      border-radius: 12px;
      font-size: 13px;
      color: #ffffff;
      line-height: 20px;
    }
    .whiteBtn {
      width: 135px;
      height: 50px;
      border-radius: 12px;
      border: 1px solid #da291c;
      font-size: 13px;
      color: #da291c;
      line-height: 20px;
      background: #fff;
      &.cancel {
        margin-top: 108px;
      }
    }
  }
}
</style>
<style lang="less">
.fileDeduplication .scanDialog {
  .van-button {
    width: 100px;
  }
  .van-dialog__cancel {
    background: #fff;
    border-radius: 12px !important;
    border: 1px solid #d0d0ce;
    color: #909399;
    font-size: 13px;
  }
  .van-dialog__confirm {
    border-radius: 12px !important;
  }
}
</style>
