<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { message } from 'ant-design-vue';

import { reUploadUserProtocol, uploadUserProtocol } from '@/api';
import { waitTime } from '@/utils';

import type { SetupProtocolForm, UseGuideStepItemProps } from '@/types';

const props = defineProps<UseGuideStepItemProps<SetupProtocolForm>>();

const remainingSeconds = ref(90);
const currentPercent = ref(0);
let timer: number | undefined;

onMounted(async () => {
  await new Promise<void>((resolve) => {
    timer = window.setInterval(() => {
      updateProgress(resolve);
    }, 500);
  });

  let uploadErr: Error | undefined;

  try {
    const { protocolType, protocolFile, protocolInfo } = props.form;
    const file = protocolFile?.[0].originFileObj;
    let data;

    if (protocolInfo.id) {
      // 若协议 id 存在，则此前已经上传过该协议，故调用重新配置的接口以删除旧协议，并上传新协议
      data = await reUploadUserProtocol(protocolType as string, protocolInfo.id, file as File);
    } else {
      data = await uploadUserProtocol(protocolType as string, file as File);
    }

    Object.assign(protocolInfo, data);
  } catch (err) {
    uploadErr = err as Error;
  }

  remainingSeconds.value = 0;
  currentPercent.value = 100;
  await waitTime(1000);

  if (uploadErr) {
    props.goToStep(props.stepIndex - 1);
    message.error(uploadErr.message);
    console.error(uploadErr);
  } else {
    props.goToStep(props.stepIndex + 1);
  }
});

const STOP_SECONDS = 3; // 更新剩余时间时的停止秒数
const STOP_PERCENT = 95; // 更新当前进度时的停止百分比

const updateProgress = (resolve: () => void) => {
  const decrementSeconds = Math.floor(remainingSeconds.value / 2);
  const incrementPercent = Math.floor((100 - currentPercent.value) / 2);
  remainingSeconds.value = Math.max(remainingSeconds.value - decrementSeconds, STOP_SECONDS);
  currentPercent.value = Math.min(currentPercent.value + incrementPercent, STOP_PERCENT);

  if (remainingSeconds.value === STOP_SECONDS && currentPercent.value === STOP_PERCENT) {
    clearInterval(timer);
    resolve();
  }
};

onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <div>
    <div class="recognize-tip">{{ $t('setupProtocol.recognizeTip', { time: remainingSeconds }) }}</div>
    <AProgress
      class="recognize-progress"
      :percent="currentPercent"
      :format="() => $t('setupProtocol.recognizeProgress')"
    />
  </div>
</template>

<style lang="scss" scoped>
.recognize-tip {
  margin-bottom: 16px;
  font-size: 14px;
  line-height: 22px;
  color: #333;
}

:deep(.recognize-progress) {
  max-width: 616px;

  .ant-progress-bg {
    background-color: var(--antd-color-primary);
  }

  .ant-progress-text {
    font-size: 14px;
    color: var(--antd-color-text-tertiary);
  }
}
</style>
