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

import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { completeProtocolConfig, downloadUserProtocol, getProtocolBaseInfo, updateProtocolBaseInfo } from '@/api';
import { downloadBlob } from '@/utils';
import { FINISH_MODAL_GUIDANCE } from '@/constants/inject-key';

import ProtocolContent from './ProtocolContent.vue';

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

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

const { handleRequest } = useRequest();
let fileName = '';

onMounted(() => {
  handleRequest(async () => {
    const { protocolInfo } = props.form;
    const { id, protocolType, protocolName } = protocolInfo;
    fileName = `${protocolType} - ${protocolName}.xlsx`;

    if (id) {
      const data = await getProtocolBaseInfo(id);
      Object.assign(protocolInfo, data);
    }
  });
});

const reRecognize = () => {
  props.goToStep(props.stepIndex - 2);
};

const exportData = () => {
  handleRequest(async () => {
    await protocolContentRef.value?.isAtLeastOneParam();

    const { id } = props.form.protocolInfo;

    if (id) {
      const file = await downloadUserProtocol(id);
      downloadBlob(file, fileName);
      message.success(t('setupProtocol.downloadProtocolSuccessful', { name: fileName }));
    }
  });
};

const goBack = () => {
  reRecognize();
  return true;
};

const protocolContentRef = useTemplateRef('protocolContent');
const finishModalGuidance = inject(FINISH_MODAL_GUIDANCE, undefined);

const finish = async () => {
  await protocolContentRef.value?.validateProtocolInfo();
  await protocolContentRef.value?.isAtLeastOneParam();
  await updateProtocolBaseInfo(props.form.protocolInfo);
  await completeProtocolConfig(props.form.protocolInfo.id as number);
  finishModalGuidance?.();
};

defineExpose<UseGuideStepItemExpose>({
  exportData,
  goBack,
  finish,
});
</script>

<template>
  <div class="result-container">
    <AButton class="icon-button recognize-button" @click="reRecognize">
      <SvgIcon name="reload" />
      {{ $t('setupProtocol.reRecognize') }}
    </AButton>
    <ProtocolContent ref="protocolContent" :info="form.protocolInfo" :is-recognized="true" />
  </div>
</template>

<style lang="scss" scoped>
.result-container {
  position: relative;
}

.recognize-button {
  position: absolute;
  top: -103px;
}
</style>
