<script setup lang="ts">
import { downloadFileWithResponse } from '@/utils/common-service';
import { showFailedMessage } from '@/utils/composition';
import { traduction } from '@/utils/language';
import { showElMessage, formattingTime } from '@/utils/utils';
import { onUnmounted, ref, toRefs } from 'vue';
import useStore from '@/stores';
import {
  collectProgress,
  getDownLoadFileContent,
  getGenericInfo,
  oneKeyCollect,
  sendMsg,
} from '../../services/home.service';

const props = defineProps({
  state: {
    type: String,
    required: true,
    default: () => {
      return '';
    },
  },
});
const { state } = toRefs(props);
let collectState = ref(state.value);
let collectPercent = ref(0);
let store = useStore();
const emit = defineEmits(['progressClose']);
let timeout: any = null;

init();
function init() {
  getGenericInfo().then(
    res => {
      let refreshTimeData = res.CurrentTime || formattingTime(new Date(0)).replace(/\//g, '-');
      refreshTimeData = refreshTimeData.substring(0, 16);
      refreshTimeData = refreshTimeData.replace(/-|:/g, '');
      refreshTimeData = refreshTimeData.replace(' ', '-');
      const productName = localStorage.getItem('productName')?.replace(/\s/g, '');
      const productSN = localStorage.getItem('productSN');
      const fileName =
        (productName ? productName + '_' : '') +
        (productSN ? productSN + '_' : '') +
        refreshTimeData +
        '.tar.gz';
      if (!localStorage.getItem('fileName')) {
        localStorage.setItem('fileName', fileName);
      }
      if (collectState.value !== 'init') {
        oneKeyCollect(fileName).then(
          rsp => {
            const url = rsp.data.url;
            sessionStorage.setItem('collectProgressURL', url);
            queryCollectProgress(fileName);
          },
          err => {
            const url = sessionStorage.getItem('collectProgressURL');
            if (url && err.data.error[0].code.indexOf('DuplicateExportingErr') > -1) {
              queryCollectProgress(fileName);
            } else {
              emit('progressClose');
              collectPercent.value = 0;
            }
          },
        );
      } else {
        const url = sessionStorage.getItem('collectProgressURL');
        if (url) {
          queryCollectProgress(fileName);
        } else {
          emit('progressClose');
          collectPercent.value = 0;
        }
      }
    },
    error => {
      emit('progressClose');
      collectPercent.value = 0;
    },
  );
}

function queryCollectProgress(fileName: string) {
  const url = sessionStorage.getItem('collectProgressURL') || '';
  collectProgress(url).then(
    res => {
      const taskPercentage = res.data.prepare_progress;
      const s = res.data.state;
      if (taskPercentage) {
        collectPercent.value = taskPercentage;
      }
      if (taskPercentage === 100 && s === 'Completed') {
        sessionStorage.removeItem('collectProgressURL');
        localStorage.removeItem('fileName');
        queryDownloadUrl(fileName);
      } else if (s === 'Exception') {
        sessionStorage.removeItem('collectProgressURL');
        localStorage.removeItem('fileName');
        emit('progressClose');
        const errorMessage = traduction('COMMON_FAILED');
        store.state.event.setEventState({
          type: 'alertMessage',
          value: { type: 'error', message: errorMessage },
        });
      } else {
        timeout = setTimeout(() => {
          queryCollectProgress(fileName);
        }, 2000);
      }
    },
    error => {
      sessionStorage.removeItem('collectProgressURL');
      emit('progressClose');
      collectPercent.value = 0;
      if (error.data && error.data.error.length > 0) {
        const errorMessage =
          traduction(error.data.error[0].code + '.errorMessage') || traduction('COMMON_FAILED');
        store.state.event.setEventState({
          type: 'alertMessage',
          value: { type: 'error', message: errorMessage },
        });
      }
    },
  );
}

function sendCompletedMsg(msg: string) {
  // 此处仅作为日志记录作用，无需界面提示成功失败
  sendMsg(msg).then(res => {});
}

function queryDownloadUrl(fileName: string) {
  getDownLoadFileContent().then(
    res => {
      downloadFileWithResponse(res.data, fileName);
      timeout = setTimeout(() => {
        emit('progressClose');
        collectPercent.value = 0;
        showElMessage('success', traduction('COMMON_SUCCESS'));
        sendCompletedMsg(`Download ${fileName} successful`);
      }, 3000);
    },
    () => {
      emit('progressClose');
      collectPercent.value = 0;
      showFailedMessage();
      sendCompletedMsg(`Download ${fileName} failed`);
    },
  );
}

onUnmounted(() => {
  if (timeout !== null) {
    clearTimeout(timeout);
  }
});
</script>

<template>
  <div id="home-collect" class="el-overlay">
    <div class="collect-shade">
      <el-progress :percentage="collectPercent" />
      <span v-t="'HOME_PLEASEWAITMINUTES'"></span>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.collect-shade {
  margin-top: calc(25% - 65px);
  margin-left: calc(50% - 175px);
  text-align: center;
  width: 350px;
  span {
    font-size: 12px;
    color: #ffffff;
    text-align: center;
    margin-top: 16px;
    display: inline-block;
    margin-left: -70px;
  }
  :deep(.el-progress__text) {
    color: #ffffff !important;
  }
}
</style>
