const { createApp } = Vue
createApp({
    data() {
      return {
        funnelId:funnelId,
        funnelName: '',
        triggerOn:'products',
        triggerOnType:'moreThan',
        location:'thankuPage',
        lineItemTitle:'',
        minValue:1,
        minQty:1,
        discountValue:10,
        discount:'percent',
        lanTitle:'Congrats!! 🎉 Special Discounts Unlocked! 🎁',// language Start
        lanSave:'Save',
        lanBuyNow:"Buy Now",
        lanFreeShipping:'Free Shipping',
        lanTimer:"Timer",
        lanFreeProduct:'Free Product',//language End
        desProBgColor:'#FFFFFF',
        desProBorderColor:'#FFFFFF',
        desBnBgColor:'#7367f0',
        desBnTextColor:'#FFFFFF',
        desDiscountPriceColor:'#000000',
        desPriceColor:'#DC143C',
        desHdTextColor:'#000000',
        desPrTextColor:'#000000',
        linkOfferTitle: true,
        hideOutOfStock: true,
        getProductsList:[],
        getSelectProductsList:[],
        selectedOfferProducts:[],
        selectedTriggerProducts:[],
        selectedCollections:[],
        selectedProducts:[],
        getProductsLink:{},
        getSelectProductsLink:{},
        offerProducts:[],
        productSearch:'',
        eligibility:false,
        loading:false,
        funnelStatus:false,
        position:"left",
        layoutType:"slider",
        layoutView:3,
        customCss:'',
        swiperSlider:''
      }
    },
  methods: {
      getProduct:function(data){
        var self=this
        self.getProductsList=[]
        self.loading=true
        $.ajax({
            type: 'POST',
            url: baseUrl+"admin/api/funnel/products"+window.location.search,
            data: {paging:data},
            dataType: "json",
            success: function(resultData) { 
              self.loading=false
              self.getProductsList=resultData.products
              self.getProductsLink=resultData.link
            }
        })
      }, 
      getSelectProduct:function(data){
        var self=this
        self.getSelectProductsList=[]
        self.loading=true
        $.ajax({
            type: 'POST',
            url: baseUrl+"admin/api/funnel/products"+window.location.search,
            data: {paging:data},
            dataType: "json",
            success: function(resultData) { 
              self.loading=false
              self.getSelectProductsList=resultData.products
              self.getSelectProductsLink=resultData.link
            }
        })
      }, 
      saveFunnel:function() {
        let saveFunnelData={
              funnelName: this.funnelName,
              triggerOn:  this.triggerOn,
              location:   this.location,
              minValue:   this.minValue,
              minQty:     this.minQty,
              discountValue:this.discountValue,
              discount:   this.discount,
              layoutType: this.layoutType,
              lanTitle:   this.lanTitle,
              lanSave:    this.lanSave,
              lanBuyNow:  this.lanBuyNow,
              lanFreeShipping: this.lanFreeShipping,
              lanTimer:   this.lanTimer,
              lanFreeProduct: this.lanFreeProduct,//language End
              desBnBgColor: this.desBnBgColor,
              desBnTextColor: this.desBnTextColor,
              desHdTextColor: this.desHdTextColor,
              desPrTextColor: this.desPrTextColor,
              desProBgColor:this.desProBgColor,
              desPriceColor:this.desPriceColor,
              desProBorderColor:this.desProBorderColor,
              desDiscountPriceColor:this.desDiscountPriceColor,
              customCss:this.customCss,
              funnelId:     this.funnelId,
               linkOfferTitle:this.linkOfferTitle,
              hideOutOfStock:this.hideOutOfStock,
              funnelStatus:this.funnelStatus,
              position:this.position,
              triggerOnType:this.triggerOnType,
              lineItemTitle:this.lineItemTitle,
              selectedTriggerProducts:this.selectedTriggerProducts,
              selectedOfferProducts:this.selectedOfferProducts
        }
        $.ajax({
            type: 'POST',
            url: baseUrl+"admin/api/funnel/save-settings"+window.location.search,
            data: saveFunnelData,
            dataType: "json",
            success: function(resultData) { 
              if(resultData.error){
                 shopifypushapp(resultData.msg,"warning");
              }else{
                  shopifypushapp(resultData.msg);
              }  
            }
        })
        
      },
      productSelect:function(e,id){
       
        let productIds=this.selectedOfferProducts;
        for( var i = 0; i < productIds.length; i++){ 
            if ( productIds[i].id === parseInt(id)) { 
                productIds.splice(i, 1); 
                this.offerProducts.splice(i,1);
            }
        } 

        if (e.target.checked) {
          this.getProductsList.forEach(item=>{
              if(parseInt(id)===item.id){
                 productIds.push(item)
                this.offerProducts.push(item.id)
              }
          })
        }  
        
        this.selectedOfferProducts=productIds
      },
      productSelectChecked:function(id){
        
        let checked =this.selectedOfferProducts.find(item=>(parseInt(id)==item.id));
        return (typeof checked=="object")?"checked":"";
      },
      productSelectTrigger:function(e){
        let productIds=this.selectedTriggerProducts;
         
        for( var i = 0; i < productIds.length; i++){ 
            if ( productIds[i].id === parseInt(e.target.value)) { 
                productIds.splice(i, 1); 
                this.selectedProducts.splice(i,1)
            }
        } 

        if (e.target.checked) {
          this.getSelectProductsList.forEach(item=>{
              if(parseInt(e.target.value)===item.id){
                  productIds.push(item)
                  this.selectedProducts.push(item.id)
              }
          })
          //productIds.push(e.target.value)
        }  
        this.selectedTriggerProducts=productIds
      },


      productRemoveSelectTrigger:function(index) {
        // body...
        let productIds=this.selectedTriggerProducts;
        productIds.splice(index, 1); 
        this.selectedProducts.splice(index,1)
        this.selectedTriggerProducts=productIds

      },
      productRemoveSelectOffer:function(index){
        this.selectedOfferProducts.splice(index,1)
        this.offerProducts.splice(index,1)
      },
      getFunnel(){
        let self= this;
          $.ajax({
            type: 'POST',
            url: baseUrl+"admin/api/funnel/get-funnel-details/"+this.funnelId+window.location.search,
            data: {},
            dataType: "json",
            success: function(resData) { 
                self.funnelName=resData.funnelName
                self.location=resData.location
                self.triggerOn=resData.triggerOn
                self.selectedTriggerProducts=(resData.recommendedProduct=="")?[]:resData.recommendedProduct
                // offer Data
                self.minQty=resData.offer.minQty
                self.minValue=resData.offer.minValue
                self.discount=resData.offer.discount
                self.discountValue=resData.offer.discountValue
                self.selectedOfferProducts=resData.offer.offerProduct
                // setting
                self.linkOfferTitle=(resData.settings.linkOfferTitle=="true")?true:false
                self.hideOutOfStock=resData.settings.hideOutOfStock=="true"?true:false
                // Design data
                self.desBnBgColor=resData.design.bnBgColor
                self.desBnTextColor=resData.design.bnTextColor
                self.desDiscountPriceColor=resData.design.discountPriceColor
                self.desHdTextColor=resData.design.hdTextColor
                self.desPrTextColor=resData.design.prTextColor
                self.desPriceColor=resData.design.priceColor
                self.desProBgColor=resData.design.proBgColor
                self.desProBorderColor=resData.design.proBorderColor
                // language
                self.lanSave=resData.language.save
                self.lanBuyNow=resData.language.buyNowButton
                self.lanFreeProduct=resData.language.freeProduct
                self.lanFreeShipping=resData.language.freeShipping
                self.lanTimer=resData.language.timer
                self.lanTitle=resData.language.title
                self.funnelStatus=(resData.status=="1")?true:false
                self.position=resData.position
                self.lineItemTitle=resData.productTitle
                self.triggerOnType=resData.triggerOnType
                self.customCss=resData.customCss
                //console.log(typeof resData.layout,"..",resData.layout);
                self.layoutType=( resData.layout==null)?'slider':resData.layout.type
                if(self.selectedOfferProducts.length>0){
                  
                    self.selectedOfferProducts.forEach(item=>{
                      self.offerProducts.push(item.id);
                    })
                    // console.log(self.offerProducts)
                }

                if(self.selectedTriggerProducts.length>0){
                    self.selectedTriggerProducts.forEach(item=>{
                      self.selectedProducts.push(item.id);
                    })
                }
                // console.log("..",self.layoutType)
                if(self.layoutType=="slider"){
                  self.sliderReconvert();
                }else if(self.layoutType=="grid"){
                  // console.log('..')
                  self.gridReconvert();
                }
              }
          })
      },
      discountType:function($val){
        if(this.discount=="percent"){
          return this.discountPercent($val);
        }else if(this.discount=="fixed"){
          return this.discountFix($val);
        }else{
          return $val;  
        }
        
      },
      discountPercent:function($val){
        let price = $val- ($val * (this.discountValue / 100));
          return price.toFixed(2)
      },
      discountFix:function($val){
        let price = $val- this.discountValue; 
        return price.toFixed(2)
      },
      changeViews:function(e){
        // console.log("E...",this.layoutView); 
      },
      sliderReconvert:function(){
        let layoutView =this.layoutView
        setTimeout(function(){
          // console.log("111...",layoutView)
          let swiperSlider = new Swiper(".reconvertSwiper", {
         
            speed: 400,
				    spaceBetween: 100,
				    initialSlide: 0,
				    //truewrapper adoptsheight of active slide
				    autoHeight: true,
				    // Optional parameters
				    direction: 'horizontal',
				    loop: true,
				    // delay between transitions in ms
				    autoplay: false,
				    autoplayStopOnLast: false, // loop false also
				    // If we need pagination
				    pagination: '.swiper-pagination',
				    paginationType: "bullets",
				    
				    // Navigation arrows
				    navigation: {
			          nextEl: ".swiper-button-next",
			          prevEl: ".swiper-button-prev",
			        },
				    
				    // And if we need scrollbar
				    //scrollbar: '.swiper-scrollbar',
				    // "slide", "fade", "cube", "coverflow" or "flip"
				    effect: 'slide',
				    // Distance between slides in px.
				    spaceBetween: 20,
				    //
				    slidesPerView: layoutView,
				    //
				    centeredSlides: false,
				    //
				    slidesOffsetBefore: 0,
				    //
				    grabCursor: true,
           
          });
          // console.log("swiperSlider....",swiperSlider)
        },1000)
          
      },
      gridReconvert:function(){
        // console.log("swiperSlider....",swiperSlider)
      },
      offerProductResourcePicker:function(){
        const productPicker = ResourcePicker.create(app, {
          resourceType: ResourcePicker.ResourceType.Product,
        });
      }

  },
  // Lifecycle hooks are called at different stages
  // of a component's lifecycle.
  // This function will be called when the component is mounted.
  mounted() {
    //this.increment();
    if(this.funnelId){
      this.getFunnel();
    }
    
    // if(!this.funnelId){
    //   console.log("...",this.funnelId);
    //   this.sliderReconvert();
    // }
    //this.sliderReconvert();
    this.getProduct('')
    this.getSelectProduct('')
     
   }
 }).mount('#funnesl_setting')
