let vue_obj;
(function () {
	const controlador = 'CallTime';
	const parseField = (
		key,
		label,
		type,
		hint,
		defaultValue,
		headerKey,
		options
	) => ({
		key,
		label,
		type,
		hint,
		defaultValue: defaultValue ? defaultValue : '',
		headerKey: headerKey && headerKey !== '' ? headerKey : undefined,
		options,
	});
	const generalFields = [
		parseField(
			'call_time_id',
			'Identificador',
			'text',
			'Deber ser unico',
			'',
			'call_time_id'
		),
		parseField(
			'call_time_name',
			'Nombre',
			'text',
			'',
			'',
			'call_time_name'
		),
		parseField(
			'call_time_comments',
			'Comentarios',
			'text',
			'',
			'',
			'call_time_comments'
		),
		parseField(
			'ct_default_start',
			'Hora de inicio por defecto',
			'text',
			'Con formato H00, ej. 13:00 -> 1300, 9:00 -> 900',
			'',
			'ct_default_start'
		),
		parseField(
			'ct_default_stop',
			'Hora de fin por defecto',
			'text',
			'Con formato H00, ej. 13:00 -> 1300, 9:00 -> 900',
			'',
			'ct_default_stop'
		),
		parseField(
			'default_afterhours_filename_override',
			'Audio',
			'select',
			'Audio que sonara fuera de las horas registradas',
			'',
			'',
			'audios'
		),
	];
	[
		{ label: 'Domingo', key: 'sunday' },
		{ label: 'Lunes', key: 'monday' },
		{ label: 'Martes', key: 'tuesday' },
		{ label: 'Miercoles', key: 'wednesday' },
		{ label: 'Jueves', key: 'thursday' },
		{ label: 'Viernes', key: 'friday' },
		{ label: 'Sabado', key: 'saturday' },
	].forEach(({ key, label }) => [
		generalFields.push(
			...[
				parseField(
					'ct_' + key + '_start',
					'Hora de inicion del ' + label,
					'text',
					'Con formato H00, ej. 13:00 -> 1300, 9:00 -> 900',
					''
				),
				parseField(
					'ct_' + key + '_stop',
					'Hora de fin del ' + label,
					'text',
					'Con formato H00, ej. 13:00 -> 1300, 9:00 -> 900',
					''
				),
				parseField(
					key + '_afterhours_filename_override',
					'Audio del ' + label,
					'select',
					'Audio que sonara fuera las horas registradas',
					'',
					'',
					'audios'
				),
			]
		),
	]);
	// const fieldsToObject = (obj) => {
	// 	let o = obj ? obj : {};
	// 	generalFields.forEach((v) => {
	// 		o[v.key] = v.defaultValue;
	// 	});
	// 	return o;
	// };
	const fieldsToHeaders = () => {
		return generalFields
			.filter((v) => v.headerKey)
			.map(({ label, headerKey: key }) => ({
				label,
				key,
			}));
	};
	const objFieldsValues = (obj, op) => {
		const o = {};
		generalFields.forEach((v) => {
			if (v.type === 'datepicker') {
				o[v.key] = $('#' + v.key + '_' + op + '_datepicker').val();
			} else {
				o[v.key] = obj[v.key];
			}
		});
		return o;
	};
	const objSetDatepickerValues = (obj, op) => {
		generalFields.forEach((v) => {
			if (v.type === 'datepicker' && obj[v.key]) {
				$('#' + v.key + '_' + op + '_datepicker').val(obj[v.key]);
			}
		});
	};
	const oneVacio = {
		call_time_id: "",
		call_time_name: "",
		call_time_comments: "",
		ct_default_start: "",
		ct_default_stop: "",
		default_afterhours_filename_override: "",
		ct_sunday_start: "",
		ct_sunday_stop: "",
		ct_monday_start: "",
		ct_monday_stop: "",
		ct_tuesday_start: "",
		ct_tuesday_stop: "",
		ct_wednesday_start: "",
		ct_wednesday_stop: "",
		ct_thursday_start: "",
		ct_thursday_stop: "",
		ct_friday_start: "",
		ct_friday_stop: "",
		ct_saturday_start: "",
		ct_saturday_stop: "",
		default_afterhours_filename_override: "",
		friday_afterhours_filename_override: "",
		monday_afterhours_filename_override: "",
		saturday_afterhours_filename_override: "",
		sunday_afterhours_filename_override: "",
		thursday_afterhours_filename_override: "",
		tuesday_afterhours_filename_override: "",
		wednesday_afterhours_filename_override: "",
		ct_holidays: "",
	};

	const app = new Vue({
		el: '#main',
		data() {
			return {
				// Variables para la tabla
				registros: [],
				loading: true,
				generalFields: generalFields,
				headers: fieldsToHeaders(),
				options: [
					{
						action: 'edit',
						tooltip: traducirFrase('Editar el horario de llamada'),
						icon: 'edit',
					},
					{
						action: 'holidays',
						tooltip: traducirFrase('Administrar dias festivos'),
						icon: 'date_range',
					},
					{
						action: 'delete',
						tooltip: traducirFrase(
							'Eliminar el horario de llamada'
						),
						icon: 'delete',
					},
				],
				// Variable para selección de día
				dayPicker: {
					sunday: 0,
					monday: 0,
					tuesday: 0,
					wednesday: 0,
					thursday: 0,
					friday: 0,
					sunday: 0,
				},
				// Variables para los modales
				targets: {
					add: false,
					edit: false,
					holidays: false,
					addOld: false,
					editOld: false,
				},
				// Registrar
				// one: fieldsToObject(),
				one: Object.assign({} , oneVacio),
				two: Object.assign({} , oneVacio),
				audios: [],
				holidays: [],
				// Editar
				// Paginacion
				pagina: 1,
				cuenta: 1,
				texto: '',
				// Info para los holidays
                holidaysHeaders: [
                    { key: 'holiday', label: 'Identificador' },
                    { key: 'name', label: 'Nombre' },
                ],
                holidaysOptions: [
                    {
						action: 'delete',
						tooltip: traducirFrase(
							'Eliminar el dia festivo'
						),
						icon: 'delete',
					},
                ],
                calltimeHolidays: [],
				calltimeActual: -1,
				holiday: -1,
			};
		},
		methods: {
			load() {
				let self = this;
				gen_rpost(controlador + '/getAllCallTime', {
					pagina: this.pagina,
					// texto: this.texto,
				})
					.then((results) => {
						self.registros = results.Registros.map((v) => ({
							...v,
						}));
						self.cuenta = Math.floor(
							+(results.Cant ? result.Cant : 10) / 10 + 1
						);
						if (results.Cant % 10 == 0) {
							self.cuenta--;
						}
						self.loading = false;
					})
					.catch((err) => {
						console.log(err);
					});
			},
			sendData(url, toggle) {
				let self = this;
				this.formatearFechas();
				handled_rpost(
					`${controlador}/${url}`,
					this.one
					// objFieldsValues(this.one, toggle)
				)
					.then((res) => {
						self.toggle(toggle);
						self.load();
					})
					.catch((err) => console.log(err));
			},
			add(url, toggle) {
				this.sendData(url, toggle);
			},
			vaciarModal(){
				this.toggle('add');
				this.one = Object.assign({} , oneVacio);
			},
			formatearFechas(){
				let self = this;

				// Default hour values
				let ct_def_start = $("#ct_default_start").val();
				if(ct_def_start === ""){
					this.one.ct_default_start = 0;
				}else{
					this.one.ct_default_start = ct_def_start.substring(ct_def_start.length - 2 , ct_def_start.length) === "AM" ? this.am(ct_def_start) : this.pm(ct_def_start);
				}

				let ct_def_stop = $("#ct_default_stop").val();
				if(ct_def_stop === ""){
					this.one.ct_default_stop = 0;
				}else{
					this.one.ct_default_stop = ct_def_stop.substring(ct_def_stop.length - 2 , ct_def_stop.length) === "AM" ? this.am(ct_def_stop) : this.pm(ct_def_stop);
				}

				// Sunday Hour Values
				let ct_sun_start = $("#ct_sunday_start").val();
				if(ct_sun_start === ""){
					this.one.ct_sunday_start = 0;
				}else{
					this.one.ct_sunday_start = ct_sun_start.substring(ct_sun_start.length - 2 , ct_sun_start.length) === "AM" ? this.am(ct_sun_start) : this.pm(ct_sun_start);
				}

				let ct_sun_stop = $("#ct_sunday_stop").val();
				if(ct_sun_stop === ""){
					this.one.ct_sunday_stop = 0;
				}else{
					this.one.ct_sunday_stop = ct_sun_stop.substring(ct_sun_stop.length - 2 , ct_sun_stop.length) === "AM" ? this.am(ct_sun_stop) : this.pm(ct_sun_stop);
				}
				
				// Monday Hour Values
				let ct_mon_start = $("#ct_monday_start").val();
				if(ct_mon_start === ""){
					this.one.ct_monday_start = 0;
				}else{
					this.one.ct_monday_start = ct_mon_start.substring(ct_mon_start.length - 2 , ct_mon_start.length) === "AM" ? this.am(ct_mon_start) : this.pm(ct_mon_start);
				}

				let ct_mon_stop = $("#ct_monday_stop").val();
				if(ct_mon_stop === ""){
					this.one.ct_monday_stop = 0;
				}else{
					this.one.ct_monday_stop = ct_mon_stop.substring(ct_mon_stop.length - 2 , ct_mon_stop.length) === "AM" ? this.am(ct_mon_stop) : this.pm(ct_mon_stop);
				}

				// Tuesday Hour Values
				let ct_tue_start = $("#ct_tuesday_start").val();
				if(ct_tue_start === ""){
					this.one.ct_tuesday_start = 0;
				}else{
					this.one.ct_tuesday_start = ct_tue_start.substring(ct_tue_start.length - 2 , ct_tue_start.length) === "AM" ? this.am(ct_tue_start) : this.pm(ct_tue_start);
				}

				let ct_tue_stop = $("#ct_tuesday_stop").val();
				if(ct_tue_stop === ""){
					this.one.ct_tuesday_stop = 0;
				}else{
					this.one.ct_tuesday_stop = ct_tue_stop.substring(ct_tue_stop.length - 2 , ct_tue_stop.length) === "AM" ? this.am(ct_tue_stop) : this.pm(ct_tue_stop);
				}

				// Wednesday Hour Values
				let ct_wed_start = $("#ct_wednesday_start").val();
				if(ct_wed_start === ""){
					this.one.ct_wednesday_start = 0;
				}else{
					this.one.ct_wednesday_start = ct_wed_start.substring(ct_wed_start.length - 2 , ct_wed_start.length) === "AM" ? this.am(ct_wed_start) : this.pm(ct_wed_start);
				}

				let ct_wed_stop = $("#ct_wednesday_stop").val();
				if(ct_wed_stop === ""){
					this.one.ct_wednesday_stop = 0;
				}else{
					this.one.ct_wednesday_stop = ct_wed_stop.substring(ct_wed_stop.length - 2 , ct_wed_stop.length) === "AM" ? this.am(ct_wed_stop) : this.pm(ct_wed_stop);
				}

				// Thursday Hour Values
				let ct_thu_start = $("#ct_thursday_start").val();
				if(ct_thu_start === ""){
					this.one.ct_thursday_start = 0;
				}else{
					this.one.ct_thursday_start = ct_thu_start.substring(ct_thu_start.length - 2 , ct_thu_start.length) === "AM" ? this.am(ct_thu_start) : this.pm(ct_thu_start);
				}

				let ct_thu_stop = $("#ct_thursday_stop").val();
				if(ct_thu_stop === ""){
					this.one.ct_thursday_stop = 0;
				}else{
					this.one.ct_thursday_stop = ct_thu_stop.substring(ct_thu_stop.length - 2 , ct_thu_stop.length) === "AM" ? this.am(ct_thu_stop) : this.pm(ct_thu_stop);
				}

				// Friday Hour Values
				let ct_fri_start = $("#ct_friday_start").val();
				if(ct_fri_start === ""){
					this.one.ct_friday_start = 0;
				}else{
					this.one.ct_friday_start = ct_fri_start.substring(ct_fri_start.length - 2 , ct_fri_start.length) === "AM" ? this.am(ct_fri_start) : this.pm(ct_fri_start);
				}

				let ct_fri_stop = $("#ct_friday_stop").val();
				if(ct_fri_stop === ""){
					this.one.ct_friday_stop = 0;
				}else{
					this.one.ct_friday_stop = ct_fri_stop.substring(ct_fri_stop.length - 2 , ct_fri_stop.length) === "AM" ? this.am(ct_fri_stop) : this.pm(ct_fri_stop);
				}

				// Saturday Hour Values
				let ct_sat_start = $("#ct_saturday_start").val();
				if(ct_sat_start === ""){
					this.one.ct_saturday_start = 0;
				}else{
					this.one.ct_saturday_start = ct_sat_start.substring(ct_sat_start.length - 2 , ct_sat_start.length) === "AM" ? this.am(ct_sat_start) : this.pm(ct_sat_start);
				}

				let ct_sat_stop = $("#ct_saturday_stop").val();
				if(ct_sat_stop === ""){
					this.one.ct_saturday_stop = 0;
				}else{
					this.one.ct_saturday_stop = ct_sat_stop.substring(ct_sat_stop.length - 2 , ct_sat_stop.length) === "AM" ? this.am(ct_sat_stop) : this.pm(ct_sat_stop);
				}
			},
			am(hora){
				if(hora.charAt(0) === "0"){
					return hora.charAt(1) + hora.substring(3,5);
				}else{
					return hora.substring(0, 2) + hora.substring(3, 5);
				}
			},
			pm(hora){
				let valorHora = 0;
				let horaIndividual = 0;
				if(hora.charAt(0) === "0"){
					horaIndividual = parseInt(hora.charAt(1));
					valorHora = horaIndividual + 12;
					return valorHora.toString() + hora.substring(3,5);
				}else{
					horaIndividual = parseInt(hora.substring(0, 2));
					valorHora = horaIndividual + 12;
					return valorHora.toString() + hora.substring(3, 5);
				}
			},
			edit($evt) {
				let self = this;
				gen_rpost(controlador + '/getCallTime', {
					call_time_id: $evt.call_time_id,
				})
					.then((res) => {
						console.log(res);
						self.one = res.CallTime;
						objSetDatepickerValues(this.one, 'edit');
						self.toggle('edit');
						self.setFechasConFormato();
					})
					.catch((err) => console.log(err));
			},
			setFechasConFormato(){
				let self = this;
	
				self.two.ct_default_start = self.desformatear(self.one.ct_default_start);
				self.two.ct_default_stop = self.desformatear(self.one.ct_default_stop);

				self.two.ct_sunday_start = self.desformatear(self.one.ct_sunday_start);
				self.two.ct_sunday_stop = self.desformatear(self.one.ct_sunday_stop);

				self.two.ct_monday_start = self.desformatear(self.one.ct_monday_start);
				self.two.ct_monday_stop = self.desformatear(self.one.ct_monday_stop);

				self.two.ct_tuesday_start = self.desformatear(self.one.ct_tuesday_start);
				self.two.ct_tuesday_stop = self.desformatear(self.one.ct_tuesday_stop);

				self.two.ct_wednesday_start = self.desformatear(self.one.ct_wednesday_start);
				self.two.ct_wednesday_stop = self.desformatear(self.one.ct_wednesday_stop);

				self.two.ct_thursday_start = self.desformatear(self.one.ct_thursday_start);
				self.two.ct_thursday_stop = self.desformatear(self.one.ct_thursday_stop);

				self.two.ct_friday_start = self.desformatear(self.one.ct_friday_start);
				self.two.ct_friday_stop = self.desformatear(self.one.ct_friday_stop);

				self.two.ct_saturday_start = self.desformatear(self.one.ct_saturday_start);
				self.two.ct_saturday_stop = self.desformatear(self.one.ct_saturday_stop);
			},
			desformatear(hora){

				let aux = 0;

				if(hora.length < 4){
					hora = "0" + hora;
				}
				if(parseInt(hora.substring(0, 2)) > 12){
					aux = parseInt(hora.substring(0 , 2)) - 12;
					if(aux < 10){
						return "0" + aux.toString() + ":" + hora.substring(2, 4) + " PM";
					}else{
						return aux.toString() + ":" + hora.substring(2, 4) + " PM";
					}
				}else{
					return hora.substring(0 , 2) + ":" + hora.substring(2, 4) + " AM";
				}

			},
			hdays($evt, notToggle) {
				let self = this;
				gen_rpost(controlador + '/getCallTime', {
					call_time_id: $evt.call_time_id,
				})
					.then((res) => {
						console.log(res);
						self.calltimeActual = $evt.call_time_id;
						self.calltimeHolidays = res.CallTime.ct_holidays
							.split('|')
							.filter((v) => v !== '')
							.map((v) => {
								const holiday = self.holidays.find(
									(v) => v.holiday_id === v
								);

								return {
									holiday: v,
									name: holiday ? holiday.holiday_name : v,
								};
							});
						if (!notToggle) self.toggle('holidays');
					})
					.catch((err) => console.log(err));
			},
			del($evt) {
				let self = this;
				conf_rpost(
					controlador + '/deleteCallTime',
					{
						call_time_id: $evt.call_time_id,
					},
					traducirFrase(
						'Continuar esta accion eliminara el horario de llamada seleccionado'
					)
				)
					.then((result) => {
						self.load();
					})
					.catch((err) => {
						console.log(err);
					});
			},
			addHoliday() {
				let self = this;
				handled_rpost(controlador + '/addHolidayToCallTime', {
					call_time_id: this.calltimeActual,
					holiday: this.holiday,
				})
					.then((result) => {
						self.holiday = -1;
						self.hdays(
							{
								call_time_id: this.calltimeActual,
							},
							true
						);
					})
					.catch((err) => {
						console.log(err);
					});
			},
			deleteHoliday($evt) {
				let self = this;
				conf_rpost(
					controlador + '/deleteHolidayToCallTime',
					{
						call_time_id: this.calltimeActual,
						holiday: $evt.holiday,
					},
					traducirFrase(
						'Continuar esta accion eliminara el dia festivo al horario de llamada seleccionado'
					)
				)
					.then((result) => {
						self.hdays(
							{
								call_time_id: this.calltimeActual,
							},
							true
						);
					})
					.catch((err) => {
						console.log(err);
					});
			},
			toggle(target) {
				selectAudios().then((audios) => {
					selectHolidays().then((holidays) => {
						this.holidays = holidays;
						this.audios = audios;
						this.audios.push({ value: '', label: 'Sin audio' });
						if (target == 'add') {
							// this.one = fieldsToObject();
							// this.one = {...this.oneVacio}; ES6 
							this.one = Object.assign({} , oneVacio);
							this.one.ct_holidays = '';
							objSetDatepickerValues(this.one, target);
						}
						app.targets[target] = !app.targets[target];
					});
				});
			},
			getOptionsByField(field) {
				if (this[field.options]) {
					return this[field.options];
				}
				return field.options;
			},
			changedValue(e) {
				console.log('changed', e);
			},
		},
		computed: {
			validForm() {
				return true;
			},
            holidaysByCalltime() {
                return this.holidays.filter(v => !this.calltimeHolidays.find(val => val.holiday === v.value))
            }
		},
		watch: {
			pagina() {
				this.load();
			},
		},
		updated() {
			$('.tooltipped').tooltip();
		},
		mounted() {
			console.log(this.one);
			let self = this;
			setTimeout(() => {
				$('.datepicker').css('z-index', 10000);
			}, 500);
			setInterval(self.load, 20000);
		},
	});

	app.load();
	vue_obj = app;
})();
