

import Ajax from '../../../components/ajax.js'
import { alertConfirmAction, alertError, alertSuccess } from '../../../components/alerts/sweetAlert.js'
class MaquinistaMultipleTarea {
    constructor(domItem) {
        this.item = domItem
        this.maquinaId = 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.datatableItem = this.item.find('#table-scanned-ots')
        this.datatableColumns = [
            { data: 'otId', searchable: false, sortable: false },
            { data: 'titulo', searchable: false, sortable: false },
            {
                data: 'barcode', searchable: false, sortable: false, render: (d, t) => {
                    return `<img class="img-fluid w-100 h-50" src="data:image/png;base64,${d}" alt="barcode" />`
                }
            },
            {
                data: 'action', searchable: false, sortable: false, render: (d, t) => {
                    return `<a href="/produccion/ordentrabajo/edit/${d}" type="button" title="OT" class="maquina-btn btn btn-primary d-flex justify-content-center gap-2"><span class="ti ti-eye ti-lg"></span></a>`
                }
            },
        ]
    }
    init() {
        this.actionButtons.on('click', this.eventActionButton.bind(this))
        this.btnDelay.on('click', this.delayEventActionButton.bind(this))
        this.btnDeleteProgress.on('click', this.deleteAll.bind(this))
        this.actionLoader(true)
        this.datatableItem.DataTable({
            processing: true,
            dom: "",
            serverSide: true,
            ordering: false,
            pageLength: 25,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatableColumns,
            ajax: '/produccion/ordentrabajo/maquinas/ots/datatable/' + this.maquinaId,

        });
        this.initData()
    }
    async initData() {
        try {
            let responseData = await this.getMaquinaMultipleTarea();
            this.fillCardData(responseData)
        } catch (error) {
            console.error(error)
        } finally {
            this.actionLoader(false)
        }
    }
    fillCardData(responseData) {
        this.item.find('#tirada-info').text(responseData?.tirada_total ?? 0)
        this.item.find('#clicks-info').text(responseData?.clicks_total ?? 0)
        this.item.find('#tiempo-estimado-info').text(responseData.tiempo_total_estimado ?? "00:00:00")
        this.item.find('#tiempo-real-info').text(responseData.tiempo_total_real ?? "00:00:00")
        this.showBasedOnStatus(responseData.estado)
    }
    async deleteAll() {
        try {
            let result = await alertConfirmAction('Se resetearán las tareas y se borrará el progreso')
            if(result.isConfirmed){
                let response = await this.deleteMaquinaOrdenesTrabajo()
                popSuccessAlert(response.message);
                window.location.reload();
            }
        } catch (error) {
            console.error(error)
        }

    }
    async eventActionButton(event) {
        try {
            this.actionLoader(true)
            let statusClick = $(event.currentTarget).data('estado');
            this.showBasedOnStatus(statusClick);
            console.info(`Estado ${statusClick}`)
            this.showBasedOnStatus(statusClick);
            if (statusClick == "F") {
                let result = await alertConfirmAction('Se marcarán como finalizadas todas las tareas')
                if (result.isConfirmed == false) {
                    this.enableButtons()
                    throw new Error('Cancelado')
                }
            }
            let response = await this.updateEstadoOts(statusClick)
            popSuccessAlert(response.message)
            let responseData = await this.getMaquinaMultipleTarea()
            this.fillCardData(responseData)
            if(statusClick == "F"){
                window.location.reload();
            }
        } catch (error) {
            console.error(error)
        } finally {
            this.actionLoader(false)
        }
    }

    async delayEventActionButton(event) {
        try {
            this.actionLoader(true)
            let statusClick = $(event.currentTarget).data('estado');
            this.showBasedOnStatus(statusClick);
            let response = await this.updateEstadoOts(statusClick)
            popSuccessAlert(response.message)
            let responseData = await this.getMaquinaMultipleTarea()
            this.fillCardData(responseData)
        } catch (error) {
            console.error(error)
        } finally {
            this.actionLoader(false)
        }
    }
    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')
        this.btnDelay.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')
        this.btnDelay.removeAttr('disabled', 'disabled')
        this.btnDeleteProgress.removeAttr('disabled', 'disabled')
    }

    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") {
            this.showPlay()
        }

    }
    getClicks() {
        return {
            click_init: this.item.find('#input-click-init').val() ?? 0,
            click_end: this.item.find('#input-click-end').val() ?? 0,
        }
    }
    /** maquinas/ots/estado */
    updateEstadoOts(estado) {
        return new Promise((resolve, reject) => {
            new Ajax('/produccion/ordentrabajo/maquinas/ots/estado',
                {
                    maquina_id: this.maquinaId,
                    estado: estado,
                    ...this.getClicks()
                },
                null,
                resolve,
                reject
            ).post()
        })
    }
    getMaquinaMultipleTarea() {
        return new Promise((resolve, reject) => {
            new Ajax('/produccion/ordentrabajo/maquinas/ots/' + this.maquinaId,
                null,
                null,
                resolve,
                reject
            ).get()
        })
    }

    deleteMaquinaOrdenesTrabajo() {
        return new Promise((resolve, reject) => {
            new Ajax('/produccion/ordentrabajo/maquinas/ots/all/' + this.maquinaId,
                null,
                null,
                resolve,
                reject
            ).delete()
        })
    }




}

export default MaquinistaMultipleTarea;