var shop2SmartSearch = new Vue({
  el: '#search-app',
  mixins: [VueClickaway.mixin],
  data: {
    search_query: "", // Строка поиска
    products: [], // Список продуктов
    foldersList: shop2SmartSearch.folders, // Список категорий
    vendorsList: shop2SmartSearch.vendors, // Список производителей
    img_w: shop2SmartSearch.img_width, // Ширина картинок
    img_h: shop2SmartSearch.img_height, // Высота картинок
    foundsProduct: 0, // Найдено продуктов
    foundsFolders: 0, // Найдено категорий
    foundsVendors: 0, // Найдено производителей
    limitProducts: shop2SmartSearch.limit_products, // Лимит на вывод товаров 
    foldersSearch: [], // Найденные категории
    vendorsSearch: [], // Найденные производители
    pagginationSearchList: [],
    windowWidth: window.innerWidth,
    resultMode: 0,
    resultType: '',
    resultToPage: 3,
    pageCount: 0,
    pageResultFounds: [],
    activePage: 1,
    activeTabs: {
    	products: false,
    	folders: false,
    	vendors: false
    },
    allResult: false
  },
  
  /*searchTr: function() {
    $('.shop-modules__search-input').oninput(function(){
    	console.log('123');
	  	$('.result-product .product-name').each(function(){
	  		var str = $(this).text();
	  		var re = search_query;
	  		var newstr = str.replace(re, 'search_query');
	  		console.log(newstr);
	  		$(this).text(newstr);
	  	});  	
  	});	
  },*/
  

  mounted: function() {
  	window.addEventListener('resize', this.handleWindowResize);
  },
  beforeDestroy: function () {
    window.removeEventListener('resize', this. handleWindowResize)
  },
  created: function() {
  	this.renderMode();
  	this.foldersList.shift();
  },
  methods: {
  	handleWindowResize: function(event) { 
  		this.windowWidth = event.currentTarget.innerWidth; 
  	},
  	setPagination: function(type) {
  		switch(type) {
  			case 'products':
  				this.changePage(1, 'products');
  				this.pageCount = Math.ceil(this.foundsProduct/this.resultToPage);
  				break;
  			case 'folders':
  				this.pageCount = Math.ceil(this.foundsFolders/this.resultToPage);
  				break;
  			case 'vendors':
  				this.pageCount = Math.ceil(this.foundsVendors/this.resultToPage);
  				break;
  		}
  	},
  	changePage: function(pageNum, type) {
  		var startRes = (pageNum - 1) * this.resultToPage;
  			switch(type) {
	  			case 'products':
	  				this.pageResultFounds = this.products.slice(startRes, startRes + this.resultToPage);
	  				break;
	  			case 'folders':
	  				this.pageResultFounds = this.foldersSearch.slice(startRes, startRes + this.resultToPage);
	  				break;
	  			case 'vendors':
	  				this.pageResultFounds = this.foldersSearch.slice(startRes, startRes + this.resultToPage);
	  				break;
	  		}
  			
  	},
  	renderMode: function() {
  		if (this.windowWidth>960) {
  			return 'desktop';
  		}
  		if (this.windowWidth<=960) {
  			return 'tab';
  		}
  		if (this.windowWidth<=767) {
  			return 'mobile';
  		}

  	},
  	renderType: function(type) {
  		this.resultMode = 1;
  		switch(type) {
  			case 'products':
  				this.setPagination('products');
  				this.resultType = 'products';
  				break;
  			case 'folders':
  				this.setPagination('folders');
  				this.resultType = 'folders';
  				break;
  			case 'vendors':
  				this.setPagination('vendors');
  				this.resultType = 'vendors';
  				break;
  		}
  	},
  	backPage: function() {
	  	this.resultMode = 0; 
	  	this.activePage = 1;
  	},
  	resetData: function() { // Cброс данных
	    this.resetDataProducts();
	    this.resetDataFolders();
	    this.resetDataVendors();
	    this.resetActiveTabs();
	    this.allResult = false;
  	},
  	resetActiveTabs: function() {
  		this.activeTabs.products = false;
  		this.activeTabs.folders = false;
  		this.activeTabs.vendors = false;
  	},
  	resetDataProducts: function() {
  		this.products = [];
  		this.foundsProduct = 0;
  	},
  	resetDataFolders: function() {
  		this.foldersSearch = [];
  		this.foundsFolders = 0;
  	},
  	resetDataVendors: function() {
  		this.vendorsSearch = [];
  		this.foundsVendors = 0;
  	},
  	searchStart: $.debounce(300,function() { // Стартовый запрос поиска
  		if (this.search_query == "" || this.search_query.length < 2) {
  			this.resetData();
  			return;
  		}
  		this.searchProductsQuery();
  		this.searchFoldersQuery();
  		this.searchVendorsQuery();
  	}),
  	searchProductsQuery: function() { // Запрос на поиск продуктов
  		
  		var imgQuery = "";
  		
  		if (this.img_w || this.img_h) {
  			imgQuery = '&img_width='+this.img_w+'&img_height='+this.img_h;
  		}
  		
  		fetch('/my/s3/xapi/public/?method=shop2/getProductsBySearchMatches&param[s][search_text]=' 
  			+ this.search_query 
  			+ '&param[template]=global:shop2.2.87-search-smart-list-product-heating-equipment-store.tpl'+imgQuery
  			+ '&param[limit]=' + this.limitProducts)
	    .then((response) => {
	        if(response.ok) {
	            return response.json();
	        }
	        throw new Error('Network response was not ok');
	    })
	    .then((json) => {
	        this.products = [];
	        
	        if (json.result.found == 0) {
	        	this.foundsProduct = 0;
	        	return;
	        }
	        var data = JSON.parse(json.result.html);
	        
	        this.foundsProduct = json.result.found;
	        
	        for(item in data) {
	        	this.products.push(data[item]);
	        }
	        this.visible_result = true;
	        
	    })
	    .catch((error) => {
	        console.log(error);
	    });
  	},
  	searchFoldersQuery: function() { // Запрос на поиск категорий
		var result = this.searchFolders(this.foldersList,this.search_query);
			if (this.addParentsToFolders(result,this.foldersList) != undefined) {
				this.foldersSearch = this.addParentsToFolders(result,this.foldersList);
			} else {
				this.foldersSearch = result;
			}
			
			this.foundsFolders = this.foldersSearch.length;
			
  	},
  	searchFolders: function(folders, text) { // Поиск категорий по ключевому слову
  		var matches = [],
			search_query = new RegExp($.trim(text),'i');
		
		for(item in folders) {
        	var is_match_name = folders[item].folder_name.match(search_query),
			   	is_match_alias = folders[item].alias.match(search_query);
				
				if (is_match_name || is_match_alias) {
					matches.push(folders[item]);
					folders[item].folder_name = folders[item].folder_name.replace(/&quot;/g, '\"');
				}
        }
		return matches;
  	},
  	addParentsToFolders: function(folders, all_folders) { // Поиск родительских категорий
		var result = [];

		for(item in folders) {
			
			if (folders[item]._level < 2) {
				return;
		 	}
		 	folders[item].parents = [];
			 	
			for(item_a in all_folders) {
				
				all_folders[item_a]._left = parseInt(all_folders[item_a]._left);
				all_folders[item_a]._right = parseInt(all_folders[item_a]._right);
				if (all_folders[item_a]._left < folders[item]._left && all_folders[item_a]._right > folders[item]._right) {
					folders[item].parents.push(all_folders[item_a]);
					
		 		}
		 	}
		 	result.push(folders[item]);
		}
		return result;
	},
	searchVendorsQuery: function() { // Запрос на поиск производителей
  		this.vendorsSearch = this.searchVendors(this.vendorsList,this.search_query);
  		this.foundsVendors = this.vendorsSearch.length;
	},
	searchVendors: function(vendors, text) { // Поиск производителей по ключевому слову
  		var matches = [],
			search_query = new RegExp($.trim(text),'i');
		
		for(item in vendors) {
        	var is_match_name = vendors[item].name.match(search_query),
			   	is_match_alias = vendors[item].alias.match(search_query);
				
				if (is_match_name || is_match_alias) {
					matches.push(vendors[item]);
				}
        }
		return matches;
  	}
  }
});