import ClassSelect from "../../../components/select2.js";
import Ajax from "../../../components/ajax.js";
import { alertError, alertSuccess } from "../../../components/alerts/sweetAlert.js";


class PlanningRotativa {
    constructor(domItem) {
        this.item = domItem
        this.tablePlanningRot = this.item.find("#planning-rotativa-datatable")
        this.tablePlanningPlana = this.item.find("#planning-plana-datatable")
        this.papelGramajeTablePlanning = this.item.find("#planning-papel-datatable")
        this.papelPliegoTablePlanning = this.item.find("#planning-pliego-datatable")
        this.papelImpresionHeader = this.item.find('#papel-impresion-name-header')
        this.papelImpresionPlanaHeader = this.item.find('#papel-impresion-name-plana-header')


        this.checkAllMetros = this.item.find("#metros-check-all")
        this.checkAllPliegos = this.item.find("#pliegos-check-all")
        this.tiempoPlanaTotal = this.tablePlanningPlana.find('#horas-sel-total')

        this.datatableColumns = [
            { data: 'otId', searchable: false, sortable: false, width: "3rem" },
            { data: 'fecha_entrega_real_at', searchable: true, sortable: false, width: "15rem" },
            { data: 'presupuesto_titulo', searchable: true, sortable: false, width: "20rem" },
            { data: 'maquina_planning_nombre', searchable: true, sortable: false, width: "10rem" },
            { data: 'ot_tirada', searchable: false, sortable: false, width: "5rem" },
            { data: 'papel_ancho', searchable: false, sortable: false, width: "5rem", render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'papel_alto', searchable: false, sortable: false, width: "5rem", render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'papel_impresion', searchable: false, sortable: false },
            { data: 'papel_gramaje',name:"presupuesto_linea.gramaje", searchable: false, sortable: false, width: "5rem", render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'corte', searchable: false, sortable: false, render: this.renderCorteImage.bind(this), width: "10rem" },
            { data: 'metros_check', searchable: false, sortable: false, render: d => `<input class="form-check-input metros-check" data-id="${d}" type="checkbox" value="" />` },
            { data: 'metros', searchable: false, sortable: false, render: d => `<span class="autonumeric">${d}</span>` },

            { data: 'action', searchable: false, sortable: false, render: this._renderBtnAction },

        ]
        this.datatablePlanaColumns = [
            { data: 'otId', searchable: false, sortable: false, width: "3rem" },
            { data: 'fecha_entrega_real_at', searchable: true, sortable: false, width: "15rem" },
            { data: 'presupuesto_titulo', searchable: true, sortable: false, width: "20rem" },
            { data: 'maquina_planning_nombre', searchable: true, sortable: false, width: "10rem" },
            { data: 'ot_tirada', searchable: false, sortable: false, width: "5rem" },
            { data: 'papel_ancho', searchable: false, sortable: false, width: "5rem", render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'papel_alto', searchable: false, sortable: false, width: "5rem", render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'papel_impresion', searchable: false, sortable: false },
            { data: 'papel_gramaje', name:"presupuesto_linea.gramaje", searchable: false, sortable: false, width: "5rem", render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'pliegos_check', searchable: false, sortable: false, render: d => `<input class="form-check-input pliegos-check" data-id="${d}" type="checkbox" value="" />` },
            { data: 'pliegosPedido', searchable: false, sortable: false, render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'tiempo_real_sum', searchable: false, sortable: false,render: d => this.formatSeconds(parseFloat(d))},
            { data: 'action', searchable: false, sortable: false, render: this._renderBtnAction },

        ]
        this.papelGramajeDatatableColumns = [
            { data: 'papelImpresionNombre', searchable: true, sortable: true },
            { data: 'papelImpresionGramaje', searchable: true, sortable: true },
            { data: 'tareasCount', searchable: true, sortable: true },
            { data: 'totalTirada', searchable: false, sortable: false },
            { data: 'metros', searchable: false, sortable: false, render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'tiempoReal', searchable: false, sortable: false, render: d => this.formatSeconds(d) },
            {
                data: 'action', searchable: false, sortable: false, render: (d) => {
                    return `<button type="button" class="btn btn-primary btn-sm w-100 papel-gramaje-btn" data-id="${d.data.papelImpresionId}" data-bs-toggle="button">${d.title}</button>`
                }
            },


        ]
        this.papelPliegoDatatableColumns = [
            { data: 'papelImpresionNombre', searchable: true, sortable: true },
            { data: 'papelImpresionGramaje', searchable: true, sortable: true },
            { data: 'tareasCount', searchable: true, sortable: true },
            { data: 'totalTirada', searchable: false, sortable: false },
            { data: 'pliegosPedido', searchable: false, sortable: false, render: d => `<span class="autonumeric">${d}</span>` },
            { data: 'tiempoReal', searchable: false, sortable: false, render: d => this.formatSeconds(d) },
            {
                data: 'action', searchable: false, sortable: false, render: (d) => {
                    return `<button type="button" class="btn btn-primary btn-sm w-100 papel-pliego-btn" data-id="${d.data.papelImpresionId}" data-bs-toggle="button">${d.title}</button>`
                }
            },


        ]
        this.maquinaSelectFilter = new ClassSelect(
            this.tablePlanningRot.find(".planning-maquina-select"),
            `/produccion/ordentrabajo/planning/select/maquina/rotativa`,
            "Seleccione una maquina",
            true, {
                dropdownCssClass: "h-2"
            }, $('body'));
        this.papelImpresionFilter = new ClassSelect(this.tablePlanningRot.find(".planning-papel-select"), `/produccion/ordentrabajo/planning/select/papel/rotativa`, "Seleccione un papel", true, {}, $('body'));
        this.maquinaSelectFilterPlana = new ClassSelect(this.tablePlanningPlana.find(".planning-maquina-select"), `/produccion/ordentrabajo/planning/select/maquina/plana`, "Seleccione una maquina", true, {}, $('body'));
        this.maquinaPadreSelectFilterPlana = new ClassSelect(this.tablePlanningPlana.find(".planning-maquina-padre-select"), `/produccion/ordentrabajo/planning/select/maquina/padre/plana`, "Máquina padre", true, {}, $('body'));
        this.papelImpresionFilterPlana = new ClassSelect(this.tablePlanningPlana.find(".planning-papel-select"), `/produccion/ordentrabajo/planning/select/papel/plana`, "Seleccione un papel", true, {}, $('body'));
        this.maquinaSelectFilter.config.dropdownParent = this.item
    }
    init() {
        const autoNumericOptions = {
            digitGroupSeparator: ".",
            decimalCharacter: ",",
            allowDecimalPadding: 'floats',
            currencySymbol: '(m)',
            currencySymbolPlacement: 's',
            decimalPlaces: 2,
            unformatOnSubmit: true,

        }
        const autoNumericPliegosOptions = {
            digitGroupSeparator: ".",
            decimalCharacter: ",",
            allowDecimalPadding: 'floats',
            decimalPlaces: 0,
            unformatOnSubmit: true,

        }
        this.totalMetros = new AutoNumeric(this.item.find('#total-metros')[0], autoNumericOptions);
        this.totalMetrosSel = new AutoNumeric(this.item.find('#metros-sel-total')[0], autoNumericOptions);
        this.totalPliegos = new AutoNumeric(this.item.find('#total-pliegos')[0], autoNumericPliegosOptions);
        this.totalPliegosSel = new AutoNumeric(this.item.find('#pliegos-sel-total')[0], autoNumericPliegosOptions);

        this.maquinaSelectFilter.init()
        this.papelImpresionFilter.init()
        this.maquinaSelectFilterPlana.init()
        this.papelImpresionFilterPlana.init()
        this.maquinaPadreSelectFilterPlana.init();
        this.checkAllMetros.on('change', () => {
            let isChecked = this.checkAllMetros.prop('checked')
            this.item.find(".metros-check").prop('checked', isChecked).trigger("change")
        })
        this.checkAllPliegos.on('change', () => {
            let isChecked = this.checkAllPliegos.prop('checked')
            this.item.find(".pliegos-check").prop('checked', isChecked).trigger("change")
        })
        this.papelGramajeTablePlanning.on('click', '.papel-gramaje-btn', this.filterPapelGramaje.bind(this))
        this.papelPliegoTablePlanning.on('click', '.papel-pliego-btn', this.filterPapelGramajePlana.bind(this))

        this.papelImpresionFilter.onChange(() => {
            this.papelImpresionHeader.text(this.papelImpresionFilter.getText())
        })
        this.papelImpresionFilterPlana.onChange(() => {
            this.papelImpresionPlanaHeader.text(this.papelImpresionFilter.getText())
        })

        this.datatablePlanningRot = this.tablePlanningRot.DataTable({
            processing: true,
            orderCellsTop: true,
            dom: 'lrtip',
            serverSide: true,
            responsive: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            createdRow: (row,data,dataIndex) => {
                this.getColorOtStatus(row,data)
            },
            columns: this.datatableColumns,
            ajax: '/produccion/ordentrabajo/planning/rotativa/datatable'
        });
        this.datatablePlanningPlana = this.tablePlanningPlana.DataTable({
            processing: true,
            orderCellsTop: true,
            dom: 'lrtip',
            serverSide: true,
            responsive: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.datatablePlanaColumns,
            createdRow: (row,data,dataIndex) => {
                this.getColorOtStatus(row,data)
            },
            ajax: {
                url : '/produccion/ordentrabajo/planning/plana/datatable',
                data : d => {
                    if(this.maquinaPadreSelectFilterPlana.getVal()){
                        d.padre_id = this.maquinaPadreSelectFilterPlana.getVal()
                    }
                }
            }
        });
        this.papelGramajeDatatable = this.papelGramajeTablePlanning.DataTable({
            processing: true,
            orderCellsTop: true,
            dom: 'lrtip',
            serverSide: true,
            responsive: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.papelGramajeDatatableColumns,
            ajax: '/produccion/ordentrabajo/planning/papel/datatable'
        });
        this.papelPliegoDatatable = this.papelPliegoTablePlanning.DataTable({
            processing: true,
            orderCellsTop: true,
            dom: 'lrtip',
            serverSide: true,
            responsive: true,
            pageLength: 10,
            language: {
                url: "/themes/vuexy/vendor/libs/datatables-sk/plugins/i18n/es-ES.json"
            },
            columns: this.papelPliegoDatatableColumns,
            ajax: '/produccion/ordentrabajo/planning/papel/plana/datatable'
        });
        /**
         * PLANNING ROTATIVA
         */
        this.tablePlanningRot.on("keyup", ".planning-filter", (event) => {
            console.log(this.datatablePlanningRot.column($(event.currentTarget).attr("name")))
            let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePlanningRot.column(columnIndex).search($(event.currentTarget).val()).draw()
        })
        this.tablePlanningRot.on("change", ".planning-maquina-select", (event) => {
            let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePlanningRot.column(columnIndex).search(this.maquinaSelectFilter.getText()).draw()
        })
        this.tablePlanningRot.on("change", ".planning-papel-select", (event) => {
            let columnIndex = this.datatableColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePlanningRot.column(columnIndex).search(this.papelImpresionFilter.getText()).draw()
        })
        this.papelGramajeDatatable.on('draw', this.addTotalFooter.bind(this))

        this.tablePlanningRot.on('change', ".metros-check", this.calcMetrosCheck.bind(this))
        this.tablePlanningRot.on("click",'.change-corte',this.toggleCorte.bind(this))
        /**
         * PLANNING PLANA
         */
        this.tablePlanningPlana.on("keyup", ".planning-filter", (event) => {
            console.log(this.datatablePlanningRot.column($(event.currentTarget).attr("name")))
            let columnIndex = this.datatablePlanaColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePlanningPlana.column(columnIndex).search($(event.currentTarget).val()).draw()
        })
        this.tablePlanningPlana.on("change", ".planning-maquina-select", (event) => {
            let columnIndex = this.datatablePlanaColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePlanningPlana.column(columnIndex).search(this.maquinaSelectFilterPlana.getText()).draw()
        })
        this.tablePlanningPlana.on("change", ".planning-papel-select", (event) => {
            let columnIndex = this.datatablePlanaColumns.findIndex((element) => element.data == $(event.currentTarget).attr("name"))
            this.datatablePlanningPlana.column(columnIndex).search(this.papelImpresionFilterPlana.getText()).draw()
        })
        this.tablePlanningPlana.on("change", ".planning-maquina-padre-select", (event) => {
            this.datatablePlanningPlana.ajax.reload();
        })
        this.papelPliegoDatatable.on('draw', this.addTotalFooterPliego.bind(this))

        this.tablePlanningPlana.on('change', ".pliegos-check", this.calcPliegosCheck.bind(this))
    }
    _renderBtnAction(d) {
        return `<a href="/produccion/ordentrabajo/edit/${d.data.otId}" class="ot-tarea-comment" data-id="${d.data.otId}"><i class="ti ti-eye"></i></a>`
    }
    _columnFiltering() {
        this.api().columns()
        console.log(this.api().columns())
    }
    filterPapelGramaje(event) {
        const papelImpresionId = $(event.currentTarget).data('id')
        this.getPapelImpresion(papelImpresionId)
    }
    filterPapelGramajePlana(event) {
        const papelImpresionId = $(event.currentTarget).data('id')
        this.getPapelImpresionPlana(papelImpresionId)
    }
    getPapelImpresion(papelImpresionId) {
        let ajax = new Ajax('/configuracion/papelesimpresion/show/' + papelImpresionId,
            null,
            null,
            this.getPapelImpresionSuccess.bind(this),
            this.getPapelImpresionError.bind(this)
        )
        ajax.get()
    }
    getPapelImpresionPlana(papelImpresionId) {
        let ajax = new Ajax('/configuracion/papelesimpresion/show/' + papelImpresionId,
            null,
            null,
            this.getPapelImpresionPlanaSuccess.bind(this),
            this.getPapelImpresionPlanaError.bind(this)
        )
        ajax.get()
    }
    getPapelImpresionSuccess(response) {
        this.papelImpresionFilter.setOption(response.id, response.nombre)
        this.tablePlanningRot.find('input[name=papel_gramaje]').val(response.gramaje).trigger("change")
        this.papelImpresionHeader.text(response.nombre)
    }
    getPapelImpresionError(response) { }
    getPapelImpresionPlanaSuccess(response) {
        this.papelImpresionFilterPlana.setOption(response.id, response.nombre)
        this.tablePlanningPlana.find('input[name=papel_gramaje]').val(response.gramaje).trigger("change")
        this.papelImpresionPlanaHeader.text(response.nombre)
    }
    getPapelImpresionPlanaError(response) { }
    formatSeconds(s) {
        const hours = Math.floor(s / 60 / 60)
        const minutes = Math.floor(s / 60 % 60)
        return [hours, minutes].join(':').replace(/\b(\d)\b/g, '0$1');
    }
    addTotalFooter() {
        const seconds = this.papelGramajeDatatable.column(5).data().reduce((a, b) => {
            return parseFloat(a) + parseFloat(b)
        }, 0)
        const metros = this.papelGramajeDatatable.column(4).data().map((e) => parseFloat(e))
        $('#total-tiempo-papel').text(this.formatSeconds(parseInt(seconds)))
        this.totalMetros.set(metros.reduce((a, b) => a + b, 0))


    }
    addTotalFooterPliego() {
        const seconds = this.papelPliegoDatatable.column(5).data().reduce((a, b) => {
            return parseFloat(a) + parseFloat(b)
        }, 0)
        const pliegos = this.papelPliegoDatatable.column(4).data().map((e) => parseFloat(e))
        $('#total-tiempo-pliego').text(this.formatSeconds(seconds))
        this.totalPliegos.set(pliegos.reduce((a, b) => a + b, 0))


    }
    calcMetrosCheck() {
        const metros_sel = this.datatablePlanningRot.rows((idx, data, node) => {
            return $(node).find('input[type="checkbox"]').prop('checked');
        }).data().toArray().map((e) => parseFloat(e.metros))
        this.totalMetrosSel.set(metros_sel.reduce((a, b) => a + b, 0))

    }
    calcPliegosCheck() {
        const metros_sel = this.datatablePlanningPlana.rows((idx, data, node) => {
            return $(node).find('input[type="checkbox"]').prop('checked');
        }).data().toArray().map((e) => parseInt(e.pliegosPedido))
        const tiempo_total_sel = this.datatablePlanningPlana.rows((idx, data, node) => {
            return $(node).find('input[type="checkbox"]').prop('checked');
        }).data().toArray().map((e) => parseFloat(e.tiempo_real_sum))
        this.totalPliegosSel.set(metros_sel.reduce((a, b) => a + b, 0))
        const totalSeconds = tiempo_total_sel.reduce((a,b) => a+b,0)
        console.log("Total seconds",totalSeconds);
        this.tiempoPlanaTotal.text(this.formatSeconds(totalSeconds))


    }
    renderCorteImage(data) {
        const tipo_corte = data.tipo_corte == "bobina" ? "cortadora_bobinas" : "guillotina";
        console.log(data.tipo_corte)
        return `
        <a type="button" class="btn btn-outline-secondary bg-white btn-xs change-corte" data-id=${data.otId}>
            <div class="avatar avatar-size-xs">
                <img src="/assets/img/${tipo_corte}.png" alt="${data.tipo_corte}" width="10px" height="10px">
            </div>
        </a>
        `
    }
    toggleCorte(event){
        let otId = $(event.currentTarget).data('id')
        let ajax = new Ajax("/produccion/ordentrabajo/planning/tarea/toggle/corte/" + otId,
            null,
            null,
            this.toggleCorteSuccess.bind(this),
            this.toggleCorteError.bind(this)
        )
        ajax.post()
    }
    toggleCorteSuccess(response){
        this.datatablePlanningRot.ajax.reload()
        alertSuccess(response.message).fire()
    }
    toggleCorteError(){
    }
    getColorOtStatus(row,data){
        let ajax = new Ajax("/produccion/ordentrabajo/color/"+data.otId,null,null,
            (response) => {
                $(row).css("border-left",`10px solid ${response.color}`)
                $(row).css("border-right",`10px solid ${response.color}`)
            },null
        )
        ajax.get()
    }


}




export default PlanningRotativa;