import axios from 'axios';
import { saveAs } from '@/lib/utils/save';
import { getUrlBlobPdf } from '@/lib/pdf/api';

export default {
  methods: {
    async onDownload(row) {
      if (!row.s3Url) {
        return;
      }

      try {
        const response = await axios.get(row.s3Url, { responseType: 'blob' });
        const fileName = row.printId ? `${row.printId}.pdf` : `pdf_${row._id || Date.now()}.pdf`;
        saveAs(response.data, fileName);
        this.$Message.success(this.$t('PDF_LOG_DOWNLOAD_SUCCESS'));
      } catch (error) {
        this.loggerApi.error('PDF_LOG_DOWNLOAD_ERROR', error);
        this.$Message.error(this.$t('PDF_LOG_DOWNLOAD_ERROR'));
      }
    },
    onView(row) {
      if (row.s3Url) {
        window.open(row.s3Url, '_blank');
      }
    },
    async onPrint(row) {
      if (!row.s3Url) {
        return;
      }

      try {
        const response = await axios.get(row.s3Url, { responseType: 'arraybuffer' });
        const pdfUrl = getUrlBlobPdf(response.data);
        const windowLoadPdf = window.open(pdfUrl, '_blank');

        if (windowLoadPdf) {
          windowLoadPdf.onload = () => {
            windowLoadPdf.print();
          };
        }
      } catch (error) {
        this.loggerApi.error('PDF_LOG_PRINT_ERROR', error);
        this.$Message.error(this.$t('PDF_LOG_PRINT_ERROR'));
      }
    },
  },
};
