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

const service = PromotionProgressiveDiscountService.build();

const record = {
  campaign_id: '',
  products_per_campaigns: [],
  name: '',
  range: []
};
export default {
  name: 'promotion-progressive-discount-detail',
  components: {
    TextInput,
    NumberInput,
    SelectInput,
    UploadImage,
    searchProduct,
    searchCampaign,
    inputQuantity
  },
  data: () => {
    return {
      record,
      loading: false,
      campaignId: 0,
      product_per_campaign: null,
      campaign: null,
      submit: false,
    };
  },
  computed: {
    rangesComputed() {
      return _.orderBy(this.record.range, 'quantity');
    },
    rangeWithError(){
      var vm = this;
      var rangeWithError = this.record.range.find(range => {
        if (range.discount == "" || range.discount < 0) {
          return true;
        }
        if (isNaN(range.quantity)) {
          return true;
        }
        var rangeValue = parseFloat(range.discount.replace(',', '.'));
        if (range.discount_type == "PERCENT" && rangeValue > 100) {
          return true;
        }

        if (range.discount_type == "CURRENCY_VALUE") {

          let errorInRange = vm.record.products_per_campaigns.find(productPerCampaign =>{
            if(productPerCampaign){
              
              if( rangeValue > productPerCampaign.catalog_value){
                return  true;
              }
            }
            });
            
            if (errorInRange) {
              
              return true;
              
            }
            

        }

      });

      if(rangeWithError){
        return true;
      }

      return false;

    },
    recordIsValid() {

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

      let nullProduct = this.record.products_per_campaigns.find(product => product == null);

      if (nullProduct || this.record.products_per_campaigns.length == 0) {
        return false
      }

      if (this.record.range.length < 1) {
        return false;
      }
    

      if (this.rangeWithError) {
        return false;
      }

      return true;
    },

    formToSend() {
      let data = {};

      Object.assign(data, this.record);

      var rangeComputed = data.range.map(item => {

        return {

          quantity: item.quantity,
          discount_type: item.discount_type,
          discount: item.discount.replace(',', '.')
        }
      });

      data.range = rangeComputed;

      var productsPerCampaignsIds = data.products_per_campaigns.map( item => item.id );


      data.products_per_campaigns = productsPerCampaignsIds;

      return data;
    }
  },
  methods: {
    
    closeModal() {
      this.$modal.hide('promotion-progressive-discount-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;
            if(resp.products_per_campaigns.length > 0){
              vm.campaign = resp.products_per_campaigns[0].campaign;
            }
          });
      } 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 {
          console.log(this.record);
          await service.create(objectToFormData(this.formToSend));
        }

        this.$fire({
          title: 'Sucesso',
          type: 'success',
          text: 'Promoção salva 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 = {
        campaign_id: '',
        products_per_campaigns: [],
        name: '',
        range: []
      };
      
      this.closeModal();
    },
    changeCampaign(campaign) {


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

        if (this.record.products_per_campaigns.length > 0) {

          let productOtherCampaing = this.record.products_per_campaigns.find(product => {
            if (product != null) {

              if (product.campaign_id != campaign.id) {
                return true;
              }
            }
          });

          if (productOtherCampaing) {

            this.record.products_per_campaigns.forEach(product => product = null);

          }

        }


      } else {
        console.log('mudar');
        this.campaignId = 0;
        var vm = this;
        this.record.products_per_campaigns.forEach((product, index) =>
          vm.record.products_per_campaigns[index] = null
        );

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

          this.$refs['searchProduct'].forEach(search => search.clear());
        }

      }

    },
    addRange() {
      this.record.range.push({
        quantity: 1,
        discount_type: "PERCENT",
        discount: '1'
      });
    },
    addProduct() {
      this.record.products_per_campaigns.push(null);
    },
    removeRange(index) {
      this.record.range.splice(index, 1);
    },
    removeProduct(index) {
      this.record.products_per_campaigns.splice(index, 1);
    },
    getValueDiscount(range) {
      if (this.product_per_campaign == null) {
        return 0;
      }
      let productValue = parseFloat(this.product_per_campaign.catalog_value);
      if (range.discount_type === 'PERCENT') {
        let discount = (productValue * parseFloat(range.discount)) / 100;

        return productValue - discount;
      }

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