//CHARGEMENT DE LA PAGE
function init_plugin_client(){
	switch($.urlParam('page')){
		case 'sheet.client':
			//Convertit les téléphones en lien appellable si on est sur mobile
			if(is_phone()) $('[data-type="phone-text"]').replaceWith(function(i,text){
				return '<a href="tel:'+text+'">'+text+'</a>';
			});
			client_contact_search();
			client_address_search(client_tab_refresh);
			client_relation_search();

			window.onhashchange = function(event){
				client_tab_refresh();
			};

			client_image_edit('.client-summary-panel .client-thumbnail','cover-thumbnail');
		break;
		default:

		break;
	}



	$(document).click(function(){
		$('#client-api .dropdown-menu').hide();
	});


}

function client_import(){
	var data = $('.client-setting-form').toJson();
	data.action = 'client_import';
	$.action(data,function(){
		$.message('success','Importé');
	});
}

function client_switch_pseudonym(value){

	if(value){
		$('.block-label').addClass('hidden');
		$('.block-pseudonym').removeClass('hidden');
	}else{
		$('.block-pseudonym').addClass('hidden');
		$('.block-label').removeClass('hidden');
	}
}

function client_tab_refresh(){
	var tab = $.hashData('tab');
	tab = tab == '' ? 'home': tab;

	$('.client-menu-bar ul li').removeClass('active');
	$('.client-menu-bar ul li[data-slug="'+tab+'"]').addClass('active');
	$('.client-content-page').load('action.php?action=client_tab_load&tab='+tab+'&id='+$('.client-container').attr('data-id'),function(){
	init_components('.client-content-page');
	var init = 'client_tab_init_'+tab;
	init = init.replace(/[^a-z_0-9]/g,'_');
	if(window[init]!=null) window[init]($.urlParam());

	});
}

function client_tab_init_home(){
	client_type_change();
	client_live_update();
	client_image_edit('.client-form .client-thumbnail','logo-thumbnail');
	client_address_change();
}

function client_image_edit(element,fileId){
	var element = $(element);
	element.addClass('client-image-edit');
	var input = $('<input type="file" id="'+fileId+'" class="hidden">');
	var button = $('<div class="client-image-edit-button editable-only"><i class="fas fa-pencil-alt"></i></div>');

	element.append(button);
	element.after(input);

	if(	$('.client-container').attr('data-editable') =='0'	) return;
	element.click(function(){
		input.change(function(){
			var reader = new FileReader();
			reader.onload = function (e) {
				element.attr('style','background-image: url('+e.target.result+');background-color:#efefef;');
			}
			reader.readAsDataURL(input.get(0).files[0]);
		});
		input.click();
	});

}

function client_name_change(){


	var label = $('#label');

	var fullName = $('#firstname').val()+' '+$('#name').val().toUpperCase();
	label.val(fullName).keyup();

}

function client_type_change(){
	var value = $('.type-choice input:checked').val();
	$('.client-container').attr('data-client-type',value);
	client_address_change();
}

function client_address_change(element){
	client_update_map_size();

	if(!$('.client-form').hasClass('client-form-map') || !$('#addresses li:not(.hidden)').length) return;

	var element = element!=null ? $(element) : $('#addresses li[data-type="global"]');
	element = element.length ? element : $('#addresses li:not(.hidden)').first();
	var address = element.data();
	var addressLabel = address.street+' '+address.city+', '+address.zip;

	var url = "https://maps.google.com/maps?q="+encodeURI(addressLabel) +"&t=&z=13&ie=UTF8&iwloc=&output=embed";
	$('#gmap_canvas').attr('src', url);

	if(address && !is_empty_obj(address))
		$('.client-city span').text(address.city+' ('+address.zip+')')
}

function client_toggle_more_fields(element){
	$('#more-fields-container').toggleClass('hidden');

	if(element!=null) $(element).find('i').toggleClass('fa-chevron-down').toggleClass('fa-chevron-up');

	client_update_map_size();
}

