import TextInput from '@/components/shared-components/inputs/TextInput';
import searchProduct from '@/components/shared-components/searchs/searchProduct';
import searchCampaign from '@/components/shared-components/searchs/searchCampaign';
import SelectInput from '@/components/shared-components/inputs/SelectInput';
import LastTimeOffersService from '@/services/resources/LastTimeOffersService';
import {toHTMLErrorsByValidatorLaravel} from "@/utils/requests"
import UploadImage from '@/components/shared-components/FileInput';
import { objectToFormData } from '@/utils/convert.js';

const service = LastTimeOffersService.build();

const record = {
  banner: '',
  product_per_campaign_id: '',
  banner_url: ''
};
export default {
  name: 'last-time-offers-detail',
  components: {
    TextInput,
    SelectInput,
    UploadImage,
    searchProduct,
    searchCampaign
  },
  data: () => {
    return {
      record,
      loading: false,
      campaignId: 0,
      loadedImage: true,
      product_per_campaign: null,
      campaign: null
    };
  },
  methods: {
    onImageChange(file) {
      this.record.banner = file;
    },
    closeModal() {
      this.$modal.hide('last-time-offers-detail');
      this.$emit('closed');
    },
    async beforeOpenModal(event) {
      this.reset();
      const { id } = event.params || {};
      if (!id) {
        return;
      }
      try {
        var vm = this;
        this.loadedImage = false;
         await service.read(id)
        .then(resp => {
          vm.record = resp;
          vm.product_per_campaign = resp.product_per_campaign;
          vm.campaign = resp.product_per_campaign.campaign;
          vm.loadedImage = true;
        });
      } catch (error) {
        this.showError(error);
      }
    },
    async save() {
      try {
        if (this.record.id) {

          if(typeof(this.record.banner) == 'string'){
            delete this.record.banner;
        }

          const obj = objectToFormData({
            ...this.record,
            _method: 'PUT'
          });
          await service.update(obj);
        } else {
          await service.create(objectToFormData(this.record));
        }

        this.$fire({
          title: 'Sucesso',
          type: 'success',
          text: 'Oferta salvo com sucesso'
        });

        this.closeModal();
        this.$emit('success');
      } catch (error) {
        this.showError(error);
      }
    },
    showError(error) {
      let html = '';
      const resp = JSON.parse(error.response.data);
      try {
        const getData = () => {
          try {
            return resp.msg || resp;
          } catch {
            return {};
          }
        };

        
        html = toHTMLErrorsByValidatorLaravel(resp.data);
      } catch {
        html = 'Ocorreu um erro na operação';
      }

      this.$fire({
        title: 'Erro',
        type: 'error',
        html
      });
    },
    reset() {
      this.record = { ...record };
      this.campaignId = 0;
      this.product_per_campaign = null,
      this.campaign = null;
      this.closeModal();
    },
    changeCampaign(campaign){
   

     if(campaign != null){
      this.campaignId = campaign.id;
      if(this.product_per_campaign != null){

        if(this.product_per_campaign.campaign_id != campaign.id){

          this.product_per_campaign = null;
          this.record.product_per_campaign_id = 0;
        }
      }else{
        this.$refs['searchProduct'].clear();
        this.record.product_per_campaign_id = 0;

      }
     }else{
       this.campaignId = 0;
      this.product_per_campaign = null;
      this.record.product_per_campaign_id = 0;
     }

    },
    changeProduct(ProductPerCampaign){
      
     this.record.product_per_campaign_id = (ProductPerCampaign != null)?  ProductPerCampaign.id : 0;
    }
  },
};
