import Ajax from "../../components/ajax.js"
import ClassSelect from "../../components/select2.js";
import DatePicker from "../../components/datepicker.js";
import { alertConfirmAction, alertConfirmationDelete, alertSuccess } from "../../components/alerts/sweetAlert.js";
import Modal from "../../components/modal.js"
import FileUploadDropzone from '../../components/forms/fileUploadDropzone.js';
class OrdenTrabajo {
    constructor(domItem) {
        this.item = domItem
        this.otForm = this.item.find("#ot-edit-form")
        this.block = document.querySelector('.section-block');
        this.modelId = this.item.data("id");
        this.tareasTableItem = this.item.find("#ot-task-table");
        this.tareasId = []
        this.summaryData = {}
        this.tareaCommentModal = new Modal($("#modalCommentTarea"))
        this.alertOrdenTrabajo = this.item.find("#alert-orden-trabajo");
        this.btnFinalizarPedido = this.item.find("#btn-finalizar-orden-pedido")
        this.btnReactivarOt = this.item.find("#btn-reactivar-orden-pedido")
        this.isOtFinalizada = false;

        this.btnResetTareas = this.item.find("#btn-reset-tareas")
        this.pedidoEnEsperaCheck = this.item.find("#ot-pedido-espera");
        this.pedidoEnEsperaBy = this.item.find("#pedido_espera_by");
        this.otEstado = this.item.find("#ot-estado");

        this.datatableColumns = [
            { data: 'orden', searchable: true, sortable: true, render: this._renderOrdenTarea.bind(this), width: "10%" },
            { data: 'nombre', searchable: true, sortable: true, width: "20%" },
            { data: 'maquina_presupuesto_linea', searchable: true, sortable: true, width: "20%" },
            { data: 'maquina_tarea', searchable: false, sortable: false, render: this._renderMaquinaSelectTable.bind(this), width: "20%" },
            { data: 'imposicion', searchable: false, sortable: false, render: this._renderImposicionSelectTable.bind(this) },
            { data: 'tiempo_estimado', searchable: false, sortable: false },
            { data: 'tiempo_real', searchable: false, sortable: false },
            {
                data: 'action', searchable: false, sortable: false, width: "10%", render: this._renderActionCell.bind(this)
            },
        ]

        /**
         * DROP ZONE FILES OT
         */
        this.configUploadDropzone = {
            domElement: '#dropzone-ot-files',
            nameId: "orden_trabajo_id",
            getUri: '/produccion/ordentrabajo/get_files',
            postUri: '/produccion/ordentrabajo/upload_files',
            resourcePath: 'orden_trabajo/' + this.modelId
        }
        if ($(this.configUploadDropzone.domElement).length > 0) {
            this.fileUploadDropzone = new FileUploadDropzone(this.configUploadDropzone)
        }
    }
    initDropFiles() {
        if ($(this.configUploadDropzone.domElement).length > 0) {
            this.fileUploadDropzone.init()
        }
    }
    configDatePickers() {
        const option = {
            altInput: true,
            altFormat: "d/m/Y",
            dateFormat: "Y-m-d",
            allowInput: true,
        }
        this.tiempoProcesamiento = this.otForm.find("#ot-tiempo-procesamiento")
        this.fechaImpresion = new DatePicker(this.otForm.find("#ot-fecha-impresion"), option)
        this.fechaEncuadernado = new DatePicker(this.otForm.find("#ot-fecha-encuadernado"), option)
        this.fechaEntregaExterno = new DatePicker(this.otForm.find("#ot-fecha-entrega-externo"), option)
        this.fechaEntregaReal = new DatePicker(this.otForm.find("#ot-fecha-entrega-real"), option)
        this.fechaEntregaEstimada = new DatePicker(this.otForm.find("#ot-fecha-entrega-estimada"), option)

        this.pendienteFerro = new DatePicker(this.otForm.find("#ot-pendiente-ferro"), option)
        this.ferroCliente = new DatePicker(this.otForm.find("#ot-ferro-cliente"), option)
        this.ferroOk = new DatePicker(this.otForm.find("#ot-ferro-ok"), option)
        this.plakeneTraslucido = new DatePicker(this.otForm.find("#ot-plakene-traslucido"), option)
        this.impresionColor = new DatePicker(this.otForm.find("#ot-impresion-color"), option)
        this.impresionBN = new DatePicker(this.otForm.find("#ot-impresion-bn"), option)

        this.portada = new DatePicker(this.otForm.find("#ot-portada"), option)
        this.plastificadoMate = new DatePicker(this.otForm.find("#ot-plastificado-mate"), option)
        this.prepGuillotina = new DatePicker(this.otForm.find("#ot-prep-guillotina"), option)
        this.prepCosido = new DatePicker(this.otForm.find("#ot-prep-cosido"), option)
        this.prepGrapado = new DatePicker(this.otForm.find("#ot-prep-grapado"), option)
        this.prepSolapa = new DatePicker(this.otForm.find("#ot-prep-solapa"), option)

        this.prepPrototipo = new DatePicker(this.otForm.find("#ot-prep-prototipo"), option)
        this.prepMarcapaginas = new DatePicker(this.otForm.find("#ot-prep-marcapaginas"), option)
        this.prepRetractilado = new DatePicker(this.otForm.find("#ot-prep-retractilado"), option)
        this.prepRetractilado5 = new DatePicker(this.otForm.find("#ot-prep-retractilado5"), option)





        this.espiral = new DatePicker(this.otForm.find("#ot-espiral"), option)
        this.embalaje = new DatePicker(this.otForm.find("#ot-embalaje"), option)
        this.envio = new DatePicker(this.otForm.find("#ot-envio"), option)

        //REVISION PREIMPRESION
        this.preFormatoAt = new DatePicker(this.otForm.find("#ot-preformato-date"), option)
        this.preLomoAt = new DatePicker(this.otForm.find("#ot-prelomo-date"), option)
        this.preSolapaAt = new DatePicker(this.otForm.find("#ot-presolapa-date"), option)
        this.preCodBarrasAt = new DatePicker(this.otForm.find("#ot-precodbarras-date"), option)
        this.preImposicionAt = new DatePicker(this.otForm.find("#ot-preimposicion-date"), option)






    }
    eventTareas() {
        this.otForm.on("change", ".select-maquina-tarea-datatable", this.handleTareaChange.bind(this))
        this.otForm.on("change", ".orden-tarea", this.handleTareaChange.bind(this))
        this.otForm.on("change", ".select-imposicion-tarea-datatable", this.handleTareaChange.bind(this))
        this.otForm.on("click", ".increase-order", (event) => {
            const input_orden_tarea = $(event.currentTarget).parent().parent().find('.orden-tarea')
            let actual_value = parseInt(input_orden_tarea.val())
            input_orden_tarea.val(actual_value + 1).trigger("change")
        })
        this.otForm.on("click", ".decrease-order", (event) => {
            const input_orden_tarea = $(event.currentTarget).parent().parent().find('.orden-tarea')
            let actual_value = parseInt(input_orden_tarea.val())
            if (actual_value > 0) {
                input_orden_tarea.val(actual_value - 1).trigger("change")
            }
        })
    }
    unbindEventTareas() {
        this.otForm.off("change", ".select-maquina-tarea-datatable")
        this.otForm.off("change", ".select-imposicion-tarea-datatable")
        this.otForm.off("change", ".orden-tarea")
        this.otForm.off("click", ".increase-order")
        this.otForm.off("click", ".decrease-order")
    }
    init() {
        this.initDropFiles()
        this.configDatePickers()
        this.initDatatableTareas()
        this.tareasTableItem.on("draw.dt", this.createSelectMaquinaTarea.bind(this))
        this.tareasTableItem.on("xhr.dt", this.unbindEventTareas.bind(this))
        this.otForm.on("click", "#btn-upload-portada", this.handleUploadPortada.bind(this))
        this.otForm.on("click", "#btn-delete-portada", this.handleDeletePortada.bind(this))
        this.btnFinalizarPedido.on("click", this.handleFinalizarPedido.bind(this))
        this.btnReactivarOt.on("click", this.handleReactivarPedido.bind(this))

        this.tareasTableItem.on("click", ".ot-tarea-btn-delete", this.handleTareaDeleteConfirmation.bind(this))
        this.item.on("click", "#btn-reset-tareas", this.handleResetTareasDeleteConfirmation.bind(this))
        this.otForm.on("click", ".ot-tarea-comment", this.handleNoteTarea.bind(this))
        $("#btn-update-tarea-comment").on("click", this.handleTareaNoteSubmit.bind(this))
        this.otForm.on("change", "#ot-comment", this.handleOtComment.bind(this))

        this._handleGetData()
        this.handleGetPortada()
    }
    initDatatableTareas() {
        this.datatableTareas = this.tareasTableItem.DataTable({
            processing: true,
            paging: false,
            layout: {
                topStart: 'pageLength',
                topEnd: 'search',
                bottomStart: 'info',
                bottomEnd: 'paging'
            },
            serverSide: true,
            responsive: true,
            createdRow: this.filterCreatedRow.bind(this),
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatableColumns,
            ajax: '/produccion/ordentrabajo/tareas/datatable/' + this.modelId
        });
    }
    getFormData() {
        let data = {}
        this.otForm.serializeArray().forEach((e) => {
            data[e.name] = e.value
        }
        )
        return data
    }
    _handleGetData() {
        Notiflix.Block.circle('.section-block');
        const ajax = new Ajax(`/produccion/ordentrabajo/summary/${this.modelId}`,
            null,
            null,
            this.handleSummarySuccess.bind(this),
            this.handleSummaryError.bind(this)
        )
        ajax.get();
    }
    _renderMaquinaSelectTable(d, t) {
        this.tareasId.push(d.id)
        return `<select id="select-maquina-tarea-${d.id}" data-maquina-id="${d.maquina_id}" data-id="${d.id}" name="maquina_id" class="select2 form-select select-maquina-tarea-datatable ${d.maquina_id ? '' : 'is-invalid'}" ${this.isOtFinalizada ? "disabled" : ""}>
        <option value="${d.maquina_id}" selected="selected">${d.maquina_name ?? ''}</option>
        </select>`

    }
    _renderImposicionSelectTable(d, t) {

        let render = `<select id="select-imposicion-tarea-${d.id}" data-imposicion-id="${d.imposicion_id}" data-id="${d.id}" name="imposicion_id" class="select2 form-select select-imposicion-tarea-datatable ${d.imposicion_id ? '' : 'is-invalid'}" ${this.isOtFinalizada ? "disabled" : ""}>
            <option value="${d.imposicion_id}" selected="selected">${d.name ?? ''}</option>
            </select>`
        return render

    }
    _renderActionCell(d, t) {

        let cell = `<div class="d-flex justify-content-start align-items-center gap-1">
            <a type="button" class="btn btn-xs ot-tarea-comment" data-id="${d.id}"> 
                <i class="ti ti-${d.comment ? "message" : "note"} ti-sm mx-2"></i>
            </a>
            <a type="button" class="btn btn-xs ot-tarea-btn-delete" data-id="${d.id}"><i class="ti ti-trash ti-sm mx-2 ${this.isOtFinalizada ? "d-none" : ""}" ></i></a>
        </div>`
        return cell;
    }
    _renderOrdenTarea(d, t) {

        return `
        <div class="d-flex justify-content-between aling-items-center gap-2 orden-tarea-cell">
            <input type="text" style="min-width:5rem" data-id="${d.id}" class="form-control form-control-sm orden-tarea mr-2" name="orden" value="${d.orden}" ${this.isOtFinalizada ? "disabled" : ""}>
            <div class="btn-group-vertical">
                <button type="button" class="btn btn-primary btn-outlined btn-xs increase-order"><i class="ti ti-chevron-up ti-xs"></i></button>
                <button type="button" class="btn btn-primary btn-xs decrease-order" data-id="${d.id}"><i class="ti ti-chevron-down ti-xs"></i></button>
            </div>
        </div>
        `
    }
    createSelectMaquinaTarea() {
        try {
            this.summaryData.tasks.forEach(element => {
                let selectItem = this.item.find("#select-maquina-tarea-" + element.id);
                if (element.presupuesto_linea_id && element.is_corte == false) this.createSelectMaquinaImpresion(selectItem)
                if (element.presupuesto_acabado_id) this.createSelectMaquinaAcabado(selectItem)
                if (element.presupuesto_encuadernado_id) this.createSelectMaquinaEncuadernacion(selectItem)
                if (element.presupuesto_manipulado_id || element.is_corte) this.createSelectMaquinaManipulado(selectItem)
                if (element.presupuesto_preimpresion_id) this.createSelectMaquinaAll(selectItem)
                if (element.presupuesto_extra_id) this.createSelectMaquinaAll(selectItem)
                if (this.summaryData.impresion_interior_bn) {
                    let isTareaImpresionInteriorBN = this.summaryData.impresion_interior_bn?.presupuesto_linea_id == element.presupuesto_linea_id && element.is_corte == false
                    if (isTareaImpresionInteriorBN) {
                        let selectItemImposicion = this.item.find("#select-imposicion-tarea-" + element.id);
                        this.createSelectImposicion(selectItemImposicion)
                    } else {
                        let selectItemImposicion = this.item.find("#select-imposicion-tarea-" + element.id);
                        selectItemImposicion.addClass("d-none");
                    }
                }
                if (this.summaryData.impresion_interior_color) {
                    let isTareaImpresionInteriorColor = this.summaryData.impresion_interior_color?.presupuesto_linea_id == element.presupuesto_linea_id && element.is_corte == false
                    if (isTareaImpresionInteriorColor) {
                        let selectItemImposicion = this.item.find("#select-imposicion-tarea-" + element.id);
                        this.createSelectImposicion(selectItemImposicion)
                    } else {
                        let selectItemImposicion = this.item.find("#select-imposicion-tarea-" + element.id);
                        selectItemImposicion.addClass("d-none");
                    }
                }
            });
        } catch (error) {
        } finally {
            this.eventTareas()

        }

    }
    createSelectMaquinaAcabado(selectItem) {
        let maquina_id = selectItem.data("maquina-id")
        let maquinaSelects = new ClassSelect(selectItem, `/tarifas/maquinas/acabado/select`, "Seleccione una maquina", true);
        maquinaSelects.init();
        if (maquina_id) {
            maquinaSelects.setVal(maquina_id)
        } else {
            maquinaSelects.reset()
        }
    }
    createSelectMaquinaManipulado(selectItem) {
        let maquina_id = selectItem.data("maquina-id")
        let maquinaSelects = new ClassSelect(selectItem, `/tarifas/maquinas/manipulado/select`, "Seleccione una maquina", true);
        maquinaSelects.init();
        if (maquina_id) {
            maquinaSelects.setVal(maquina_id)
        } else {
            maquinaSelects.reset()
        }
    }
    createSelectMaquinaImpresion(selectItem) {
        let maquina_id = selectItem.data("maquina-id")
        let maquinaSelects = new ClassSelect(selectItem, `/tarifas/maquinas/impresion/select`, "Seleccione una maquina", true);
        maquinaSelects.init();
        if (maquina_id) {
            maquinaSelects.setVal(maquina_id)
        } else {
            maquinaSelects.reset()
        }
    }
    createSelectMaquinaEncuadernacion(selectItem) {
        let maquina_id = selectItem.data("maquina-id")
        let maquinaSelects = new ClassSelect(selectItem, `/tarifas/maquinas/encuadernacion/select`, "Seleccione una maquina", true);
        maquinaSelects.init();
        if (maquina_id) {
            maquinaSelects.setVal(maquina_id)
        } else {
            maquinaSelects.reset()
        }
    }
    createSelectMaquinaAll(selectItem) {
        let maquina_id = selectItem.data("maquina-id")
        let maquinaSelects = new ClassSelect(selectItem, `/maquinas/select`, "Seleccione una maquina", true);
        maquinaSelects.init();
        if (maquina_id) {
            maquinaSelects.setVal(maquina_id)
        } else {
            maquinaSelects.reset()
        }
    }
    createSelectImposicion(selectItem) {
        let imposicionId = selectItem.data("imposicion-id")
        let imposicionSelect = new ClassSelect(selectItem, `/imposiciones/select`, "Seleccione una imposición", true);

        imposicionSelect.config.templateResult = (state) => {
            let $state = $(`
                <div class="d-flex flex-column justify-content-start align-items-start gap-1">
                <span class="item-text">${state.text}</span>
                <span class="badge text-bg-secondary">${state.desc ?? ''}</span>
                </div>`)
            return $state;
        }
        imposicionSelect.init();
        if (imposicionId) {
            imposicionSelect.setVal(imposicionId)
        } else {
            imposicionSelect.reset()
        }
    }