function client_live_update(){
	$('[data-live-update]').each(function(){
		var tag = $(this);
		var selector = tag.attr('data-live-update');
		$(selector).on('keyup',function(){
			tag.text($(selector).val());
		}).keyup();
	});
}


function client_internet_modal(){

	$('#client-internet-modal').modal('show');
	client_api_search();
}

function client_api_search(){
	var label = $('#label').val();
	if(!label) return $.message('warning','Vous devez remplir le libellé pour lancer une recherche');

	var choices = $('#client-internet-modal .choices');

	var city = $('.client-city').attr('data-city');
	var zip = $('.client-city').attr('data-zip');

	$('#client-internet-modal .modal-preloader').addClass('btn-preloader');

	$('#client-internet-modal .choices').fill({
		action: 'client_api_search',
		label:  label
	},function(r){
		for(var k in r.rows){
			var row = r.rows[k];
			var li = $('#client-internet-modal .choices li:eq('+(parseInt(k) + 1)+')');
			if( (city && row.city.indexOf(city) !== -1) || (zip && row.zip == zip) ) li.find('h5').addClass('text-warning');
			li.data('infos',row);
		}
		$('#client-internet-modal .modal-preloader').removeClass('btn-preloader');
	});

}

function client_api_load(li){
	var li = $(li);
	var infos = li.data('infos');
	$('#label').val(infos.label);
	$('#job').val(infos.job);
	$('#siret').val(infos.siret);

	var comment = $('#comment').val();
	if(comment) comment+'\n';
	$('#comment').val(comment+"Taille : "+infos.size+' - (environ '+infos.employees+' employés'+"\n"+infos.status+" - SIREN : "+infos.siren+"\n"+" Société fondée le : "+infos.created);

	$('#client-internet-modal').modal('hide');

	client_client_save(function(client){
		client_address_save({
			"type": "global",
			"street": infos.street,
			"complement": "",
			"city": infos.city,
			"zip": infos.zip,
			"country": "France"
		},function(){
			$.message('success','Informations intégrées à la fiche client');
		},true);
	},true);


}

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


/** CLIENT **/
//Récuperation d'une liste de client dans le tableau #clients
function client_client_search(options){

	options = !options ? {} : options;

	var box = new FilterBox('#filters');
	if(options && options.exportMode) $('.btn-export').addClass('btn-preloader');

	var searchTable = $('#clients').data('searchTable');
	searchTable.resetGlobalCheckbox();
	if(!options.keepChecked) searchTable.resetCheckbox();

	$('#clients').fill({
		action:'client_client_search',
		filters: box.filters(),
		sort: $('#clients').sortable_table('get'),
		firm: $.urlParam('firm'),
		export:  !options.exportMode ? false : options.exportMode,
		selected : searchTable.checkboxes()
	},function(response){
		if(!options.exportMode) $('.results-count > span').text(response.pagination.total);

		searchTable.fillCheckbox();

		if(options.callback!=null) options.callback(response);
		init_components();
	});
}


function client_client_mail_copy(){

	$.action({
		action : 'client_client_mail_copy',
		ids : $('#clients').data('searchTable').checkboxes()
	},function(r){
		copy_string(r.mails.join(';'));
		$.message('success',r.mails.length+' e-mail copiés');
	});
}


function client_relation_search(callback){
	$('#holding').html('');
	$('#subsites').fill({
		action:'client_relation_search',
		client: $.urlParam('id'),
		showing:function(line,key,data){

			if(data.level == 'holding'){
				$('#holding').append(line.detach());
			}else if(data.level =='memberof'){
				$('#memberof').append(line.detach());
			}


			line.removeClass('hidden');
		}
	},function(response){
		var count = $('#subsites .site-block:visible').length;
		$('.client-subsite-count').text(count>0?'('+count+') ':'');
		if(callback!=null) callback();
	});
}


function client_relation_add(modal){
	var site =  $.urlParam('id');
	if(!modal){
		$.action({
			action : 'client_relation_add',
			relation : $('#relation-link').val(),
			id : site,
			level : $('[name="relation-level"]:checked').val()
		},function(r){
			client_relation_search();
		});
		$('#client-holding-modal').modal('hide');
	}else{
		if(!site) return $.message('error','Vous ne pouvez lié le client qu\'une fois celui çi enregistré');
		$('#client-holding-modal').modal('show');
	}
}

