let vue_obj;
(function () {
	const controlador = 'Holiday';
	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(
			'holiday_id',
			'Identificador',
			'text',
			'Deber ser unico',
			'',
			'holiday_id'
		),
		parseField('holiday_name', 'Nombre', 'text', '', '', 'holiday_name'),
		parseField(
			'holiday_comments',
			'Comentarios',
			'text',
			'',
			'',
			'holiday_comments'
		),
		parseField(
			'holiday_date',
			'Fecha',
			'datepicker',
			'',
			new Date().toISOString().split('T').shift(),
			'holiday_date'
		),
		parseField(
			'holiday_status',
			'Estado',
			'select',
			'',
			'ACTIVE',
			'holiday_status',
			[
				{ label: 'Activo', value: 'ACTIVE' },
				{ label: 'Inactivo', value: 'INACTIVE' },
			]
		),
		parseField(
			'ct_default_start',
			'Hora de inicio',
			'text',
			'Con formato H00, ej. 13:00 -> 1300, 9:00 -> 900'
		),
		parseField(
			'ct_default_stop',
			'Hora de fin',
			'text',
			'Con formato H00, ej. 13:00 -> 1300, 9:00 -> 900'
		),
		parseField(
			'default_afterhours_filename_override',
			'Audio',
			'select',
			'Audio que sonara en el dia y 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 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 dia festivo'),
						icon: 'edit',
					},
					{
						action: 'delete',
						tooltip: traducirFrase('Eliminar el dia festivo'),
						icon: 'delete',
					},
				],
				// Variables para los modales
				targets: {
					add: false,
					edit: false,
				},
				// Registrar
				one: fieldsToObject(),
				audios: [],
				// Editar
				// Paginacion
				pagina: 1,
				cuenta: 1,
				texto: '',
			};
		},
		methods: {
			load() {
				let self = this;
				gen_rpost(controlador + '/getAllHolidays', {
					pagina: this.pagina,
					// texto: this.texto,
				})
					.then((results) => {
						self.registros = results.Registros.map((v) => ({
							...v,
							holiday_status: {
								ACTIVE: 'Activo',
								INACTIVE: 'Inactivo',
								EXPIRED: 'Expirado',
							}[v.holiday_status],
						}));
						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;
				handled_rpost(
					`${controlador}/${url}`,
					objFieldsValues(this.one, toggle)
				)
					.then((res) => {
						self.toggle(toggle);
						self.load();
					})
					.catch((err) => console.log(err));
			},
			add(url, toggle) {
				this.sendData(url, toggle);
			},
			edit($evt) {
				let self = this;
				gen_rpost(controlador + '/getHoliday', {
					holiday_id: $evt.holiday_id,
				})
					.then((res) => {
						console.log(res);
						self.one = res.CallTime;
                        objSetDatepickerValues(this.one, 'edit');
						self.toggle('edit');
					})
					.catch((err) => console.log(err));
			},
			del($evt) {
				let self = this;
				conf_rpost(
					controlador + '/deleteHoliday',
					{
						holiday_id: $evt.holiday_id,
					},
					traducirFrase(
						'Continuar esta accion eliminara el dia festivo seleccionado'
					)
				)
					.then((result) => {
						self.load();
					})
					.catch((err) => {
						console.log(err);
					});
			},
			toggle(target) {
				selectAudios().then((audios) => {
					this.audios = audios;
					this.audios.push({ value: '', label: 'Sin audio' });
					if (target == 'add') {
						this.one = fieldsToObject();
                        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 this.one.nombre != '';
				return true;
			},
		},
		watch: {
			pagina() {
				this.load();
			},
		},
		updated() {
			$('.tooltipped').tooltip();
		},
		mounted() {
			let self = this;
			setTimeout(() => {
				$('.datepicker').css('z-index', 10000);
			}, 500);
			setInterval(self.load, 20000);
		},
	});

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