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

import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { addProtocolBaseInfo, completeProtocolConfig, downloadUserProtocol, 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();

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

    if (props.form.protocolInfo.id) {
      await updateProtocolBaseInfo(props.form.protocolInfo);
    } else {
      props.form.protocolInfo.id = await addProtocolBaseInfo(props.form.protocolInfo);
      await protocolContentRef.value?.submitLocalParams();
      protocolContentRef.value?.getCurrentProtocolParams();
    }

    const { id, protocolType, protocolName } = props.form.protocolInfo;
    const fileName = `${protocolType} - ${protocolName}.xlsx`;
    const file = await downloadUserProtocol(id);
    downloadBlob(file, fileName);
    message.success(t('setupProtocol.downloadProtocolSuccessful', { name: fileName }));
  });
};

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

const finish = async () => {
  await protocolContentRef.value?.validateProtocolInfo();
  await protocolContentRef.value?.isAtLeastOneParam();

  if (props.form.protocolInfo.id) {
    await updateProtocolBaseInfo(props.form.protocolInfo);
  } else {
    props.form.protocolInfo.id = await addProtocolBaseInfo(props.form.protocolInfo);
    await protocolContentRef.value?.submitLocalParams();
  }

  await completeProtocolConfig(props.form.protocolInfo.id as number);
  finishModalGuidance?.();
};

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

<template>
  <div>
    <ProtocolContent ref="protocolContent" :info="form.protocolInfo" :is-recognized="false" />
  </div>
</template>