function client_relation_delete(element){
	var line =  $(element).closest('.site-block');
	if(!confirm('Êtes-vous sûr de vouloir supprimer cette relation ?')) return;
	$.action({
		action : 'client_relation_delete',
		relation : line.attr('data-id'),
		id : $.urlParam('id'),
		level : line.attr('data-level')
	},function(r){
		line.remove();
	});
	$('#client-holding-modal').modal('hide');

}

//Ajout ou modification d'élément client
function client_client_save(callback,noMessage){
	var data = $('#client-form').toJson();

	data.type = $('input[name="type"]:checked').val();

	$('#client-form input[type="radio"]:checked').each(function(i,element){
		data[$(element).attr('name')] = $(element).attr('value');
	});
	$('#client-form input[type="checkbox"]').each(function(i,element){
		data[$(element).attr('id')] = $(element).prop('checked') ? 1 : 0;
	});

	data.address = $('#address').data();
	data.id = $('.client-container').attr('data-id');
	data.logo = $('#logo-thumbnail').get(0).files[0];
	data.cover = $('#cover-thumbnail').get(0).files[0];

	data.parent = $.urlParam('parent');

	$.action(data,function(r){
		$.urlParam('id',r.id)
		$('.client-container').attr('data-id',r.id);
		if(callback) callback(r);
		if(!noMessage) $.message('success','Enregistré');
	});

}


//Fusion d'un client avec un autre (modale)
function client_client_merge_edit(){
	$('#client-merge-modal').modal('show');
	$('.btn-merge').removeClass('hidden');
}

//Fusion d'un client avec un autre (execution)
function client_client_merge(){
	if(!confirm('Êtes-vous sûr de vouloir fusionner ces clients ? Cette opération est irréversible')) return;
	$('.btn-merge').addClass('hidden');
	var data = { action : 'client_client_merge'};
	data.left = $('.client-container').attr('data-id');
	data.right = $('#client-merge-right').val();
	data.keep = {};

	$('#client-merge-modal input[type="radio"]:checked').each(function(){
		data.keep[$(this).attr('data-key')] = $(this).val();
	});

	$.action(data,function(r){
		$('#client-merge-modal .merge-logs').html(r.logs.join('<br>'));
		$.message('success','Client fusionné');
	});
}

//Vérification des doublons
function client_client_check_duplicate(element){
	element = $(element);

	$.action({
		action : 'client_client_check_duplicate',
		field : element.attr('id'),
		label : element.val(),
		id : $('#client-form').attr('data-id')
	},function(r){

		var clientWarning = $('.client-warning',element.parent());
		if(clientWarning.length==0){
			clientWarning = $('<a class="input-group-append hidden client-warning" data-tooltip> \
					<span class="btn pr-0"><i class="fas fa-exclamation-circle text-warning"></i></span></a>');
			element.after(clientWarning);
		}

		var filters = {"k":"","a":[]}
		if(r.rows.length>0){

			var title = r.rows.length+' client(s) existant(s) montre(nt) des similarités avec ce champ'+"<br>";
			for(var k in r.rows){
				var row = r.rows[k];
				var filter = {"t":"number","c":"main.id","o":"=","v":[row.id]};
				if(k != r.rows.length-1) filter.j = "or";
				filters.a.push(filter);
				title += '- '+row.label+' (#'+row.id+')'+"<br>";
			}
			var url = 'index.php?module=client&p=1&filters='+btoa(JSON.stringify(filters));
			clientWarning.removeClass('hidden').attr('title',title).attr('href',url);
			init_components(clientWarning.parent());
		}else{
			clientWarning.addClass('hidden');
		}
	});
}

