import offersDetail from '@/components/modals/last-time-offers/LastTimeOffersDetail.vue';
import LastTimeOffersService from '@/services/resources/LastTimeOffersService';


const service = LastTimeOffersService.build();


export default {
  components: {
    offersDetail
  },
  data() {
    return {
      rows: [],
      loading: false
    };
  },
  methods: {
    search() {
      this.loading = true;

      service
        .search({with: "product_per_campaign.product,product_per_campaign.campaign"})
        .then((resp) => {
          this.rows = resp;
this.loading = false
        })
        .catch((err) => {
          const resp = JSON.parse(err.response.data);
          this.$fire({
            title: 'Falha na solicitação',
            text: resp.msg,
            type: 'error'
          });
          this.loading = false;
        });
    },
    showModal() {
      this.$modal.show('last-time-offers-detail');
    },
    edit(id) {
      this.$modal.show('last-time-offers-detail', { id });
    },
    remove(row) {
      this
        .$fire({
          title: 'Remover oferta',
          html: `Deseja realmente remover o oferta <strong>${row.product_per_campaign.product.name}</strong>?`,
          type: 'question',
          showCancelButton: true,
          confirmButtonText: 'Deletar',
          cancelButtonText: 'Cancelar'
        })
        .then(async ({ value }) => {
          if (value) {
            let text = 'Oferta removido com sucesso.';
            let type = 'success';
            try {
              await service.destroy(row.id);
              this.search();
            } catch (error) {
              console.error(error);
              text = 'Ocorreu um erro ao tentar remover o oferta';
              type = 'danger';
            } finally {
              this.$fire({
                title: 'Remoção de oferta',
                type,
                text
              });
            }
          }
        });
    }
  },
  mounted() {
    this.search();
  }
};