    filterCreatedRow(row, data, dataIndex, cells) {
        if (data.maquina_tarea.maquina_id == null) {
        }
    }

    /**========================================================================
     *                           DETAILS
     *========================================================================**/
    handleSummarySuccess(data) {
        try {
            this.summaryData = data
            this.otForm.off("change", ".ot-date")
            this.otForm.off("change", ".ot-pedido")
            this.otForm.off("change", ".ot-pedido-check")
            this.otForm.off("change", ".ot-preview")
            this.fillOtDetails()
            this.fillOtDates()
            this.fillPreimpresionReview()
            this.isOtFinalizada = this.summaryData.ot.estado == "F";
            this.datatableTareas.ajax.reload()
        } catch (error) {
            console.error(error)
        } finally {
            this.otForm.on("change", ".ot-date", this.handleDateChange.bind(this))
            this.otForm.on("change", ".ot-pedido", this.handlePedidoChange.bind(this))
            this.otForm.on("change", ".ot-pedido-check", this.handlePedidoCheckChange.bind(this))
            this.otForm.on("change", ".ot-preview", this.handlePreimpresionReviewChange.bind(this))
            Notiflix.Block.remove('.section-block');

        }

    }
    handleSummaryError(error) {
        Notiflix.Block.remove('.section-block');
    }
    fillPreimpresionReview() {
        this.otForm.find("[name=fecha_entrega_warning]").prop("checked", this.summaryData.ot.fecha_entrega_warning)
        this.otForm.find("[name=fecha_entrega_warning_revised]").prop("checked", this.summaryData.ot.fecha_entrega_warning_revised)
        this.otForm.find("[name=revisar_formato]").prop("checked", this.summaryData.ot.revisar_formato)
        this.otForm.find("[name=revisar_lomo]").prop("checked", this.summaryData.ot.revisar_lomo)
        this.otForm.find("[name=revisar_solapa]").prop("checked", this.summaryData.ot.revisar_solapa)
        this.otForm.find("[name=revisar_isbn]").prop("checked", this.summaryData.ot.revisar_isbn)
        this.otForm.find("[name=revisar_codigo_barras]").prop("checked", this.summaryData.ot.revisar_codigo_barras)
        this.otForm.find("[name=realizar_imposicion]").prop("checked", this.summaryData.ot.realizar_imposicion)
        this.otForm.find("[name=enviar_impresion]").prop("checked", this.summaryData.ot.enviar_impresion)
        this.otForm.find("[name=inaplazable]").prop("checked", this.summaryData.pedido.inaplazable)



    }
    fillOtDetails() {
        const progreso = this.summaryData.ot.progreso
        this.otForm.find("#ot-progress-bar").attr('aria-valuenow', progreso).text(progreso + "%").css("width", progreso + "%")
    }
    fillOtDates() {
        this.fechaImpresion.setDate(this.summaryData.pedido.fecha_impresion)
        this.fechaEncuadernado.setDate(this.summaryData.pedido.fecha_encuadernado)
        this.fechaEntregaExterno.setDate(this.summaryData.pedido.fecha_entrega_externo)
        this.fechaEntregaReal.setDate(this.summaryData.pedido.fecha_entrega_real)
        // this.fechaEntregaEstimada.setDate(this.summaryData.pedido.fecha_entrega_at)

        this.pendienteFerro.setDate(this.summaryData.dates.pendiente_ferro_at)
        this.ferroCliente.setDate(this.summaryData.dates.ferro_en_cliente_at)
        this.ferroOk.setDate(this.summaryData.dates.ferro_ok_at)
        // this.plakeneTraslucido.setDate(this.summaryData.dates.fecha_impresion_at)
        this.impresionColor.setDate(this.summaryData.dates.interior_color_at)
        this.impresionBN.setDate(this.summaryData.dates.interior_bn_at)
        this.portada.setDate(this.summaryData.dates.cubierta_at)
        this.plastificadoMate.setDate(this.summaryData.dates.plastificado_at)
        this.prepGuillotina.setDate(this.summaryData.dates.corte_at)
        this.prepCosido.setDate(this.summaryData.dates.cosido_at)
        this.prepSolapa.setDate(this.summaryData.dates.solapa_at)
        this.prepGrapado.setDate(this.summaryData.dates.grapado_at)

        this.prepPrototipo.setDate(this.summaryData.dates.prototipo_at)
        this.prepMarcapaginas.setDate(this.summaryData.dates.marcapaginas_at)
        this.prepRetractilado.setDate(this.summaryData.dates.retractilado_at)
        this.prepRetractilado5.setDate(this.summaryData.dates.retractilado5_at)

        this.espiral.setDate(this.summaryData.dates.fecha_impresion_at)
        this.embalaje.setDate(this.summaryData.dates.embalaje_at)
        this.envio.setDate(this.summaryData.dates.envio_at)
        this.pedidoEnEsperaCheck.prop("checked", this.summaryData.ot.is_pedido_espera);
        this.tiempoProcesamiento.val(this.summaryData.tiempo_procesamiento);
        if (this.summaryData.ot.pedido_espera_by) {
            this.pedidoEnEsperaBy.text([this.summaryData.ot.pedido_espera_by.first_name, this.summaryData.ot.pedido_espera_by.last_name].join(" "))
        } else {
            this.pedidoEnEsperaBy.text("");
        }
        this.otEstado.val(this.summaryData.ot.estado)
        this.preFormatoAt.setDate(this.summaryData.dates.pre_formato_at)
        this.preLomoAt.setDate(this.summaryData.dates.pre_lomo_at)
        this.preSolapaAt.setDate(this.summaryData.dates.pre_solapa_at)
        this.preCodBarrasAt.setDate(this.summaryData.dates.pre_codbarras_at)
        this.preImposicionAt.setDate(this.summaryData.dates.pre_imposicion_at)



    }

