$(document).ready(async function () {
    const url = window.location.href
    const id = url.split('/')[url.split('/').length - 1]

    if (id && id !== 'create') {
        await buscarDadosCadastro(id)
    }

    async function buscarDadosCadastro(id) {
        try {
            $.LoadingOverlay('show')
            const response = await requisicao('GET', `/sisplan/pcpfaixa/v1/faixa?`, `ID=${id}`, '', 3600000)
            const json = await response.json()

            if (!json) {
                return
            }

            const { resultado, mensagem } = json
            if (mensagem?.codigo !== 200) {
                throw mensagem?.mensagem
            }

            preencherDadosCadastro(resultado)
        } catch (error) {
            console.error(error)
            msgErro('Não foi possível buscar os dados.')
        } finally {
            $.LoadingOverlay('hide')
        }
    }

    function preencherDadosCadastro(dados) {
        if (!dados) {
            return
        }

        $('#txtFaixa').val(dados.faixa)
        $('#txtDescricao').val(dados.descricao)
        $('#selectTipo').val(dados.tipo)
        $('#txtTam01').val(dados.tam01.trim())
        $('#txtTam02').val(dados.tam02.trim())
        $('#txtTam03').val(dados.tam03.trim())
        $('#txtTam04').val(dados.tam04.trim())
        $('#txtTam05').val(dados.tam05.trim())
        $('#txtTam06').val(dados.tam06.trim())
        $('#txtTam07').val(dados.tam07.trim())
        $('#txtTam08').val(dados.tam08.trim())
        $('#txtTam09').val(dados.tam09.trim())
        $('#txtTam10').val(dados.tam10.trim())
        $('#txtTam11').val(dados.tam11.trim())
        $('#txtTam12').val(dados.tam12.trim())
        $('#txtTam13').val(dados.tam13.trim())
        $('#txtTam14').val(dados.tam14.trim())
        $('#txtTam15').val(dados.tam15.trim())
        $('#txtTam16').val(dados.tam16.trim())
        $('#txtTam17').val(dados.tam17.trim())
        $('#txtTam18').val(dados.tam18.trim())
        $('#txtTam19').val(dados.tam19.trim())
        $('#txtTam20').val(dados.tam20.trim())
        $('#txtTam21').val(dados.tam21.trim())
        $('#txtTam22').val(dados.tam22.trim())
        $('#txtTam23').val(dados.tam23.trim())
        $('#txtTam24').val(dados.tam24.trim())
        $('#txtTam25').val(dados.tam25.trim())
        $('#txtTam26').val(dados.tam26.trim())
        $('#txtTam27').val(dados.tam27.trim())
        $('#txtTam28').val(dados.tam28.trim())
        $('#txtTam29').val(dados.tam29.trim())
        $('#txtTam30').val(dados.tam30.trim())
        $('#txtTam31').val(dados.tam31.trim())
        $('#txtTam32').val(dados.tam32.trim())
        $('#txtTam33').val(dados.tam33.trim())
        $('#txtTam34').val(dados.tam34.trim())
        $('#txtTam35').val(dados.tam35.trim())
        $('#txtTam36').val(dados.tam36.trim())
        $('#txtTam37').val(dados.tam37.trim())
        $('#txtTam38').val(dados.tam38.trim())
        $('#txtTam39').val(dados.tam39.trim())
        $('#txtTam40').val(dados.tam40.trim())
        $('#txtTam41').val(dados.tam41.trim())
        $('#txtTam42').val(dados.tam42.trim())
        $('#txtTam43').val(dados.tam43.trim())
        $('#txtTam44').val(dados.tam44.trim())
        $('#txtTam45').val(dados.tam45.trim())

        $('#txtFaixa').prop('disabled', true)
    }

    for (let i = 1; i < 46; i++) {
        const tam = i.toString().padStart(2, '0')

        $(`#txtTam${tam}`).autocompleta(1, `JSON={ "tabela":"TABTAM", "camposSelect":["TAM CHAVE, ACRESCIMO DESCRICAO"], "where": [] }`, [`#txtTam${tam}`], ['CHAVE'], [], undefined, [true])
        $(`#btnTam${tam}`).pesquisa_serverside([`#txtTam${tam}`], ['TAM', 'ACRESCIMO'], ['ACRESCIMO', 'TAM'], '{"tabela":"TABTAM", "camposSelect":[ "TAM", "ACRESCIMO" ], "where": null}', 'Pesquisa Tamanho', undefined, [true])
        $(`#btnLimpaTam${tam}`).on('click', function () {
            $(`#txtTam${tam}`).val('')
        })
    }

    $('#btnGravar').on('click', function () {
        salvar()
    })

    async function salvar() {
        try {
            $.LoadingOverlay('show')
            const dados = retornarDadosSalvar()

            const response = await requisicao('POST', `/sisplan/pcpfaixa/v1/faixa?`, '', JSON.stringify(dados), 3600000)
            const json = await response.json()

            if (!json) {
                return
            }

            const { mensagem } = json
            if (mensagem?.codigo !== 200) {
                throw mensagem?.mensagem
            }

            toastr.success("Dados gravados com sucesso!", "Confirmação", {
                toastClass: "alert",
                iconClasses: {
                    error: "alert-error",
                    info: "alert-info",
                    success: "alert-success",
                    warning: "alert-warning",
                },
                positionClass: "toast-top-center",
                progressBar: true,
                timeOut: 1000,
                fadeOut: 1000,
                onHidden() {
                    window.location.href = `${BASE_URI}/pcpfaixa`
                }
            }).css({
                "margin-top": "20%",
                width: "500px",
                "max-width": "500px",
            })
        } catch (error) {
            console.error(error)
            msgErro(error || 'Não foi possível salvar os dados.')
        } finally {
            $.LoadingOverlay('hide')
        }
    }

    function retornarDadosSalvar() {
        const dados = {
            id,
            faixa: $('#txtFaixa').val(),
            descricao: $('#txtDescricao').val(),
            tipo: $('#selectTipo').val(),
            tam01: $('#txtTam01').val(),
            tam02: $('#txtTam02').val(),
            tam03: $('#txtTam03').val(),
            tam04: $('#txtTam04').val(),
            tam05: $('#txtTam05').val(),
            tam06: $('#txtTam06').val(),
            tam07: $('#txtTam07').val(),
            tam08: $('#txtTam08').val(),
            tam09: $('#txtTam09').val(),
            tam10: $('#txtTam10').val(),
            tam11: $('#txtTam11').val(),
            tam12: $('#txtTam12').val(),
            tam13: $('#txtTam13').val(),
            tam14: $('#txtTam14').val(),
            tam15: $('#txtTam15').val(),
            tam16: $('#txtTam16').val(),
            tam17: $('#txtTam17').val(),
            tam18: $('#txtTam18').val(),
            tam19: $('#txtTam19').val(),
            tam20: $('#txtTam20').val(),
            tam21: $('#txtTam21').val(),
            tam22: $('#txtTam22').val(),
            tam23: $('#txtTam23').val(),
            tam24: $('#txtTam24').val(),
            tam25: $('#txtTam25').val(),
            tam26: $('#txtTam26').val(),
            tam27: $('#txtTam27').val(),
            tam28: $('#txtTam28').val(),
            tam29: $('#txtTam29').val(),
            tam30: $('#txtTam30').val(),
            tam31: $('#txtTam31').val(),
            tam32: $('#txtTam32').val(),
            tam33: $('#txtTam33').val(),
            tam34: $('#txtTam34').val(),
            tam35: $('#txtTam35').val(),
            tam36: $('#txtTam36').val(),
            tam37: $('#txtTam37').val(),
            tam38: $('#txtTam38').val(),
            tam39: $('#txtTam39').val(),
            tam40: $('#txtTam40').val(),
            tam41: $('#txtTam41').val(),
            tam42: $('#txtTam42').val(),
            tam43: $('#txtTam43').val(),
            tam44: $('#txtTam44').val(),
            tam45: $('#txtTam45').val(),
        }

        return dados
    }

    $('#btnVoltar').on('click', function () {
        window.history.back()
    })
})