<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { useRoute } from 'vue-router';
import { exportBiosConfig, getBiosExportEnableState, getTask, setBiosExportEnableState } from '@/services/system/bios-service';
import { generalDownLoadFile, downloadFileWithResponse } from '@/utils/common-service';
import { getErrorTranslate, traduction } from '@/utils/language';
import { ElNotification as elNotification } from 'element-plus';
import UploadingIcon from '@/components/UploadingIcon/UploadingIcon.vue';
import { notificationIcons } from '@/model/base-constant';
import useStore from '@/stores';
import { checkPrivil } from '@/apps/app-bmc/router/routes';
import { UserPrivil } from '@/model/base-enum';
import { loading, showFailedMessage } from '@/utils/composition';
import { showElMessage } from '@/utils/utils';

const route = useRoute();

const switchEnabled = ref(false);
const switchState = ref(false);
const exportState = ref(false);

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

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

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

const store = useStore();
const isSystemLocked = computed(() => store.state.glob.systemLocked);
const isAdmin = checkPrivil(UserPrivil.userConfig);

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(() => {
  checkSwitchEnable();
  checkAndResumeExportTask();
});

async function checkSwitchEnable(): Promise<void> {
  const systemId = route.query.systemId as string ?? '1';
  const state = await getBiosExportEnableState(systemId);
  if (state !== null) {
    switchEnabled.value = true;
    switchState.value = state;
  }
} 

// 检查并恢复当前主机的导出任务
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);
  }
}

async function setExportEnable(state: boolean): Promise<void> {
  const systemId = route.query.systemId as string ?? '1';
  loading(true);
  try {
    await setBiosExportEnableState(systemId, state);
    showElMessage('success', traduction('COMMON_SUCCESS'));
  } catch (error: any) {
    const code = error?.data?.error?.[0]?.code;
    showFailedMessage(getErrorTranslate(code));
  } finally {
    loading(false);
    checkSwitchEnable();
  }
}

// 监听路由参数变化，当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 v-if="switchEnabled && isAdmin" class="bios-enable">
        <span class="bios-enable-label">{{ $t('BIOS_EXPORT_ENABLED') }}</span>
        <el-switch v-model="switchState" :disabled="exportState || isSystemLocked" @change="setExportEnable" />
      </div>
      <div class="export">
        <el-button
          type="primary"
          :disabled="exportState || (switchEnabled && !switchState) || isSystemLocked"
          :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;
  .bios-enable {
    margin-bottom: 16px;
    display: flex;
    gap: 32px;
    .bios-enable-label {
      color: var(--o-text-color-secondary);
    }
  }
  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>
