import Ajax from "../../components/ajax.js"
import ClassSelect from "../../components/select2.js";
import DatePicker from "../../components/datepicker.js";
import { alertConfirmationDelete } from "../../components/alerts/sweetAlert.js";
import Modal from "../../components/modal.js"

class OrdenTrabajo {
    constructor(domItem) {
        this.item = domItem
        this.otForm = this.item.find("#ot-edit-form")
        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.btnResetTareas = this.item.find("#btn-reset-tareas")
        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_id', searchable: false, sortable: false },
            { 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)
            },
        ]




    }
    configDatePickers() {
        const option = {
            altInput: true,
            altFormat: "d/m/Y",
            dateFormat: "Y-m-d",
            allowInput: true,
        }
        this.tiempoProcesamiento = new DatePicker(this.otForm.find("#ot-tiempo-procesamiento"), {
            dateFormat: "H:i",
            enableTime: true,
            noCalendar: true,
            time_24hr: true,
            allowInput: true,
        })
        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.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.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)


    }
    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("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", ".orden-tarea")
        this.otForm.off("click", ".increase-order")
        this.otForm.off("click", ".decrease-order")
    }
    init() {
        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-finalizar-orden-pedido", this.handleFinalizarPedido.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("keyup","#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() {
        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'}">
        <option value="${d.maquina_id}" selected="selected">${d.maquina_name ?? ''}</option>
        </select>`

    }
    _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"></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}">
            <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.tareasId.forEach(element => {
                let selectItem = this.item.find("#select-maquina-tarea-" + element);
                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()
                }
            });
        } catch (error) {
        } finally {
            this.eventTareas()

        }

    }
    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-preview")
            this.fillOtDetails()
            this.fillOtDates()
            this.fillPreimpresionReview()
        } catch (error) {

        } finally {
            this.otForm.on("change", ".ot-date", this.handleDateChange.bind(this))
            this.otForm.on("change", ".ot-preview", this.handlePreimpresionReviewChange.bind(this))

        }

    }
    handleSummaryError(error) { }
    fillPreimpresionReview() {
        console.log(this.summaryData.ot)
        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)

    }
    fillOtDetails() {
        const progreso = this.summaryData.ot.progreso
        this.otForm.find("#ot-progress-bar").attr('aria-valuenow',progreso).text(progreso + "%").css("width",progreso + "%")
        this.otForm.find("#ot-paginas").val(this.summaryData.presupuesto.paginas)
        this.otForm.find("#ot-tirada").val(this.summaryData.presupuesto.tirada)
        this.otForm.find("#ot-merma").val(this.summaryData.presupuesto.merma)
    }
    fillOtDates() {
        this.fechaImpresion.setDate(this.summaryData.dates.fecha_impresion_at)
        this.fechaEncuadernado.setDate(this.summaryData.dates.fecha_encuadernado_at)
        // this.fechaEntregaExterno.setDate(this.summaryData.dates.fecha_entrega_externo_)
        this.fechaEntregaReal.setDate(this.summaryData.dates.fecha_entrega_real_at)
        this.fechaEntregaEstimada.setDate(this.summaryData.dates.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.portada.setDate(this.summaryData.dates.cubierta_at)
        this.plastificadoMate.setDate(this.summaryData.dates.plastificado_at)
        this.prepGuillotina.setDate(this.summaryData.dates.corte_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)

    }

    handleTareaChange(event) {
        const key = $(event.currentTarget).attr("name")
        const data = {}
        data[key] = $(event.currentTarget).val()
        data["orden_trabajo_tarea_id"] = $(event.currentTarget).data("id")
        console.log(data);
        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"] = $("#comment-tarea").data("id")
        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){
        console.log($(event.currentTarget).val())
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update",
            {
                "orden_trabajo_id" : this.modelId,
                "name" : $(event.currentTarget).attr("name"),
                "comentarios" : $(event.currentTarget).val()
            },
            null,
            null,
            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;
        console.log(data)
        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")
        formItem.parent().append(`<div class="form-text">${[response.user.first_name, response.user.last_name].join(" ")}</div>`)
    }
    handleDateChangeError(errors) { }
    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) {

    }
    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()
        this.otForm.find("#portada-file-input").val(null)
    }
    handleUploadPortadaError(errors) { }
    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(errors) { }
    handleFinalizarPedido() {
        const ajax = new Ajax(
            "/produccion/ordentrabajo/update",
            {
                orden_trabajo_id: this.modelId,
                estado: 'F'
            },
            null,
            this.handleEstadoChangeSuccess.bind(this),
            this.handleEstadoChangeError.bind(this)
        );
        ajax.post()
    }
    handleEstadoChangeSuccess() {
        this.alertOrdenTrabajo.removeClass("alert-info").addClass("alert-success")
        this.btnFinalizarPedido.prop("disabled", true);
    }
    handleEstadoChangeError() { }
    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.handleDeleteTareaSuccess.bind(this),
            this.handleDeleteTareaError.bind(this)
        );
        ajax.delete()
    }
    handleDeleteResetTareasSuccess(response) {
        this.datatableTareas.ajax.reload()
    }
    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) {
        let tarea_id = $(event.currentTarget).data("id");
        const tarea = this.summaryData.tasks.find(task => task.id == tarea_id)
        if (tarea) {
            $("#comment-tarea").attr("data-id", tarea_id)
            $("#comment-type").text(tarea.nombre ?? "")
            $("#comment-tarea").val(tarea.comment)
            this.tareaCommentModal.toggle()
        }
    }

}


export default OrdenTrabajo;