import TextInput from '@/components/shared-components/inputs/TextInput';
import NumberInput from '@/components/shared-components/inputs/NumberInput';
import inputQuantity from '@/components/shared-components/inputs/inputQuantity';
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 PromotionService from '@/services/resources/PromotionService';
import { toHTMLErrorsByValidatorLaravel } from "@/utils/requests"
import UploadImage from '@/components/shared-components/FileInput';
import { objectToFormData } from '@/utils/convert.js';

const service = PromotionService.build();

const recordDefault = {
  campaign_id: '',
  name: '',
  discount_type: "PERCENT",
  buy_type: "OR", 
  take_type: "OR",
  promotion_has_buy_product_per_campaign: [],
  promotion_has_take_product_per_campaign: []
};
export default {
  name: 'promotion-detail',
  components: {
    TextInput,
    NumberInput,
    SelectInput,
    UploadImage,
    searchProduct,
    searchCampaign,
    inputQuantity
  },
  data: () => {
    return {
      record:recordDefault,
      loading: false,
      campaignId: 0,
      product_per_campaign: null,
      campaign: null,
      submit: false,
    };
  },
  computed: {
    rangesComputed() {
      return _.orderBy(this.record.range, 'quantity');
    },
    recordIsValid() {

      if (this.record.name.length < 4) {
        return false;
      }

      if(this.record.promotion_has_buy_product_per_campaign.length == 0 || this.record.promotion_has_take_product_per_campaign.length == 0){
        return false;
      }

    var vm = this;
     let takeWithError = this.record.promotion_has_take_product_per_campaign.find(take => {
        if (take.discount == "" || take.discount < 0) {
          return true;
        }
        
        if(take.product_per_campaign == null){
          return true;
         }

        let takeValue = parseFloat(take.discount.replace(',','.'));
        if(vm.record.discount_type == "PERCENT" && takeValue > 100){
          return true;
        }

        if(vm.record.discount_type == "CURRENCY_VALUE" && takeValue > take.product_per_campaign.catalog_value){
          return true;
        }

      });


      let buyWithError = this.record.promotion_has_buy_product_per_campaign.find(buy => {
        
        if(isNaN(buy.quantity)){
          return true;
        }

       if(buy.product_per_campaign == null){
        return true;
       }

      });

      if(takeWithError || buyWithError){
        return false;
      }

      return true;
    },
    formToSend(){
      var data  = {};
     
      Object.assign(data,this.record);
      
      let buyArray = data.promotion_has_buy_product_per_campaign.map( buy => {
        return {
          product_per_campaign_id: buy.product_per_campaign.id,
          quantity: buy.quantity
        };
      });
      data.promotion_has_buy_product_per_campaign = buyArray;

      let takeArray = data.promotion_has_take_product_per_campaign.map( take => {
        return {
          product_per_campaign_id: take.product_per_campaign.id,
          discount: parseFloat(take.discount.replace(',','.'))
        };
      });

      data.promotion_has_take_product_per_campaign = takeArray;

      return data
    }
  },
  methods: {
    onImageChange(file) {
      this.record.banner = file;
    },
    closeModal() {
      this.$modal.hide('promotion-detail');
      this.$emit('closed');
    },
    async beforeOpenModal(event) {
      this.reset();
      const { id } = event.params || {};
      if (!id) {
        return;
      }
      try {
        var vm = this;
        
        await service.read(id)
          .then(resp => {
            vm.record = resp;
           
            vm.campaign = resp.campaign;
            
          });
          this.$forceUpdate();
      } catch (error) {
        this.showError(error);
      }
    },
    async save() {

      if(!this.recordIsValid){
        this.submit = true;
        return;
      }

      try {
        if (this.record.id) {



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

       await this.$fire({
          title: 'Sucesso',
          type: 'success',
          text: 'Promoção salva com sucesso'
        });
        this.reset();
       // 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 = {
  campaign_id: '',
  name: '',
  discount_type: "PERCENT",
  buy_type: "OR", 
  take_type: "OR",
  promotion_has_buy_product_per_campaign: [],
  promotion_has_take_product_per_campaign: []
};
      
      this.closeModal();
    },
    changeCampaign(campaign) {


      if (campaign != null) {
        this.record.campaign_id = campaign.id;
        console.log(this.record.promotion_has_buy_product_per_campaign.length);
        if ( this.record.promotion_has_buy_product_per_campaign.length > 0
          || this.record.promotion_has_take_product_per_campaign.length > 0 ) {

          let buyOtherCampaign =  this.record.promotion_has_buy_product_per_campaign.find( buy => buy.product_per_campaign.campaign_id != campaign.id);
          let takeOtherCampaign =  this.record.promotion_has_take_product_per_campaign.find( take => take.product_per_campaign.campaign_id != campaign.id);

          if (buyOtherCampaign || takeOtherCampaign) {

            this.record.promotion_has_buy_product_per_campaign.forEach( buy => buy.product_per_campaign = null);
            this.record.promotion_has_take_product_per_campaign.forEach( take => take.product_per_campaign = null);

          }
        } else {

          if( this.$refs['searchProduct']){

            this.$refs['searchProduct'].forEach( search => search.clear());
          }
       
        }
      } else {
        this.record.campaign_id = 0;
        this.record.promotion_has_buy_product_per_campaign.forEach( buy => buy.product_per_campaign = null);
        this.record.promotion_has_take_product_per_campaign.forEach( take => take.product_per_campaign = null);
      }

    },
    changeProduct(ProductPerCampaign) {

      this.record.product_per_campaign_id = (ProductPerCampaign != null) ? ProductPerCampaign.id : 0;
    },
    addtake() {
      this.record.promotion_has_take_product_per_campaign.push({
        discount: '1',
        product_per_campaign: null
      });
    },
    removeTake(index) {
      console.log(index);
      this.record.promotion_has_take_product_per_campaign.splice(index, 1);
    },
    addBuy() {
      this.record.promotion_has_buy_product_per_campaign.push({
        quantity: 1,
        product_per_campaign: null
      });
    },
    removeBuy(index) {
      this.record.promotion_has_buy_product_per_campaign.splice(index, 1);
    },
    getValueDiscount(take) {
      if (take.product_per_campaign == null) {
        return 0;
      }
      let productValue = parseFloat(take.product_per_campaign.catalog_value);
      if (this.record.discount_type === 'PERCENT') {
        let discount = (productValue * parseFloat(take.discount)) / 100;

        return productValue - discount;
      }

      return productValue - parseFloat(take.discount.replace(',', '.'));
    },
  },
};
