//CHARGEMENT DE LA PAGE
function init_plugin_import(){
	switch($.urlParam('page')){
		case 'sheet.import':
			$('#file').change(function(){

				import_save(function(){
					if($('.plugin-import').attr('data-mode') != 'configure') return;
					import_template_setting();
				},true);
			});

			if($('.plugin-import').attr('data-mode') == 'configure'){
				import_template_setting(function(){
					import_mapping_search();
				});
			}

		break;
		default:
		break;
	}
	$('#imports').sortable_table({
		onSort : import_search
	});
}




function import_template_setting(callback){
	var id = $.urlParam('id');
	if(!id) return;
	$.action({
		action : 'import_template_setting',
		import : id,
	},function(response){

		/*var columns ='';
		for(var k in response.headers){
			var column = response.headers[k];
			columns+='<option value="'+column.value+'">'+column.value+'</option>';
		}
		columns+='<option value="fixed">Valeur fixe</option>';
		$('select[data-id="excelColumn"]').html(columns);*/
		$('#template-settings').html(response.form);
		if(callback) callback();
	});
}

//Enregistrement des configurations
function import_setting_save(){
	$.action({
		action: 'import_setting_save',
		fields:  $('#import-setting-form').toJson()
	},function(){
		$.message('success','Enregistré');
	});
}

/** IMPORT **/
//Récuperation d'une liste  import dans le tableau #imports
function import_search(callback,exportMode){
	var box = new FilterBox('#import-filters');
	if(exportMode) $('.btn-export').addClass('btn-preloader');

	$('#imports').fill({
		action:'import_search',
		filters: box.filters(),
		sort: $('#imports').sortable_table('get'),
		export:  !exportMode ? false : exportMode
	},function(response){
		if(!exportMode) $('.results-count > span').text(response.pagination.total);
		if(callback!=null) callback();
	});
}

//Ajout ou modification import
function import_save(callback){
	var data = $('#import-form').toJson();

	data.meta = $('#template-settings').toJson();

	$.action(data,function(r){
		$('#import-form').attr('data-id',r.id);
		$.urlParam('id',r.id);

		init_components('.file-container');
		if(callback) callback();
	});
}


//Suppression import
function import_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer cet item ?')) return;
	var line = $(element).closest('.item-line');
	$.action({
		action: 'import_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Item supprimé');
	});
}


/** LINE D\'IMPORT MAPPéE **/


function import_mapping_deduction(){
	var id = $.urlParam('id');

	if(!id || !entity) return $.message('warning','Entitée ou excel non renseigné');


	$('.btn-import-deduction').addClass('btn-preloader');
	$.action({
		action:'import_mapping_deduction',
		id: id
	},function(response){
		import_mapping_search();
		$.message('success',response.excelCount+' Champs excel trouvés, '+response.entityCount+' associations erp déduites');
	});

}

function import_excel_infos(callback){
	var id = $.urlParam('id');

	$.action({
		action:'import_excel_infos',
		id: id
	},function(response){
		if(callback) callback();
	});

}

function import_mapping_fixed_change(element){
	var fixedValue =  $(element).closest('.import-label-column').find('.excelColumnFixedValue');
	fixedValue.toggleClass('hidden',!$(element).prop('checked'));
	if(!$(element).prop('checked')) fixedValue.val('');
	import_mapping_save(element);
}

//Récuperation d'une liste  line d\'import mappée dans le tableau #importmappings
function import_mapping_search(callback){
	var id = $.urlParam('id');
	var entity = $('#entity').val();
	if(!id || !entity) return;

	$('.entityField').html('');
	$.action({
		action : 'core_entity_attribute_search',
		path : entity
	},function(response){
		var html = '<option value="">-</option>';
		var subhtml = '';
		for(var k in response.fields){
			var field = response.fields[k];
			html += '<option '+(field.childs?'data-link':'')+' value="'+field.column+'">'+field.label+'</option>';
			//si l'attribut et lié a une autre entité, on stock les attributs de cette autre entitée en tableau global pour réutilisation dans import_check_foreign_attribute
			if(field.childs  && field.entity !='Dictionary'){

				if(!window.importLinks ) window.importLinks = {};
				window.importLinks[field.column] = field.childs;
			}
		}

		html+= '<option value="otherEntity">Autre donnée</option>';

		$('.entityField').html(html);

		$.action({
			action:'import_mapping_search',
			id: id
		},function(response){
			$('#import-mappings tbody tr:not(:eq(0))').remove();
			var tpl = $('#import-mappings tbody tr:eq(0)').get(0).outerHTML.replace(/data-tpl-type/g,'data-type');

			for(var k in response.rows){
				var line = $(Mustache.render(tpl,response.rows[k]));
				line.removeClass('hidden');
				$('#import-mappings').append(line);
				line.fromJson(response.rows[k]);


				import_check_foreign_attribute(line.find('.entityField'));
				line.find('.entitySubField').val(response.rows[k].entitySubField);

				if(response.rows[k].entityRelatedField){
					line.find('.entityRelatedField,.entityRelated').removeClass('hidden');
					import_entity_related_change(line.find('.entityRelated'));
				}

				if(response.rows[k].excelColumnFixedValue){

					line.find('.fixedValueCheckbox').prop('checked',true);
					line.find('[data-id="excelColumnFixedValue"]').removeClass('hidden');
				}
				init_components(line);
			}

			if(callback!=null) callback();
		});
	});


}