    handleTareaChange(event) {
        const key = $(event.currentTarget).attr("name")
        const data = {}
        data[key] = $(event.currentTarget).val()
        data["orden_trabajo_tarea_id"] = $(event.currentTarget).data("id")
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update/tarea",
            data,
            null,
            this.handleTareaChangeSuccess.bind(this),
            this.handleTareaChangeError.bind(this)
        )
        ajax.post();
    }
    handleTareaNoteSubmit(event) {
        const data = {}
        data["comment"] = $("#comment-tarea").val()
        data["orden_trabajo_tarea_id"] = this.tareaIdComment
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update/tarea",
            data,
            null,
            this.handleTareaChangeSuccess.bind(this),
            this.handleTareaChangeError.bind(this)
        )
        ajax.post();
    }
    handleTareaChangeSuccess(data) {
        this.datatableTareas.ajax.reload()
        this.tareaCommentModal.item.modal("hide")
        this._handleGetData();
    }
    handleTareaChangeError(error) { }
    handleOtComment(event) {
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update",
            {
                "orden_trabajo_id": this.modelId,
                "name": $(event.currentTarget).attr("name"),
                "comentarios": $(event.currentTarget).val()
            },
            null,
            (response) => {

                this._handleGetData();
                alertSuccess(response.message).fire()
            },
            null
        )
        ajax.post();
    }

    handleDateChange(event) {
        const key = $(event.currentTarget).attr("name")
        const data = {}
        const element = $(event.currentTarget);
        data[key] = $(event.currentTarget).val()
        data["orden_trabajo_id"] = this.modelId
        data["name"] = key;
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update/date",
            data,
            null,
            this.handleDateChangeSuccess.bind(this, element),
            this.handleDateChangeError.bind(this)
        )
        ajax.post();

    }
    handleDateChangeSuccess(formItem, response) {
        formItem.addClass("is-valid")
        alertSuccess(response.message).fire()
        this._handleGetData();
        if (response.user) {
            formItem.parent().find(".form-text").remove()
            formItem.parent().append(`<div class="form-text">${[response.user.first_name, response.user.last_name].join(" ")}</div>`)
        }
    }
    handleDateChangeError(errors) { }
    handlePedidoChange(event) {
        const key = $(event.currentTarget).attr("name")
        const data = {}
        const element = $(event.currentTarget);
        data[key] = $(event.currentTarget).val()
        data["orden_trabajo_id"] = this.modelId
        data["name"] = key;
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update/pedido/date",
            data,
            null,
            this.handleDateChangeSuccess.bind(this, element),
            this.handleDateChangeError.bind(this)
        )
        ajax.post();
    }
    handlePedidoCheckChange(event) {
        const key = $(event.currentTarget).attr("name")
        const data = {}
        data[key] = $(event.currentTarget).is(":checked") ? 1 : 0
        data["orden_trabajo_id"] = this.modelId
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update/pedido",
            data,
            null,
            this.handlePreimpresionReviewChangeSuccess.bind(this),
            this.handlePreimpresionReviewChangeError.bind(this)
        )
        ajax.post();
    }
    handlePreimpresionReviewChange(event) {
        const key = $(event.currentTarget).attr("name")
        const data = {}
        data[key] = $(event.currentTarget).is(":checked") ? 1 : 0
        data["orden_trabajo_id"] = this.modelId
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update",
            data,
            null,
            this.handlePreimpresionReviewChangeSuccess.bind(this),
            this.handlePreimpresionReviewChangeError.bind(this)
        )
        ajax.post();

    }
    handlePreimpresionReviewChangeSuccess(response) {
        this._handleGetData();
        alertSuccess(response.message).fire()

    }
    handlePreimpresionReviewChangeError(error) {

    }
    handleUploadPortada(event) {


        let data = new FormData()
        data.set("orden_trabajo_id", this.modelId)
        data.set("portada_file", this.otForm.find("#portada-file-input")[0].files[0])
        const ajax = new Ajax(
            "/produccion/ordentrabajo/upload/portada",
            data,
            null,
            this.handleUploadPortadaSuccess.bind(this),
            this.handleUploadPortadaError.bind(this)
        )
        ajax.ajaxForm("POST");

    }
    handleUploadPortadaSuccess(response) {
        this.handleGetPortada()
        popSuccessAlert(response.message)
        this.otForm.find("#portada-file-input").val(null)
    }
    handleUploadPortadaError(errors) {
        popSuccessAlert(errors?.message)
    }
    handleDeletePortada() {
        this.item.find(".portada-loader").prop("hidden", true);
        this.item.find("#portada-orden-trabajo").prop("hidden", false);
        let ajax = new Ajax('/produccion/ordentrabajo/portada/' + this.modelId,
            null,
            null,
            this.handleDeletePortadaSuccess.bind(this),
            this.handleGetPortadaError.bind(this),
        )
        alertConfirmationDelete("¿Estás seguro de realizar esta acción?")
            .then(result => {
                if (result.isConfirmed) {
                    ajax.delete();
                }
            })
    }
    handleDeletePortadaSuccess(response) {
        $('#portada-orden-trabajo').attr('src', '/assets/img/portada_not_found.png');
        this.item.find(".portada-loader").prop("hidden", true);
        this.item.find("#portada-orden-trabajo").prop("hidden", false);
        popSuccessAlert(response.message)
    }
    handleDeletePortadaError(response) {
        popErrorAlert(response.error)
    }

    handleGetPortada() {
        this.item.find(".portada-loader").prop("hidden", false);
        this.item.find("#portada-orden-trabajo").prop("hidden", true);
        $.ajax({
            url: '/produccion/ordentrabajo/portada/' + this.modelId,
            method: 'GET',
            xhrFields: {
                responseType: 'blob' // Expect binary data
            },
            success: this.handleGetPortadaSuccess.bind(this),
            error: this.handleGetPortadaError.bind(this)
        });
    }
    handleGetPortadaSuccess(data) {
        const imageUrl = URL.createObjectURL(data);
        $('#portada-orden-trabajo').attr('src', imageUrl);
        this.item.find(".portada-loader").prop("hidden", true);
        this.item.find("#portada-orden-trabajo").prop("hidden", false);
    }
    handleGetPortadaError() {
        this.item.find(".portada-loader").prop("hidden", true);
        this.item.find("#portada-orden-trabajo").prop("hidden", false);

    }
    handleFinalizarPedido() {
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update",
            {
                orden_trabajo_id: this.modelId,
                estado: 'F'
            },
            null,
            this.handleEstadoChangeSuccess.bind(this),
            this.handleEstadoChangeError.bind(this)
        );
        alertConfirmAction("Esta acción marcará la orden de trabajo como FINALIZADA")
            .then(result => {
                if (result.isConfirmed) {
                    ajax.post()
                }
            })
    }
    handleEstadoChangeSuccess(response) {
        popSuccessAlert(response.message)
        this.alertOrdenTrabajo.removeClass("alert-info").addClass("alert-success")
        this.btnFinalizarPedido.prop("disabled", true);
        window.location.reload();
    }
    handleEstadoChangeError() { }
    handleReactivarPedido() {
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update",
            {
                orden_trabajo_id: this.modelId,
                estado: 'I'
            },
            null,
            this.handleEstadoChangeSuccess.bind(this),
            this.handleEstadoChangeError.bind(this)
        );
        alertConfirmAction("Esta acción reactivará la orden de trabajo.")
            .then(result => {
                if (result.isConfirmed) {
                    ajax.post()
                }
            })
    }

    handleTareaDeleteConfirmation(event) {
        const orden_tarea_id = $(event.currentTarget).data("id")
        alertConfirmationDelete("¿Estás seguro de realizar esta acción?")
            .then(result => {
                if (result.isConfirmed) {
                    this.handleDeleteTarea(orden_tarea_id)
                }
            })
    }
    handleResetTareasDeleteConfirmation(event) {
        alertConfirmationDelete("¿Estás seguro de realizar esta acción?")
            .then(result => {
                if (result.isConfirmed) {
                    this.handleDeleteResetTareas()
                }
            })
    }
    handleDeleteResetTareas() {
        const ajax = new Ajax(
            "/produccion/ordentrabajo/reset/tareas/" + this.modelId,
            null,
            null,
            this.handleDeleteResetTareasSuccess.bind(this),
            this.handleDeleteResetTareasError.bind(this)
        );
        ajax.delete()
    }
    handleDeleteResetTareasSuccess(response) {
        this._handleGetData()
    }
    handleDeleteResetTareasError() { }
    handleDeleteTarea(orden_tarea_id) {
        const ajax = new Ajax(
            "/produccion/ordentrabajo/tareas/" + orden_tarea_id,
            null,
            null,
            this.handleDeleteTareaSuccess.bind(this),
            this.handleDeleteTareaError.bind(this)
        );
        ajax.delete()
    }
    handleDeleteTareaSuccess(response) {
        this.datatableTareas.ajax.reload()
    }
    handleDeleteTareaError() { }
    handleNoteTarea(event) {
        this.tareaIdComment = $(event.currentTarget).data("id");
        const tarea = this.summaryData.tasks.find(task => task.id == this.tareaIdComment)
        if (tarea) {
            $("#comment-tarea").attr("data-id", this.tareaIdComment)
            $("#comment-type").text(tarea.nombre ?? "")
            $("#comment-tarea").val(tarea.comment)
            this.tareaCommentModal.toggle()
        }
    }

}


export default OrdenTrabajo;