// let funnelSettings= new Vue({
// 	el: "#funnesl_setting",
// 	data(){
// 		return{
// 			funnelName:""
// 		}
// 	}

// })

const { createApp } = Vue
createApp({
    data() {
      return {
        funnelId:funnelId,
        funnelName: '',
        triggerOn:'products',
        location:'postPurches',
        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
        lanDecline:'Decline this offer',
        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",

      }
    },
  // Methods are functions that mutate state and trigger updates.
  // They can be bound as event listeners in templates.
  methods: {
      clearFiled:function(){
        if(this.productSearch!=""){
          this.productSearch=""; 
             this.getProduct("");  
              this.getSelectProduct(""); 
        }
        

      },
      searchForGetProduct:function(){
          this.getProduct("",this.productSearch); 
      },
      searchForGetSelectProduct:function(){
        this.getSelectProduct("",this.productSearch); 
      },
      getProduct:function(data,search=''){
        var self=this
        self.getProductsList=[]
        self.loading=true
        $.ajax({
            type: 'POST',
            url: baseUrl+"admin/api/funnel/products"+window.location.search,
            data: {paging:data,search:search},
            dataType: "json",
            success: function(resultData) { 
              self.loading=false
              self.getProductsList=resultData.products
              self.getProductsLink=resultData.link
            }
        })
      }, 
      getSelectProduct:function(data,search=''){
        var self=this
        self.getSelectProductsList=[]
        self.loading=true
        $.ajax({
            type: 'POST',
            url: baseUrl+"admin/api/funnel/products"+window.location.search,
            data: {paging:data,search:search},
            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,
              lanTitle:   this.lanTitle,
              lanSave:    this.lanSave,
              lanBuyNow:  this.lanBuyNow,
              lanFreeShipping: this.lanFreeShipping,
              lanTimer:   this.lanTimer,
              lanFreeProduct: this.lanFreeProduct,//language End
              lanDecline:this.lanDecline,
              desBnBgColor: this.desBnBgColor,
              desBnTextColor: this.desBnTextColor,
              desHdTextColor: this.desHdTextColor,
              desPrTextColor: this.desPrTextColor,
              desProBgColor:this.desProBgColor,
              desPriceColor:this.desPriceColor,
              desProBorderColor:this.desProBorderColor,
              desDiscountPriceColor:this.desDiscountPriceColor,
              funnelId:     this.funnelId,
               linkOfferTitle:this.linkOfferTitle,
              hideOutOfStock:this.hideOutOfStock,
              funnelStatus:this.funnelStatus,
              selectedTriggerProducts:this.selectedTriggerProducts,
              selectedOfferProducts:this.selectedOfferProducts,
               position:this.position
        }

        $.ajax({
            type: 'POST',
            url: baseUrl+"admin/api/funnel/save"+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);
            }
        } 
        let productLength=10;
        if(this.location=="postPurches"){
          productLength=2;
        }
        console.log(this.location,'...',productLength)
        if (e.target.checked) {
          if(this.offerProducts.length>=productLength){
            let msgOf= (this.location=="postPurches")?'Max. 2 products can be added':'Max. 10 products can be added'
            e.target.checked=false;
            shopifypushapp(msgOf,"warning");
            return;
          }
          this.getProductsList.forEach(item=>{
              if(parseInt(id)===item.id){
                 productIds.push(item)
                this.offerProducts.push(item.id)
              }
          })
          //productIds.push(e.target.value)
        }  
        
        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)
              }
          })
          
        }  
        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.lanDecline=(typeof resData.language.decline !='undefined')?resData.language.decline:self.lanDecline
                console.log(typeof resData.language.decline !='undefined' ,'...',self.lanDecline)
                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
                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);
                    })
                }
                
            }
          })
      },
      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)
      },
      productResourcePicker:function(typeofPicker){
        
        let self=this;
       
        let selectedProducts=[];
        if(typeofPicker=='product' && self.selectedTriggerProducts.length>0){
          self.selectedTriggerProducts.forEach(item=>{
            selectedProducts.push({ id: 'gid://shopify/Product/'+item.id})
          })
        }else if(typeofPicker=='offer' && self.selectedOfferProducts.length>0){
         
          self.selectedOfferProducts.forEach(item=>{
            selectedProducts.push({ id: 'gid://shopify/Product/'+item.id})
          })
         
        }
        let productLength=2
        if(self.location !="postPurches"){
          productLength=10;
        }
        /*console.log("...productLength....",productLength)
          const selected =  shopify.resourcePicker({
            type: 'product',
            action: 'select',
            selectionIds:selectedProducts,
            multiple: productLength,
            filter: {
              hidden: false,
              variants: false,
            },
            onSelection:function(){
              console.log('....')
            }
          });

          if (selected) {
            console.log(selected);

          } else {
            console.log('Picker was cancelled by the user');
          }
           selected.dispatch("Resource_Picker.open");
        selected.subscribe("Resource_Picker.select", ({selection}) => {
          
            console.log(k);
          })*/
        const productPicker = ResourcePicker.create(app, {
            resourceType: ResourcePicker.ResourceType.Product,
            options: {
              selectMultiple: productLength,
              showHidden: false,
              showVariants:false,
              initialSelectionIds:selectedProducts,
              
  
            },
          });
      
        productPicker.dispatch(ResourcePicker.Action.OPEN);
        productPicker.subscribe(ResourcePicker.Action.SELECT, ({selection}) => {
          // Do something with `selection`
            //const selection = selectPayload.selection;
          self.selectedProductsByOffer(selection,typeofPicker)
            // console.log("selection...",selectPayload.selection)
        });
         productPicker.subscribe(ResourcePicker.Action.CANCEL, () => {
          // Picker was cancelled
         
        });
       
      },
      selectedProductsByOffer(ids,typeofPicker){
        
          // let products=this.selectedOfferProducts;
        let products=[]
        let   productsIds=[]
          ids.forEach(item=>{
            let itemProudct={
              id:item.id.replace("gid://shopify/Product/",""),
              handle:item.title,
              title:item.handle,
              images:[{id:item.images[0].id.replace("gid://shopify/ProductImage/",""),src:item.images[0].originalSrc}],
              variants:item.variants
            }
            products.push(itemProudct)
            productsIds.push(item.id.replace("gid://shopify/Product/",""));
          })
          if(typeofPicker=='offer'){
            this.selectedOfferProducts=products
            this.offerProducts=productsIds
          }else{
            this.selectedTriggerProducts=products
          }
      }
  },

  // 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();
    }
    this.getProduct('')
    this.getSelectProduct('')
    
   
  }
 }).mount('#funnesl_setting')