function import_entity_field_change(element){
	var select = $(element);
	var line = $(select).closest('tr');

	if(select.val() == 'otherEntity'){
		var related = line.find('.entityRelated');
		related.attr('data-type',related.attr('data-tpl-type')).removeClass('hidden');
		init_components(line);
		related.change(function(){
			import_entity_related_change(related);
		});
	}else{
		import_check_foreign_attribute(element);
	}
	import_mapping_save(element);
}

function import_entity_related_change(related){
	var line = related.closest('tr');
	$.action({
		action : 'core_entity_attribute_search',
		path : related.val()
	},function(response){
		var relatedField = line.find('.entityRelatedField');
		relatedField.attr('data-type',relatedField.attr('data-tpl-type')).removeClass('hidden');
		var values = {};

		for (var k in response.fields) {
			var field = response.fields[k];

			values[field.column] = {id :k, label : field.label};
			if(field.childs){
				values[field.column].childs = {};
				for (var u in field.childs) {
					var child =  field.childs[u];
					child.id = k+'.'+u;
					values[field.column].childs[child.column] = child;
				}
			}
		}

		relatedField.attr('data-values',JSON.stringify(values))
		init_components(line);
	});
}

//Lors de la selection d'un attirbut d'entité, vérifie qu'il n'existe pas
// d'entité liée, si c'est le cas, ça affiche ses attributs en sous liste
function import_check_foreign_attribute(element){
	var select = $(element);
	var line = $(select).closest('tr');

	if(!select.find('option:selected').hasAttr('data-link')){
		line.find('.entitySubField').addClass('hidden');
		return;
	}
	var html = '';
	if(!window.importLinks || !window.importLinks[select.val()]) return;
	var childs = window.importLinks[select.val()];
	for(var k in childs){
		var field = childs[k];
		html += '<option value="'+field.column+'">'+field.label+'</option>';
	}
	line.find('.entitySubField').removeClass('hidden').html(html);
}


//Ajout ou modification line d\'import mappée
function import_mapping_save(element){
	var data = $(element).closest('tr').toJson();
	data.action = 'import_mapping_save';
	data.import = $.urlParam('id');
	$.action(data,function(r){
		$.message('success','Enregistré');
	});
}

function import_mapping_add(){
	var data = {action:'import_mapping_save'};
	data.import = $.urlParam('id');
	$.action(data,function(r){
		import_mapping_search();
	});
}

//Récuperation ou edition line d\'import mappée
function import_mapping_edit(element){
	var line = $(element).closest('.item-line');

	$.action({
		action: 'import_mapping_edit',
		id: line.attr('data-id')
	},function(r){
		$('#import-mapping-form').fromJson(r);
		init_components('#import-mapping-form');
		$('#import-mapping-form').attr('data-id',r.id);
	});
}

//Suppression line d\'import mappée
function import_mapping_delete(element){



	if(!confirm('Êtes vous sûr de vouloir supprimer cet/ces item(s) ?')) return;

	if(element!='all'){
		var line = $(element).closest('.item-line');
		var id = line.attr('data-id');
	}else{
		id = element;
	}

	$.action({
		action: 'import_mapping_delete',
		id: id,
		import: $.urlParam('id'),
	},function(r){
		if(line){
			line.remove();
		}else{
			$('#import-mappings .item-line:not(:eq(0))').remove();
		}
		$.message('info','Item(s) supprimé(s)');
	});
}

function import_execute(){
	$('.btn-import').addClass('btn-preloader');
	$.action({
		action : 'import_execute',
		id : $.urlParam('id')
	},function(r){

		$.message('info','Import terminé');

		var statsList = $('.import-stats-list');
		statsList.find('>li').remove();;
		var statsListTemplate = $('template',statsList).html();
		for(var slug in r.stats){
			var line = $(Mustache.render(statsListTemplate,r.stats[slug]));
			statsList.append(line);
		}

		$('.import-excel-table-container').removeClass('hidden');

		var table = $('.import-excel-table');

		if(r.stats.imported == r.stats.total){
			table.addClass('hidden');
		}else{
			table.removeClass('hidden');
		}


		table.find('.title-head tr th').html(r.fileName);


		var columnTemplate = $('thead template',table).html();
		var lineTemplate = $('tbody template:eq(0)',table).html();
		var columnsTemplate = $('tbody template:eq(1)',table).html();

		$('thead:eq(0) tr th',table).attr('colspan',r.columns.length+1);

		for(var i in r.columns){
			$('thead:eq(1) tr',table).append($(Mustache.render(columnTemplate,r.columns[i])));
		}

		table.find('.title-head tr th').attr("colspan",$('thead:eq(1) tr th',table).length);

		for(var i in r.lines){
			var line = r.lines[i];
			line.lineNumber = i;
			var tr = $(Mustache.render(lineTemplate,line));

			for(var u in line.columns){
				var td = $(Mustache.render(columnsTemplate,line.columns[u]));
				tr.append(td);
			}

			$('tbody',table).append(tr);
		}

		init_components($('#file').parent());

	});
}