
import Ajax from '../../../components/ajax.js'
import { alertConfirmAction, alertError, alertSuccess } from '../../../components/alerts/sweetAlert.js'
class MaquinistaTareaView {
    constructor(domItem) {
        this.item = domItem
        this.tareaId = this.item.data("id");
        this.btnPlay = this.item.find("#btn-start-tarea")
        this.btnPause = this.item.find("#btn-pause-tarea")
        this.btnDelay = this.item.find("#btn-stop-tarea")
        this.btnFinish = this.item.find("#btn-finish-tarea")
        this.btnDeleteProgress = this.item.find("#btn-delete-tarea")
        this.actionButtons = this.item.find('.action-btn')
        this.tareaCardClass = '.tarea-card-action-block'
        this.inputClick = $('.ot-tarea-click')
        this.btnPrintLabels = this.item.find('#btn-print-labels')
    }
    init() {
        this.actionButtons.on('click', this.eventActionButton.bind(this))
        this.btnDelay.on('click', this.delayEventActionButton.bind(this))
        this.btnDeleteProgress.on('click', this.handleDeleteTareaProgress.bind(this))
        this.handleGetTareaProgress();
        this.inputClick.on('input', this.handleUpdateClickInput.bind(this))
        this.btnPrintLabels.on('click', this.handlePrintLabels.bind(this))
    }

    eventActionButton(event) {
        let statusClick = $(event.currentTarget).data('estado');
        this.showBasedOnStatus(statusClick);
        console.info(`Estado ${statusClick}`)
        this.handleUpdateTareaProgress(statusClick)
    }
    delayEventActionButton(event) {
        let statusClick = $(event.currentTarget).data('estado');
        this.delayTarea()
    }
    actionLoader(status = true) {
        if (status) {
            Notiflix.Block.circle(this.tareaCardClass);
        } else {
            Notiflix.Block.remove(this.tareaCardClass);
        }
    }
    showPlay() {
        this.btnPause.addClass('d-none')
        this.btnPlay.removeClass('d-none')
        this.btnFinish.removeClass('d-none')

    }
    showPause() {
        this.btnPlay.addClass('d-none')
        this.btnFinish.addClass('d-none')
        this.btnPause.removeClass('d-none')

    }
    disableButtons() {
        this.actionButtons.attr('disabled', 'disabled')
        this.btnDelay.attr('disabled', 'disabled')
        this.btnDeleteProgress.attr('disabled', 'disabled')
    }
    enableButtons() {
        this.actionButtons.removeAttr('disabled')
    }
    handleUpdateClickInput(event) {
        let tareaId = $(event.currentTarget).data('id');
        let name = $(event.currentTarget).attr('name')
        let value = $(event.currentTarget).val()
        let formData = {
            orden_trabajo_tarea_id: tareaId
        }

        formData[name] = value;
        let ajax = new Ajax('/produccion/ordentrabajo/update/tarea',
            formData,
            null,
            this.handleUpdateClickInputSucess.bind(this),
            this.handleGetTareaProgressError.bind(this)
        )
        if (value) {
            ajax.post()
        }

    }
    handleUpdateClickInputSucess(response) {
        popSuccessAlert(response.message)
        this.updateContentClick(response.data.click_end - response.data.click_init)
    }
    handleUpdateClickInputError(error) {
        popErrorAlert(error)
    }
    updateContentClick(clicks) {
        this.item.find('#clicks-info').empty().html(clicks)
    }
    handleDeleteTareaProgress() {
        let ajax = new Ajax('/produccion/ordentrabajo/tarea/progress/' + this.tareaId,
            null,
            null,
            this.handleDeleteTareaProgressSuccess.bind(this),
            this.handleDeleteTareaProgressError.bind(this)
        )
        alertConfirmAction('Se borrará todo el progreso y se reiniciará el progreso')
            .then(result => {
                if (result.isConfirmed) {
                    this.actionLoader(true)
                    ajax.delete()
                }
            })
    }
    handleDeleteTareaProgressSuccess() {
        window.location.reload()
    }
    handleDeleteTareaProgressError(error) {
        popErrorAlert(error)
    }

