import promotionDetail from '@/components/modals/promotion/PromotionDetail.vue';
import PromotionService from '@/services/resources/PromotionService';


const service = PromotionService.build();


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

      service
        .search({with: "campaign,promotion_has_buy_product_per_campaign.product_per_campaign.product,promotion_has_take_product_per_campaign.product_per_campaign.product"})
        .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('promotion-detail');
    },
    edit(id) {
      this.$modal.show('promotion-detail', { id });
    },
    remove(row) {
      this
        .$fire({
          title: 'Remover oferta',
          html: `Deseja realmente remover o oferta <strong>${row.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();
  }
};
