<template>
  <div>
    <v-btn @click="downloadCSV">Descargar CSV</v-btn>
  </div>
</template>
<script>
  import { inject } from 'vue';

  export default {
    name: 'ExportPurchasesForTryton',
    data() {
      return {
        api: inject('api'),
      };
    },
    methods: {
      downloadCSV() {
        this.api.getCSVForTryton()
            .then(data => {
              const blob = new Blob([data['csv']], {type: 'text/csv'});
              const pattern = /[/: ]/g;
              const datetime = new Date();
              const date = datetime.toLocaleDateString().replace(pattern, '-');
              const time = datetime.toLocaleTimeString().replace(pattern, '-');
              const name = `VentasTryton_${date}_${time}.csv`;
              const link = document.createElement('a');

              link.href = URL.createObjectURL(blob);
              link.download = name;
              link.click();
              URL.revokeObjectURL(link.href);
            })
            .catch(error => {
              console.error(error);
            });
      },
    },
  };
</script>