    handleGetTareaProgress() {
        this.actionLoader()
        let ajax = new Ajax(`/produccion/ordentrabajo/tarea/progress/${this.tareaId}`, null, null,
            this.handleGetTareaProgressSuccess.bind(this),
            this.handleGetTareaProgressError.bind(this),

        )
        if (this.tareaId) {
            ajax.get();
        }
    }
    handleGetTareaProgressSuccess(response) {
        if (response.progress_dates.length > 0) {
            let lastStatus = response.progress_dates.findLast(e => e.estado != null).estado
            console.log("Last status :", lastStatus)
            this.showBasedOnStatus(lastStatus)
        } else {
            this.showBasedOnStatus('P')
        }
        this.item.find('#tiempo-real-info').html(response.tiempo_trabajado ?? "00:00")
        this.actionLoader(false)

    }
    handleGetTareaProgressError(error) {
        this.actionLoader(false)
    }
    handleUpdateTareaProgress(status) {
        this.actionLoader(true)
        let ajax = new Ajax(`/produccion/ordentrabajo/update/tarea/progress`,
            {
                'ot_tarea_id': this.tareaId,
                'estado': status
            }, null,
            this.handleUpdateTareaProgressSuccess.bind(this),
            this.handleUpdateTareaProgressError.bind(this),
        )
        if (this.tareaId) {
            if (status == "F") {
                alertConfirmAction('La tarea se marcará como finalizada')
                    .then(result => {
                        if (result.isConfirmed) {
                            ajax.post();
                        }
                    })
            } else {
                ajax.post();
            }
        }
    }
    handleUpdateTareaProgressSuccess(response) {
        if (response.data.tarea) {
            if (response.data.tarea.estado == 'D') {
                window.location.href = '/produccion/ordentrabajo/maquinista/maquinas/view'
            }
            this.item.find('#tiempo-real-info').html(response.data.tiempo_trabajado ?? "00:00")
            this.showBasedOnStatus(response.data.estado)
            alertSuccess(response.message, null, { position: 'top' }).fire()
        }
        this.actionLoader(false)
    }
    handleUpdateTareaProgressError(error) {
        popErrorAlert(error.error)
        alertError(error.error, null, { position: 'top' }).fire()
        this.actionLoader(false)
    }

    showBasedOnStatus(status) {
        if (['P', 'S'].includes(status)) {
            this.enableButtons()
            this.showPlay()
        }
        if (['F', 'E'].includes(status)) {
            this.disableButtons()
            this.showPlay()
        }
        if (status == 'I') {
            this.enableButtons()
            this.showPause()
        }
        if (status == 'D') {
            window.href
        }
    }
    eventUnloadWindow(event) {
        // return confirm('¿Estás seguro de abandonar la página? La tarea se marcará como pausada')
        alertConfirmAction('La tarea se marcará como pausada')
            .then(result => {

                if (result.isConfirmed) {
                    return ""
                }
            })
    }
    delayTarea() {
        alertConfirmAction('La tarea se marcará como aplazada y podrás continuar después')
            .then(result => {
                if (result.isConfirmed) {
                    this.handleUpdateTareaProgress('D')
                }
            })
    }
    getTarea(tarea_id) {
        return new Promise((resolve, reject) => {
            let ajax = new Ajax(`/produccion/ordentrabajo/tarea/${tarea_id}`, null, null, (response) => {
                resolve(response)
            },
                (error) => {
                    resolve(error)
                })
            ajax.get()
        })
    }

    handlePrintLabels() {

        const impresoras = JSON.parse($('#impresoras').val());

        let options = '';
        impresoras.forEach(p => {
            options += `<option value="${p.id}">${p.name}</option>`;
        });

        Swal.fire({
            title: 'Imprimir etiquetas',
            html: `
        <div class="mb-3 text-start">
            <label for="swal-impresora" class="form-label">Impresora</label>
            <select id="swal-impresora" class="form-control">
                ${options}
            </select>
        </div>
        <div class="mb-3 text-start">
            <label for="swal-unidades" class="form-label">Unidades por caja</label>
            <input type="number" id="swal-unidades" class="form-control" min="1" value="${$("#tirada-info").html()}" />
        </div>
    `,
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            confirmButtonText: 'Aceptar',
            cancelButtonText: 'Cancelar',
            customClass: {
                confirmButton: 'btn btn-primary me-1',
                cancelButton: 'btn btn-secondary'
            },
            buttonsStyling: false,
            preConfirm: () => {
                const impresora = $('#swal-impresora').val();
                const unidades = parseInt($('#swal-unidades').val(), 10);

                if (!impresora || isNaN(unidades) || unidades <= 0) {
                    Swal.showValidationMessage('Debe seleccionar una impresora y un número válido de unidades.');
                    return false;
                }

                return { impresora, unidades };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                
                $.post('/produccion/ordentrabajo/maquinista/maquinas/tareas/printLabels', {
                    impresora_id: result.value.impresora,
                    unidades_caja: result.value.unidades,
                    ot_id: $('#otId').html(),
                }, function (response) {
                    if (response.status) {
                        popSuccessAlert(response.message);
                        if(response.data) {
                            // show xml in new tab
                            const blob = new Blob([response.data], { type: 'application/xml' });
                            const url = URL.createObjectURL(blob);
                            const newTab = window.open(url, '_blank');
                            if (newTab) {
                                newTab.onload = function () {
                                    // Revoke the object URL after the new tab has loaded
                                    URL.revokeObjectURL(url);
                                };
                            } else {
                                popErrorAlert('Error abriendo la pestaña');
                            }
                        }
                    } else {
                        popErrorAlert(response.error)
                    }
                }, 'json');
            }
        });
    }

}

export default MaquinistaTareaView;