import Ajax from '../ajax.js'
import ClassSelect from '../select2.js'
class ImposicionForm {
    constructor(domItem) {
        this.item = domItem
        this.modelId = this.item.data("id");
        this.btnSubmitUpdateImposicion = this.item.find("#btnSubmitUpdateImposicion")
        this.btnSubmitNewImposicion = this.item.find("#btnSubmitNewImposicion")
        this.selectImposicionEsquemaItem = this.item.find("#imposicion-esquema-select")
        this.renderSchemaDiv = this.item.find("#imposicion-esquema-render");
        this.schemaLink = this.item.find(".imposicion-esquema-link")
        this.selectImposicionEsquema = new ClassSelect(this.selectImposicionEsquemaItem, '/imposiciones/esquema/select', 'Seleccione un esquema', true)
        this.imposicionEsquemaData = {}
        this.initialData = {
            "ancho": null,
            "alto": null,
            "unidades": null,
            "etiqueta": null,
            "maquina": null,
            "orientacion": null
        }
        this.formData = this.initialData

    }
    initSelectImposicionEsquema() {

        this.selectImposicionEsquema.init()
        this.selectImposicionEsquema.onChange(this.handleGetImposicionEsquema.bind(this))


    }
    resize() {
        let w = this.renderSchemaDiv.width()
        let h = this.renderSchemaDiv.height()

        let svgX = this.renderSchemaDiv.find("svg").width()
        this.renderSchemaDiv.find("svg").attr("width", w)
        this.renderSchemaDiv.find("svg").attr("height", h)

        this.renderSchemaDiv.find("svg").attr('viewBox', `0 0 ${svgX} ${h + 100}`);
    }
    load(status = false) {
        if (status) {
            Notiflix.Block.circle('.section-block');
        } else {
            Notiflix.Block.remove('.section-block');
        }

    }
    loadSchema(status = false) {
        if (status) {
            Notiflix.Block.circle('.section-block-esquema');
        } else {
            Notiflix.Block.remove('.section-block-esquema');
        }

    }
    init() {
        this.btnSubmitUpdateImposicion.on("click", this.handleUpdate.bind(this))
        this.handleGetData()
        this.initSelectImposicionEsquema()
        this.schemaLink.attr("disabled", "disabled")
        $(window).on("resize", this.resize.bind(this))
    }
    initNew() {
        this.btnSubmitNewImposicion.on("click", this.handleNew.bind(this))
        this.initSelectImposicionEsquema()
        this.schemaLink.attr("disabled", "disabled")
        $(window).on("resize", this.resize.bind(this))

    }
    handleGetImposicionEsquema() {
        this.loadSchema(true)
        let imposicion_esquema_id = this.selectImposicionEsquema.getVal()
        let ajax = new Ajax(`/imposiciones/esquema/find/${imposicion_esquema_id}`, null, null, this.handleGetImposicionEsquemaSuccess.bind(this), this.handleGetDataError.bind(this))
        if (imposicion_esquema_id) {
            ajax.get()
        } else {
            this.loadSchema(false)
            this.renderSchemaDiv.find("svg").empty()
        }

    }
    handleGetImposicionEsquemaSuccess(response) {
        this.renderSchemaDiv.empty()
        this.imposicionEsquemaData = response
        this.renderSchemaDiv.append(response.svg_schema)
        let svgX = this.renderSchemaDiv.width()
        let svgY = this.renderSchemaDiv.height()
        this.schemaLink.removeAttr("disabled")
        this.schemaLink.attr("href", `/imposiciones/esquema/edit/${response.id}`)
        this.renderSchemaDiv.find("svg").attr('viewBox', `0 0 ${svgX} ${svgY}`);

        this.resize()
        this.loadSchema(false)

    }
    handleGetImposicionEsquemaError(error) {
        this.loadSchema(false)
    }
    handleGetData() {
        this.load(true)
        let ajax = new Ajax(`/imposiciones/find/${this.modelId}`, null, null, this.handleGetDataSuccess.bind(this), this.handleGetDataError.bind(this))
        ajax.get()

    }
    getFormData() {
        let data = {}
        this.item.serializeArray().forEach((e) => {
            data[e.name] = e.value
        }
        )
        this.formData = data
        return this.formData
    }
    setFormData(data) {
        Object.entries(data).forEach(([key, value], index) => {
            this.item.find(`input[name=${key}]`).val(value)
            this.item.find(`select[name=${key}]`).val(value)
            if (key == "imposicion_esquema" && value) {
                this.selectImposicionEsquema.setOption(value.id, value.name)
                this.schemaLink.removeAttr("disabled")
                this.schemaLink.attr("href", `/imposiciones/esquema/edit/${value.id}`)
            }
        })

    }
    disable() {
        Object.entries(this.initialData).forEach(([key, value], index) => {
            this.item.find(`input[name=${key}]`).prop("disabled", "disabled")
            this.item.find(`select[name=${key}]`).prop("disabled", "disabled")
        })
    }
    handleGetDataSuccess(response) {
        this.setFormData(response)
        this.load(false)
    }
    handleGetDataError() { }
    handleNew() {
        this.load(true)
        let ajax = new Ajax(`/imposiciones/create`, this.getFormData(), null, this.postSuccessNew.bind(this), this.postErrorNew.bind(this))
        ajax.post()
    }
    handleUpdate() {
        this.load(true)
        let ajax = new Ajax(`/imposiciones/${this.modelId}`, this.getFormData(), null, this.postSuccess.bind(this), this.postError.bind(this))
        ajax.post()
    }
    handleDelete(id) {
        let ajax = new Ajax(`/imposiciones/${id}`, null, null, this.deleteSuccess.bind(this), this.deleteError.bind(this))
        ajax.delete()
    }
    deleteSuccess(response) {
        popSuccessAlert(response.message)
    }
    deleteError(error) {
        popErrorAlert(error.responseJSON.message)
    }
    postSuccess(response) {
        this.load(false)
        this.setFormData(response.data)
        popSuccessAlert(response.message)
    }

    postError(error) {
        this.load(false)
        popErrorAlert(error.responseJSON.message)
        this.validationErrors(error.responseJSON.errors)
    }
    postSuccessNew(response) {
        this.load(false)
        this.disable()
        this.item.find(".invalid-feedback").remove()
        this.btnSubmitNewImposicion.addClass("d-none")
        popSuccessAlert(response.message)
    }
    postErrorNew(error) {
        this.load(false)
        this.validationErrors(error.responseJSON.errors)
        popErrorAlert(error.responseJSON.message)
    }
    validationErrors(errors) {
        this.item.find(".invalid-feedback").remove()
        Object.entries(errors).forEach(([key, value], index) => {
            let el = this.item.find(`input[name=${key}]`)
            this.addError(el, value)
        })
    }
    addError(el, error) {
        el.addClass("is-invalid")
        el.parent().append(`<div class="invalid-feedback">${error}</div>`)
    }
}

export default ImposicionForm;