
import Ajax from '../../../components/ajax.js'
import { alertConfirmAction, alertError, alertSuccess } from '../../../components/alerts/sweetAlert.js'

class MaquinistaFichajeAuto {
    constructor(domItem) {
        this.item = domItem
        /** ELEMENT DOM VARIABLES */
        this.otInputId = this.item.find('#ot-id')
        this.wrapperCard = this.item.find('#ot-fa-card')
        this.btnCancelTarea = this.item.find('#btn-cancel-tarea')
        this.btnFinishTarea = this.item.find('#btn-finish-tarea')
        this.inputClickInit = this.item.find("#input-click-init")
        this.inputClickEnd = this.item.find("#input-click-end")

        this.otId = null
        this.lastOtId = null
        this.maquinaId = this.item.data("id")
        this.tareas = []

    }
    init() {
        Notiflix.Block.circle('.section-block');
        this.otInputId.trigger('focus')
        this.otInputId.on('change', this._handleGetOt.bind(this))
        this.btnFinishTarea.on('click', this._handleUpdateTareasConfirm.bind(this))
        this.btnCancelTarea.on('click',this._handleResetTareasConfirm.bind(this))
    }

    hideCard() {
        this.wrapperCard.addClass('d-none')
    }
    showCard() {
        this.wrapperCard.removeClass('d-none')
    }
    actionLoader(status = true) {
        if (status) {
            Notiflix.Block.circle('.section-block');
        } else {
            Notiflix.Block.remove('.section-block');
        }
    }

    getFormData() {
        return {
            maquina_id: this.maquinaId,
            tareas: this.tareas,
            click_init: this.inputClickInit.val() ?? 0,
            click_end: this.inputClickEnd.val() ?? 0
        }
    }
    fillData(data) {
        this.lastOtId = data.ot.id
        this.item.find('#ot-id-header').text(data.ot.id)
        this.item.find('#presupuesto-id').text(data.presupuesto.id)
        this.item.find('#ot-title').text(data.presupuesto.titulo)
        if (data.tareas) {
            this.tareas = data.tareas.map(tarea => tarea.id)
        }

    }


    _handleGetOt() {
        this.otId = this.otInputId.val();
        this.otInputId.removeClass('is-valid')
        this.otInputId.removeClass('is-invalid')
        this.actionLoader(false)
        let ajax = new Ajax(
            `/produccion/ordentrabajo/tareas/maquina/${this.otId}/${this.maquinaId}`,
            null,
            null,
            this._handleGetOtSuccess.bind(this),
            this._handleGetOtError.bind(this)
        )
        if (this.otId) {
            ajax.get();
        }
    }
    _handleGetOtSuccess(response) {
        this.showCard();
        if (this.lastOtId) {
            console.log("Siguiente OT insertada")
            console.log("Iniciar ", this.otId)
            if (this.lastOtId != this.otId) {
                console.log("Finalizar", this.lastOtId)
                this._handleUpdateTareas(this.lastOtId,'F')
            }
        } else {
            console.log("Primera OT insertada")
        }
        this.otInputId.addClass('is-valid')
        popSuccessAlert(response.message)
        this.actionLoader(false)
        if (response.data) {
            this.fillData(response.data)
            this._handleUpdateTareas(this.otId, 'I')
        }
    }
    _handleGetOtError(error) {
        this.hideCard()
        this.otInputId.addClass('is-invalid')
        popErrorAlert(error.responseJSON.message)
    }

    _handleUpdateTareas(otId,estado = "F") {
        let ajax = new Ajax('/produccion/ordentrabajo/fa/tareas/update',
            {
                orden_trabajo_id: otId,
                estado : estado,
                ...this.getFormData()
            }, null,
            this._handleUpdateTareasSucess.bind(this),
            this._handleUpdateTareasError.bind(this)
        );
        ajax.post()

    }
    _handleUpdateTareasConfirm(event) {
        let otId = this.otInputId.val()
        console.log("Finalizar", otId);
        let ajax = new Ajax('/produccion/ordentrabajo/fa/tareas/update',
            {
                orden_trabajo_id: otId,
                estado : 'F',
                ...this.getFormData()
            }, null,
            this._handleUpdateTareasConfirmSucess.bind(this),
            this._handleUpdateTareasConfirmError.bind(this)
        );
        if (otId) {
            alertConfirmAction('Se va finalizar la tarea actual y se cancelará el modo auto.')
                .then((result) => {
                    if (result.isConfirmed) {
                        ajax.post();
                    }
                })
        }

    }
    _handleUpdateTareasConfirmSucess(response) {
        this.hideCard()
        this.otInputId.val(null)
        this.otId = null
        this.lastOtId = null
        this.tareas = []
        popSuccessAlert(response.message)
    }
    _handleDeleteTareasConfirmSucess(response) {
        this.hideCard()
        this.otInputId.val(null)
        this.otId = null
        this.lastOtId = null
        this.tareas = []
        popSuccessAlert(response.message)
    }
    _handleDeleteTareasConfirmError(error) {
        popErrorAlert(error)
    }
    _handleResetTareasConfirm(event) {
        let otId = this.otInputId.val()
        console.log("Finalizar", otId);
        let ajax = new Ajax('/produccion/ordentrabajo/fa/tareas/reset',
            {
                orden_trabajo_id: otId,
                estado : 'P',
                ...this.getFormData()
            }, null,
            this._handleDeleteTareasConfirmSucess.bind(this),
            this._handleUpdateTareasConfirmError.bind(this)
        );
        if (otId) {
            alertConfirmAction('Se va a cancelar la tarea y se borrará el progreso')
                .then((result) => {
                    if (result.isConfirmed) {
                        ajax.post();
                    }
                })
        }

    }
    _handleUpdateTareasConfirmError() { }
    _handleUpdateTareasSucess(response) { 
        this.item.find('#tiempo-estimado-info').text(response.data.tiempo_total_estimado)
        this.item.find('#tiempo-real-info').text(response.data.tiempo_total_real)

    }
    _handleUpdateTareasError() { }







}

export default MaquinistaFichajeAuto;