//Suppression d'élement client
function client_client_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer ce client ?')) return;

	var recursive = confirm('Voulez vous supprimer également les sous entreprises de ce client ?');
	var line = element ? $(element).closest('tr') : null;
	var id = line ? line.attr('data-id') : $.urlParam('id');

	$.action({
		action: 'client_client_delete',
		id: id,
		recursive : recursive ?1:0
	},function(r){
		if(line){
			client_client_search();
			$.message('success','Client supprimé');
		}else{
			window.location = 'index.php?module=client&success=Client%20supprimé';
		}
	});
}


/** CLIENTCONTACT **/
//Récuperation d'une liste de clientcontact dans le tableau #clientcontacts
function client_contact_search(callback,exportMode){

	$.action({
		action:'client_contact_search',
		client: $.urlParam('id')
	},function(response){
		var tpl = $('.client-contact-panel .contact-template').get(0).outerHTML;
		$('#internals li:visible,#contacts li:visible').remove();
		var stats  = {contacts :0,internals :0,}
		for (var k in response.rows) {
			var data = response.rows[k];
			var li = $(Mustache.render(tpl,data));
			li.removeClass('hidden');
			if(data.type=='user'){
				$('#internals').append(li);
				stats.internals++;
			}else{
				$('#contacts').append(li);
				stats.contacts++;
			}
		}
		$('.internals-title span').text(stats.internals);
		$('.contacts-title span').text(stats.contacts);
	});

}

function client_contact_mobile_toggle(){
	$('.client-contact-panel').toggle();
	client_update_map_size();
}

//Ajout ou modification d'élément clientcontact
function client_contact_save(){
	var data = $('#contactModal').toJson();
	data.action = 'client_contact_save';
	data.client = $.urlParam('id');
	data.id = $('#contactModal').attr('data-id');

	data.account = $('#contactModal .contact-type-block:not(.hidden) [data-id="account"]').val();
	data.job = data['contact-job'];
	data.comment = data['contact-comment'];
	data.mail = data['contact-mail'];
	data.phone = data['contact-phone'];
	data.mobile = data['contact-mobile'];
	data.type = $('[name="contact-type"]:checked').attr('data-value');

	$.action(data,function(r){
		$.message('success','Enregistré');
		$('#contactModal').clear().modal('hide');
		client_contact_search();
	});
}
function client_contact_edit(element){
	var id = element ? $(element).closest('li').attr('data-id'): null;
	var modal = $('#contactModal');
	modal.clear();

	$.action({
		action: 'client_contact_edit',
		id: id
	},function(r){
		r['contact-job'] = r.job;
		r['contact-comment'] = r.comment;
		r['contact-phone'] = r.phone;
		r['contact-mobile'] = r.mobile;
		r['contact-mail'] = r.mail;
		$.setForm('#contactModal',r);

		$('#civility option[value="'+r.civility+'"]').prop('selected',true);

		modal.modal('show');
		modal.attr('data-id',r.id);

		if(!r.type) r.type = 'external';
		$('[name="contact-type"][data-value="'+r.type+'"]').click();

		client_contact_type();
		init_components('#contactModal');
	});
}

//Suppression d'élement clientcontact
function client_contact_delete(element){
	if(!confirm('Êtes vous sûr de vouloir supprimer ce contact ?')) return;
	var line = $(element).closest('li');

	$.action({
		action: 'client_contact_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Contact supprimé');
	});
}

function client_contact_type(){

	$('.contact-type-block').addClass('hidden');

	switch($('[name="contact-type"]:checked').attr('data-value')){
		case 'external':
			$('.external-type-block').removeClass('hidden');
		break;
		case 'client':
			$('.client-type-block').removeClass('hidden');
		break;
		case 'user':
			$('.user-type-block').removeClass('hidden');
		break;
	}

}

//Gestion des adresses

