
import {getValueToPay} from "@/utils/promotions";
import { state } from ".";
import getters from "./getters";
import {defaultState} from '@/store/modules/orderCreate/functions'

export default {

    initState: (state,payload) => {

        state.free_shipping = payload.free_shipping ;
        state.min_order_amount = payload.min_order_amount ;
        state.sales_consultant_fixed_discount = payload.sales_consultant_fixed_discount ;
        state.credit_limit = payload.credit_limit ;
        state.promotions = payload.promotions;
        state.promotions_progressive = payload.promotions_progressive;
        state.last_time_offers = payload.last_time_offers;
        state.featured_offers = payload.featured_offers;
        state.payment_method = (parseFloat(payload.credit_limit) > 0)? "BILLET" : "CREDIT_CARD";
        state.calendar = payload.calendar;
        state.benchmarking_ranges = payload.benchmarking_ranges;
        state.incentives = payload.incentives;
        state.service = (payload.order !=null)? payload.order.service : null;
    },
    resetState: (state) => {
      Object.assign(state, defaultState());
    },
    setSettings: (state,payload) => {
        state.settings = payload;
    },
    setPaymentMethod(state, payload){
        state.payment_method = payload.payment_method;
    },
    setServiceOrder(state, payload){
      state.service = payload;
  },
    setSalesConsultant: (state,payload) => {

       
       
        state.salesConsultantId = payload;
       
        
    },
    setSalesConsultantObject: (state,payload) => {

       
       
      state.salesConsultant = payload;
     
      
  },
    setResumeLastOrderValue: (state,payload) =>{
      state.resumeLastOrderValue = parseFloat(payload);
    },
    addProduct: (state,payload) => {
       payload.sub_total = 0;
       payload.to_pay = 0;
        state.order_products.push(payload);
        clearProductPromotionDiscount(state);

    },
    updateProductQuantity: (state, payload) => {
    
       if(payload.quantity < 0 ){
        return;
       }
        state.order_products.find(product => {
            if (product.product_per_campaign.id == payload.product_per_campaign.id) {
              product.quantity = payload.quantity;
              return true;
            }
          });

          clearProductPromotionDiscount(state);
    },
    

    updateProductPromotionDiscount: (state, payload) => {
    
       
        state.order_products.find(product => {
            if (product.product_per_campaign.id == payload.product_per_campaign.id) {
              product.discount_promotion += payload.discountPromotion;

              if(!product.promotions.includes(payload.promotion) && typeof(payload.promotion) !== "undefined"){

                  product.promotions.push(payload.promotion);
              }

              if(payload.promotionProgressive){
                product.promotions_progressive = payload.promotionProgressive;
              }

              return true;
            }
          });
    },

    updateOrderPrices: (state,getters) => {
        
        state.order_products.forEach( product => {
            
            product.sub_total = (product.quantity * product.product_per_campaign.catalog_value) -  product.discount_promotion; 
            
            product.to_pay = getValueToPay(product,state.sales_consultant_fixed_discount, getters.getters.getBenchmarkingRange);
        });

    },

    updateComputedOrder: (state,getters) => {


        state.computedOrder = getProductsOrder(state.order_products, state);
    },

    removeProduct(state,index){
        state.order_products.splice(index, 1);
        clearProductPromotionDiscount(state);
    },

    setOrderId(state, id){
        state.orderId = id;
    },
    setStatus(state,status){
      state.status = status;
    }

    
}

function clearProductPromotionDiscount(state){

    state.order_products.forEach( product => {
        product.discount_promotion = 0;
        product.promotions = [];
        product.promotions_progressive = null;
    });
}

function getProductsOrder(products, state){

    var table = [];
    
  
    products.forEach( product => {
  
        let row = {};
  
        
        if(product.promotions_progressive != null){
            
            row.product_per_campaign_id = product.product_per_campaign.id; 
            row.unit_price = parseFloat(product.product_per_campaign.catalog_value) - calcDiscountProgessive(product);
            row.quantity = product.quantity;
            row.total =  product.quantity * (parseFloat(product.product_per_campaign.catalog_value) - calcDiscountProgessive(product))
            
            table.push(row);
            
        }else if(product.promotions.length > 0){
            
            table = table.concat(getPricesTableByPromotions(product, state));
            
        }else{
            //console.log(product.product_per_campaign.id);
            row.product_per_campaign_id = product.product_per_campaign.id; 
            row.unit_price = parseFloat(product.product_per_campaign.catalog_value);
            row.quantity = product.quantity;
            row.total =  product.quantity * parseFloat(product.product_per_campaign.catalog_value);
            
            table.push(row)
        }
  
  
    });
  
  return table;
  }
  
  function getPricesTableByPromotions(product, state){
  
    var total = product.quantity;
    var table = [];
  
      product.promotions.forEach(promotionApplied => {
        let promotion = state.promotions.find(
          promotion => promotionApplied.promotionId == promotion.id
        );
  
        let productPromotionTakeValue = promotion.promotion_has_take_product_per_campaign.find(
          promotion =>
            promotion.product_per_campaign.id ==
            product.product_per_campaign.id
        );
  
        let row = {};
  
    let productPromotionBuy = thereIsBuy(promotion, product.product_per_campaign.id);
        if (!productPromotionBuy) {
          row.unit_price =
            parseFloat(product.product_per_campaign.catalog_value) -
            getValueDiscount(
            parseFloat(product.product_per_campaign.catalog_value),
              promotion.discount_type,
              productPromotionTakeValue.discount
            );
          row.quantity = promotionApplied.quantity;           
          total -= promotionApplied.quantity;
        } else {
  
            row.unit_price = 
            parseFloat(product.product_per_campaign.catalog_value) -
            (getValueDiscount(
            parseFloat(product.product_per_campaign.catalog_value),
              promotion.discount_type,
              productPromotionTakeValue.discount
            ) / productPromotionBuy.quantity);
          row.quantity = promotionApplied.quantity * productPromotionBuy.quantity ;
          total -= promotionApplied.quantity * productPromotionBuy.quantity;
        }
        row.total = row.quantity * row.unit_price;
        row.product_per_campaign_id = product.product_per_campaign.id; 
        table.push(row);
      });
  
      if (total > 0) {
          let unit_price = parseFloat(product.product_per_campaign.catalog_value);
        let row = {
        product_per_campaign_id: product.product_per_campaign.id,
          unit_price: unit_price,
          quantity: total,
          total: total * unit_price
  
        };
  
        table.push(row);
    }
  
    return table;
  }
  function  thereIsBuy(promotion,productPerCampaignId) {
  
    return promotion.promotion_has_buy_product_per_campaign.find(
      product => product.product_per_campaign.id == productPerCampaignId
    );
  }
  
  function calcDiscountProgessive(product) {
  
    return getValueDiscount(
        parseFloat(product.product_per_campaign.catalog_value),
             product.promotions_progressive.discount_type,
             parseFloat( product.promotions_progressive.discount),
           );
  
  }
  
  function getValueDiscount(productCatalogPrice, typeDiscount, valueDiscount) {
  
    if (typeDiscount === "PERCENT") {
  
        return parseFloat(valueDiscount) * parseFloat(productCatalogPrice) / 100;
  
    } else {
  
        return valueDiscount;
  
    }
}