app
	.component('appClientes',{
		templateUrl: './views/clientes/clientes.view.html',
		controller: CtrlClientes
	});

	CtrlClientes.$inject = ['$scope','api.service','form.service','alert.service'];

	//let selected;
	//console.log('aqui');
	function CtrlClientes(scope,api,form,alert) 
	{
		scope.tipodoc = [];
		scope.cliente = [];

		Init = () => 
		{
			scope.spinner = true;

			api.list('Clientes/parametros').then(res => {
				scope.tipodoc = res.data.tipodoc;
			})

			api.list('Clientes/lista').then(res => {
				scope.cliente = res.data;
			})
			.finally(fin => scope.spinner = false);
		}
		
		scope.openModal = (index,object = {}) => 
		{
			Clean();

			switch(index)
			{
				case 1:
					scope.modal.edit = false;
					scope.modal.title = "Agregar Cliente";
					form.modal('edit');
				break;
				case 2:
					scope.modal.edit = true;
					scope.modal.title = "Editar Cliente";
					scope.modal.model = angular.copy(object);
					form.modal('edit');
				break;
			}
		}

		scope.save = () => 
		{
			scope.modal.spinner = true;
			scope.modal.fails   = {};

			let promise;

						
			if(scope.modal.model.id_cliente){
				//Function_cp();
				scope.modal.model.id = scope.modal.model.id_cliente;
				promise = api.update('Clientes',scope.modal.model);
			}else{
				promise = api.store('Clientes',scope.modal.model);
			}

			promise.then(res => Process(res)).catch(error => ManagerError(error)).finally(fin => scope.modal.spinner = false);
		}

		scope.delete = (Clientes) => 
		{
			scope.deleted = Clientes;
			alert.confirm("¡Se eliminara a " + Clientes.cliente + " de la lista de clientes, esta operación es irreversible!",Delete);
		}

		Delete = (Clientes) => 
		{
			scope.spinner_delete = true;

			api.delete('Clientes',scope.deleted.id_cliente).then(res => {
				if(!res.data.success) return ManagerError(res.data.message);
				alert.success(res.data.message);
				Init();
			})
			.catch(error => ManagerError(error))
			.finally(fin => scope.spinner_delete = false);
		}
		
		Process = (res) => 
		{
			if(res.data.fails)
				return scope.modal.fails = res.data.fails;

			if(!res.data.success)
				return alert.warning(res.data.message);
			
			alert.success(res.data.message);
			form.modal('edit',false);
			Init();
		}

		ManagerError = (error) => {
			alert.warning(error);
		}

		Clean = () => {
			scope.modal = {model: {},fails: {}};
		}

		Init();
	}

	