function client_address_search(callback,exportMode){
	$.action({
		action:'client_address_search',
		client: $.urlParam('id')
	},function(response){
		var tpl = $('.client-contact-panel .address.hidden').get(0).outerHTML;
		$('#addresses li:visible').remove();

		for (var k in response.rows) {
			var data = response.rows[k];
			var li = $(Mustache.render(tpl,data));
			li.removeClass('hidden');
			$('#addresses').append(li);
		}
		if(response.rows) $('.address-title span').text(response.rows.length);

		if(callback!=null) callback();
	});
}
function client_address_save(fromCode,callback,noMessage){
	var data = $('#addressModal').toJson();
	data.action = 'client_address_save';
	data.client = $.urlParam('id');

	data.id = $('#addressModal').attr('data-id');
	data.job = data['contact-job'];
	data.mail = data['contact-mail'];
	data.phone = data['contact-phone'];
	for(var k in data){
		data[k.replace('address-','')] = data[k];
	}

	if(fromCode) $.extend(data,fromCode);

	$.action(data,function(r){

		if(!noMessage) $.message('success','Enregistré');
		if(callback) callback();
		$('#addressModal').clear().modal('hide');
		client_address_search(function(){
			client_address_change();
		});
	});
}

function client_address_edit(element){
	var id = element ? $(element).closest('li').attr('data-id'): null;
	$('#addressModal').modal('show');
	$('#addressModal').clear();

	if(id){
		$.action({
			action: 'client_address_edit',
			id: id
		},function(r){
			$('#address-type').val(r.type);
			$('#address-street').val(r.street);
			$('#address-complement').val(r.complement);
			$('#address-zip').val(r.zip);
			$('#address-city').val(r.city);
			$('#address-country').val(r.country);

			$('#addressModal').attr('data-id',r.id);
			init_components('#addressModal');
		});
	}
}

function client_address_fill(data){
	$('#address-street').val(data.address);
	$('#address-zip').val(data.zip);
	$('#address-city').val(data.city);
	$('#address-country').val(data.country);
}


function client_address_delete(element){
	if(!confirm('Êtes-vous sûr de vouloir supprimer cette adresse ?')) return;
	var line = $(element).closest('li');

	$.action({
		action: 'client_address_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
		$.message('info','Adresse supprimée');
	});
}

function client_address_copy(element){
	var line = $(element).closest('li');

	var datas = ['street', 'complement', 'zip', 'city', 'country'];
	var address = [];

	datas.forEach(function(data){
		var attribute = line.attr('data-'+data);
		if (attribute) address.push(attribute);
	});

	var clipboard = address.join(', ');
	copy_string(clipboard);
	$.message('success','Copié avec succès');
}

/** HISTORY **/
//Récuperation d'une liste de history dans le tableau #historys
function client_core_history_search(callback,exportMode){
	if($('.client-container').attr('data-id')=='') return;

	var box = new FilterBox('#client-history-filters');

	$('#historys').fill({
		action:'client_core_history_search',
		filters: box.filters(),
		id: $('.client-container').attr('data-id'),
		export:  !exportMode ? false : exportMode
	},function(response){
		$('.results-count span').text(response.pagination.total);
		if(callback!=null) callback();
	});
}




function client_core_history_save(callback){
	var data = {action:'client_core_history_save',client:$.urlParam('id'),comment:$('#history-comment').val()}

	if($('#history-comment').attr('data-id')) data.id = $('#history-comment').attr('data-id');

	$.action(data,function(r){
		$('#history-comment').attr('data-id','')
		$('#history-comment').val('');

		$('#history-comment').data('trumbowyg').empty()
		client_core_history_search();
		if(callback) callback();
	});
}
function client_history_edit(element){

	var line = $(element).closest('.item-line');
	console.log(line,element);
	$.action({
		action: 'client_history_edit',
		id: line.attr('data-id')
	},function(r){

		$('#history-comment').val(r.comment).attr('data-id',r.id);
		init_components($('#history-comment').parent());
	});

}

function client_core_history_delete(element){
	if(!confirm('Êtes-vous sûr de vouloir supprimer cet historique client ?')) return;
	var line = $(element).closest('.item-line');

	$.action({
		action: 'client_core_history_delete',
		id: line.attr('data-id')
	},function(r){
		line.remove();
	});

}

function client_update_map_size(){
	var height = $('.client-info').outerHeight();
	$('.client-map').css('height',height+'px');
	$('#gmap_canvas')
		.attr('width',$('.client-map').outerWidth())
		.attr('height',height);
}