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

class MaquinistaScan {
    constructor(domItem) {
        this.item = domItem
        /** ELEMENT DOM VARIABLES */
        this.otInputId = this.item.find('#ot-id')
        this.otId = null
        this.maquinaId = this.item.data("id")
        this.ots = []
        this.datatableItem = this.item.find('#table-scanned-ots')
        this.btnSave = this.item.find('#btn-save-maquina-ots');
        this.btnReset = this.item.find('#btn-reset-ots')
        this.datatableColumns = [
            { data: 'id', searchable: false, sortable: false },
            { data: 'title', searchable: false, sortable: false },
        ]
        this.datatableData = [];
        this.linkAfterSave = this.item.find('#ot-maquina-tareas-link')
        this.scanWrapper = this.item.find('.ot-scan-wrapper')

    }
    init() {
        this.otInputId.trigger('focus')
        this.otInputId.on('change', this.addOt.bind(this))
        this.btnReset.on('click',this.reset.bind(this))
        this.btnSave.on('click',this.saveMultipleOTs.bind(this))
        this.datatable = this.datatableItem.DataTable({
            processing: true,
            serverSide: false,
            ordering: false,
            dom: "",
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatableColumns,
            data: this.datatableData
        });

    }
    reset(){
        this.ots = []
        this.datatable.clear()
        this.datatable.draw()
        this.reloadFocus();
        this.btnSave.attr('disabled','disabled');
    }
    hideWrapper() {
        this.scanWrapper.addClass('d-none')
    }
    showWrapper() {
        this.scanWrapper.removeClass('d-none')
    }
    actionLoader(status = true) {
        if (status) {
            Notiflix.Block.circle('.section-block');
        } else {
            Notiflix.Block.remove('.section-block');
        }
    }
    reloadFocus() {
        this.otInputId.val("")
        this.otInputId.trigger('focus')
    }
    async saveMultipleOTs() {
        try {
            let result = await alertConfirmAction()
            if(result.isConfirmed){
                this.actionLoader(true)
                let response = await this.postMaquinaOrdenesTrabajo()
                this.actionLoader(false)
                popSuccessAlert(response.message)
                this.hideWrapper()
                this.linkAfterSave.removeClass('d-none')
            }

        } catch (error) {
            this.actionLoader(false)
            if (error?.responseJSON) {
                popErrorAlert(error.responseJSON.message)
            } else {
                popErrorAlert(error)
            }
        }
    }
    async addOt() {
        try {
            if (this.ots.includes(this.otInputId.val())) {
                throw new Error("Esta OT ya ha sido introducida");
            }
            if (this.otInputId.val()) {
                let response = await this.getOt(this.otInputId.val())
                console.log(response)
                const data = response.data
                this.ots.push(data.ot.id)
                this.datatable.rows.add([{
                    id: data.ot.id,
                    title: data.presupuesto.titulo
                }])
                this.datatable.draw()
                this.reloadFocus()
                this.btnSave.removeAttr('disabled')
            }

        } catch (error) {
            console.log(error)
            this.reloadFocus()
            if (error?.responseJSON) {
                popErrorAlert(error.responseJSON.message)
            } else {
                popErrorAlert(error)
            }
        }
    }
    getOt(otId) {
        return new Promise((resolve, reject) => {
            let ajax = new Ajax(
                `/produccion/ordentrabajo/tareas/maquina/${otId}/${this.maquinaId}`,
                null,
                null,
                (response) => {
                    resolve(response)
                },
                (error) => {
                    reject(error)
                }
            )
            ajax.get();
        })

    }

    postMaquinaOrdenesTrabajo() {
        return new Promise((resolve, reject) => {
            let ajax = new Ajax(
                `/produccion/ordentrabajo/maquinas/ots`,
                {
                    maquina_id: this.maquinaId,
                    ordenes_trabajo: this.ots
                },
                null,
                (response) => {
                    resolve(response)
                },
                (error) => {
                    reject(error)
                }
            )
            ajax.post();
        })
    }








}

export default MaquinistaScan;