<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
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 route = useRoute();

const exportState = ref(false);

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

// 当前主机的导出任务URL
const currentExportTaskKey = ref('');

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

function exportConfig() {
  setExportButtonState(true);
  exportProgress.show = true;
  exportProgress.value = 0;
  // 获取systemId参数，如果存在则传递给exportBiosConfig
  const systemId = route.query.systemId as string;
  // 生成当前主机的导出任务key
  const taskKey = systemId ? `bios_export_${systemId}` : 'bios_export_single';
  currentExportTaskKey.value = taskKey;

  exportBiosConfig(systemId).then((res: any) => {
    const url = res.data.url;
    // 使用主机相关的key存储，避免多主机环境下冲突
    sessionStorage.setItem(taskKey, url);
    preProgress(url);
    openNotification({
      title: traduction('COMMON_EXPORTING'),
      message: traduction('BIOS_EXPORTING'),
      icon: UploadingIcon as any,
    });
  }).catch(() => {
    if (currentExportTaskKey.value === taskKey) {
      setExportButtonState(false);
      exportProgress.show = false;
      exportProgress.value = 0;
    }
  });
}

// 查询导出进度
function preProgress(url: string) {
  if (url !== sessionStorage.getItem(currentExportTaskKey.value)) {
    return;
  }
  getTask(url).then((response: any) => {
    const res = response.data;
    if (res.prepare_progress === 100 && res.state === 'Completed') {
      exportProgress.value = 100;
      // 清理当前主机的导出任务
      if (currentExportTaskKey.value) {
        sessionStorage.removeItem(currentExportTaskKey.value);
      }
      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(() => {
  checkAndResumeExportTask();
});

// 检查并恢复当前主机的导出任务
function checkAndResumeExportTask() {
  setExportButtonState(false);
  exportProgress.show = false;
  exportProgress.value = 0;
  exportProgress.errorMsg = '';

  const systemId = route.query.systemId as string;
  const exportTaskKey = systemId ? `bios_export_${systemId}` : 'bios_export_single';
  currentExportTaskKey.value = exportTaskKey;

  const url = sessionStorage.getItem(exportTaskKey);
  if (url) {
    setExportButtonState(true);
    exportProgress.show = true;
    preProgress(url);
  }
}

// 监听路由参数变化，当systemId改变时重新获取数据
watch(
  () => route.query.systemId,
  (newSystemId, oldSystemId) => {
    if (newSystemId !== oldSystemId) {
      // systemId变化时，切换主机的导出任务状态
      // 不需要停止导出，只是获取新主机的导出状态
      checkAndResumeExportTask();
    }
  },
);
</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>
