import { range } from "lodash";

export default {
  getOrderById: (state) => (id) => {


    return state.order_products.find(product => product.product_per_campaign.id === id);


  },
  getOrder: (state, getters) => () => {
    return state.order_products;
  },

  getTotalToPay: (state, getters) => {
    var total = 0;

    getters.getOrder().forEach(product => {

      total += parseFloat(product.to_pay);
    });

if(typeof(getters.getBenchmarkingRange) != 'undefined'){

  total += parseFloat(getters.getBenchmarkingRange.shipping_value);

}

    return total;
  },
  getOrdeWithCatalogPrice: (state, getters) => () =>{

    var products =  getters.getOrder();

    return getProductsOrder(products,state);

  },
  getSumSubTotal: (state, getters) => {
    var total = 0;

    getters.getOrder().forEach(product => {

      total += parseFloat(product.sub_total);
    });

    return total;
  },
  getMinOrderAmount: (state, getters) => {
    var total = 0;

    getters.getOrder().forEach(product => {

      if(parseFloat(product.product_per_campaign.amount_minimum_value) > 0){

        total += parseFloat(product.sub_total);
      }

    });

    return total;
  },

  getNeedMinOrderToClass: (state, getters) => {

    if(state.settings.discount_class != "P"){
      return state.min_order_amount;
    }

    var min = 0;

    state.benchmarking_ranges.forEach(   (range, index) => {
      
      if(index == 0){
        min = parseFloat(range.start_value);
      }else if(index > 0 && parseFloat(range.start_value) < min){
        min = parseFloat(range.start_value);
      }
    } );

    return min;

  },

  getLastTimeOffers: (state, getters) => {

    return state.last_time_offers.filter(offer => {
      return !getters.getOrderById(offer.product_per_campaign.id);
    })
  },
  getBenchmarkingRange: (state, getters) => {

return state.benchmarking_ranges.find( range => getters.getMinOrderAmount >=  range.start_value && getters.getMinOrderAmount <= range.end_value )
  },
  getSuggestedProducts: (state, getters) => {
    var suggested = [];
    console.log(getters.getOrder());
    getters.getOrder().forEach(product => {

      if (product.product_per_campaign.suggested_product) {
        if (!getters.getOrderById(product.product_per_campaign.suggested_product.id)) {

          suggested.push(product.product_per_campaign.suggested_product);
        }
      }


    });
    return suggested;
  },

  getFeaturedOffers: (state, getters) => {
    return state.featured_offers.filter(offer => {
      return !getters.getOrderById(offer.product_per_campaign.id);
    })
  },

  getAmountIncentive: (state, getters) =>{

    var total = 0;
    
    state.computedOrder.forEach(product => {
     
      if(product.unit_price > 0 && getters.getOrderById(product.product_per_campaign_id)){
       
        total += product.quantity * parseFloat(getters.getOrderById(product.product_per_campaign_id).product_per_campaign.amount_incentive);
      }

     
    });

    return total;
  },
  getTotalIncentiveQuantity: (state, getters) =>{

    var total = 0;
    
    state.computedOrder.forEach(product => {
     
      if(product.unit_price > 0 && getters.getOrderById(product.product_per_campaign_id)){
       
        total += product.quantity * getters.getOrderById(product.product_per_campaign_id).product_per_campaign.quantity_incentive;
      }

     
    });

    return total;
  },
  getConqueredIncentives: (state,getters) =>{

    var conqueredIncentives = [];
/** 
 * 
 * Comentado para adaptaçãop da Campanha 12 *Rolette*
 *       state.incentives.forEach( incentive => {
        if(getters.getAmountIncentive > parseFloat(incentive.min_amount_order) && 
        getters.getTotalIncentiveQuantity > incentive.min_quantity ){
          conqueredIncentives.push(incentive);
        }
      });
       */

      state.incentives.forEach( incentive => {
        if(getters.distanceToGoal === 0){
          conqueredIncentives.push(incentive);
        }
      });

      return conqueredIncentives;
  },
  isPromotherInOtherOrder(state,getters, rootState, rootGetters){
       
    if(!rootGetters.isSalesConsultant){
      return false;
    }

    if(rootGetters.isPromoter &&  
         state.salesConsultantId !=   rootState.user.user.sales_consultant.id){
      return true;
    }

  return false;
 },

 /**
  * Código temporário para Atender a campanha 12
  */

  roletteGoal(state){

    if(state.resumeLastOrderValue >= 80 && state.resumeLastOrderValue <= 149.99){
      return state.resumeLastOrderValue + 20;
    }else if(state.resumeLastOrderValue >= 150 && state.resumeLastOrderValue <= 299.99){
      return state.resumeLastOrderValue + 30;
    }else if(state.resumeLastOrderValue >= 300 && state.resumeLastOrderValue <= 499.99){
      return state.resumeLastOrderValue + 45;
    }else if(state.resumeLastOrderValue >= 500 && state.resumeLastOrderValue <= 699.99){
      return state.resumeLastOrderValue + 60;
    }else if(state.resumeLastOrderValue >= 700 && state.resumeLastOrderValue <= 1499.99){
      return state.resumeLastOrderValue + 80;
    }else if(state.resumeLastOrderValue > 1500){
      return state.resumeLastOrderValue + 100;
    }

    return 200;

  },
  distanceToGoal: (state,getters) => {
    let distanceToGoal =  parseFloat(getters.roletteGoal)-parseFloat(getters.getMinOrderAmount);
    if(distanceToGoal < 0){
        return 0;
    }
return distanceToGoal;
}




}//fim do  export

/**
 * Funções auxiliares
 */
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;

  }


}