<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { exportBiosConfig, getTask } from '@/services/system/bios-service';
import { generalDownLoadFile, downloadFileWithResponse } from '@/utils/common-service';
import { traduction } from '@/utils/language';
import { ElNotification as elNotification } from 'element-plus';
import UploadingIcon from '@/components/UploadingIcon/UploadingIcon.vue';
import { notificationIcons } from '@/model/base-constant';

const exportState = ref(false);

const exportProgress = reactive({
  show: false,
  value: 0,
  errorMsg: '',
});

function setExportButtonState(state: boolean) {
  exportState.value = state;
}

function exportConfig() {
  setExportButtonState(true);
  exportProgress.show = true;
  exportProgress.value = 0;
  exportBiosConfig().then((res: any) => {
    const url = res.data.url;
    sessionStorage.setItem('biosExportUrl', url);
    preProgress(url);
    openNotification({
      title: traduction('COMMON_EXPORTING'),
      message: traduction('BIOS_EXPORTING'),
      icon: UploadingIcon as any,
    });
  });
}

// 查询导出进度
function preProgress(url: string) {
  getTask(url).then((response: any) => {
    const res = response.data;
    if (res.prepare_progress === 100 && res.state === 'Completed') {
      exportProgress.value = 100;
      sessionStorage.removeItem('biosExportUrl');
      downloadConfig('/tmp/bios.tar.gz');
    } else if (res.state === 'Running' || res.state === 'Starting') {
      exportProgress.value = res.prepare_progress;
      setTimeout(() => preProgress(url), 3000);
    } else {
      executeExportFailed();
    }
  }).catch(() => {
    executeExportFailed();
  });
}

// 下载文件
function downloadConfig(url: string) {
  setExportButtonState(false);
  generalDownLoadFile(url).then(res => {
    const fName = res.headers['content-disposition'].split('=')[1];
    downloadFileWithResponse(res.data, fName);
    elNotification.closeAll();
    openNotification({
      title: traduction('COMMON_EXPORT_COMPLETE'),
      message: traduction('BIOS_EXPORT_SUCCESS'),
      icon: notificationIcons.success as any,
    });
  });
}

// 导出失败
function executeExportFailed() {
  setExportButtonState(false);
  exportProgress.errorMsg = traduction('BIOS_EXPORT_FAILED');
  openNotification({
    title: traduction('COMMON_EXPORT_FAILED'),
    message: traduction('BIOS_EXPORT_FAILED'),
    icon: notificationIcons.error as any,
  });
}

// 右下角通知
let noticeInstance: any = null;
function openNotification(param: any) {
  if (noticeInstance) {
    noticeInstance.close();
  }
  noticeInstance = elNotification({
    title: param.title,
    message: param.message,
    position: 'bottom-right',
    duration: 0,
    icon: param.icon,
    appendTo: '#configUpdateBox',
  });
}

// 页面初始化时检查是否有未完成导出任务
onMounted(() => {
  const url = sessionStorage.getItem('biosExportUrl');
  if (url) {
    preProgress(url);
  }
});
</script>

<template>
  <div id="configUpdateBox" class="root-container">
    <div class="config-item">
      <div class="export">
        <el-button
          :disabled="exportState"
          :class="{ 'default-disabled-btn': exportState }"
          @click="exportConfig"
        >
          {{ traduction('CONFIG_UPGRADE_EXPORT_SHORT') }}
        </el-button>
      </div>
      <el-progress
        v-if="exportProgress.show"
        class="export-progress"
        stroke-width="4"
        :percentage="exportProgress.value"
      />
      <div v-if="exportProgress.errorMsg !== ''" class="export-errors">
        {{ exportProgress.errorMsg }}
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.root-container {
  margin-right: 24px;
}
.config-item {
  padding: 24px;
  background: var(--o-bg-color-base);
  border-radius: 4px;
  h3 {
    font-size: 16px;
    margin-bottom: 16px;
  }
  .export-progress {
    margin-top: 8px;
    width: 400px;
  }
  .export-errors {
    color: var(--o-color-danger);
    margin-top: 4px;
  }
  .default-disabled-btn {
    background-color: #ebedf3;
  }
}
</style>
