@extends('ventas.base')

@section('venta_subtitle')
    Crédito
@endsection

@section('venta_content')
    @php($credito = $venta->formaPago()->credito)
    <div class="ui grid">
        <div class="row">
            <div class="two wide column">Fecha</div>
            <div class="six wide column" id="fecha" data-status="static">
                <span id="fecha_data">
                    {{$credito->pago->fecha->format('d-m-Y')}}
                </span>
                <a href="#" id="fecha_edit">
                    <i class="edit icon"></i>
                </a>
                <div class="ui calendar hidden" id="fecha_input">
                    <div class="ui left icon input">
                        <i class="calendar icon"></i>
                        <input type="text" name="fecha" />
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="two wide column">Banco</div>
            <div class="six wide column" id="banco" data-status="static">
                <span id="banco_data">
                    @if (isset($credito->pago->banco))
                        {{$credito->pago->banco->nombre}}
                    @else
                        No definido
                    @endif
                </span>
                <a href="#" id="banco_edit">
                    <i class="edit icon"></i>
                </a>
                <div class="ui search selection dropdown hidden" id="banco_input">
                    <input type="hidden" name="banco" />
                    <i class="dropdown icon"></i>
                    <div class="default text">Banco</div>
                    <div class="menu">
                    @foreach ($bancos as $banco)
                        <div class="item" data-value="{{$banco->id}}">{{$banco->nombre}}</div>
                    @endforeach
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="two wide column">Valor</div>
            <div class="six wide column" id="valor" data-status="static">
                <span id="valor_data">
                    {{$format->ufs($credito->pago->valor())}}
                </span>
                <a href="#" id="valor_edit">
                    <i class="edit icon"></i>
                </a>
                <div class="ui right labeled input hidden" id="valor_input">
                    <input type="text" name="valor" />
                    <div class="ui basic label">UF</div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('page_styles')
    <style>
        .hidden {
            display: none !important;
        }
    </style>
@endpush
@push('page_scripts')
    <script>
        const credito = {
            ids: {},
            data: {
                venta: {{$venta->id}},
                credito: {{$credito->id}},
                fecha: new Date({{$credito->pago->fecha->format('Y')}},
                        {{$credito->pago->fecha->format('m')}}+1,
                        {{$credito->pago->fecha->format('d')}}),
                banco: {
                    @if (isset($credito->pago->banco))
                    id: {{$credito->pago->banco->id}},
                    nombre: '{{$credito->pago->banco->nombre}}'
                    @else
                    id: 0,
                    nombre: ''
                    @endif
                },
                valor: {{$credito->pago->valor()}},
                bancos: JSON.parse('{!! json_encode($bancos) !!}')
            },
            elements: {},
            change() {
                return {
                    status: (id, status) => {
                        this.elements[id].dataset.status = status
                    }
                }
            },
            hide() {
                return {
                    data: id => {
                        this.elements[id + '.data'].innerHTML = ''
                        this.elements[id + '.data'].classList.add('hidden')
                        this.elements[id + '.data'].hidden = true
                    },
                    input: id => {
                        this.elements[id + '.input'].classList.add('hidden')
                        this.elements[id + '.input'].hidden = true
                    }
                }
            },
            show() {
                return {
                    data: id => {
                        this.elements[id + '.data'].classList.remove('hidden')
                        this.elements[id + '.data'].hidden = false
                    },
                    input: id => {
                        this.elements[id + '.input'].classList.remove('hidden')
                        this.elements[id + '.input'].hidden = false
                    }
                }
            },
            draw() {
                return {
                    edit: (id) => {
                        this.change().status(id, 'edit')
                        this.show().input(id)
                        this.update()[id]()
                    },
                    static: (id, text) => {
                        this.change().status(id, 'static')
                        this.hide().input(id)
                        this.elements[this.ids.fields[id] + '.data'].innerHTML = this.format()[id](text)
                    }
                }
            },
            send(id, value) {
                const url = '{{$urls->api}}/venta/{{$venta->id}}/credito'
                const body = new FormData()
                body.set(id, value)
                return fetchAPI(url, {method: 'post', body}).then(response => {
                    if (!response) {
                        return
                    }
                    return response.json().then(json => {
                        if (!json.status) {
                            return
                        }
                        this.data.fecha = new Date(json.credito.pago.fecha)
                        this.data.banco.id = json.credito.pago.banco.id
                        this.data.banco.nombre = json.credito.pago.banco.nombre
                        this.data.valor = json.credito.pago.valor / json.credito.pago.uf
                    })
                })
            },
            edit() {
                return {
                    fecha: fecha => {
                        this.send('fecha', fecha).then(() => {
                            this.draw().static('fecha', this.data.fecha)
                        })
                    },
                    banco: banco_id => {
                        this.send('banco', banco_id).then(() => {
                            this.draw().static('banco', this.data.banco.nombre)
                        })
                    },
                    valor: valor => {
                        this.send('valor', valor).then(() => {
                            this.draw().static('valor', this.data.valor)
                        })
                    }
                }
            },
            format() {
                return {
                    fecha: value => {
                        const dateFormatter = new Intl.DateTimeFormat('es-CL', {year: 'numeric', month: 'numeric', day: 'numeric'})
                        return dateFormatter.format(value)
                    },
                    banco: value => {
                        if (value === '') {
                            value = 'No definido'
                        }
                        return value
                    },
                    valor: value => {
                        const numberFormatter = new Intl.NumberFormat('es-CL', {minimumFractionDigits: 2, maximumFractionDigits: 2})
                        return numberFormatter.format(value) + ' UF'
                    }
                }
            },
            update() {
                return {
                    fecha: () => {
                        const $fecha = $(this.elements.fecha.querySelector('div.ui.calendar'))
                        $fecha.calendar('set date', this.data.fecha)
                        $fecha.calendar('focus')
                    },
                    banco: () => {
                        const $dropdown = $(this.elements.banco.querySelector('div.ui.dropdown'))
                        $dropdown.dropdown('clear')
                        if (this.data.banco.id !== 0) {
                            $dropdown.dropdown('set selected', this.data.banco.id)
                        }
                        $dropdown.dropdown('toggle')
                    },
                    valor: () => {
                        const input = this.elements.valor.querySelector('input')
                        input.value = this.data.valor ?? ''
                        input.focus()
                    }
                }
            },
            watch(id) {
                this.elements[id + '.edit'].addEventListener('click', event => {
                    const elem = event.currentTarget.parentNode
                    const id = elem.id
                    const status = elem.dataset.status
                    if (status !== 'static') {
                        return
                    }
                    this.draw().edit(id)
                })
            },
            register(name, elem_id) {
                this.elements[name] = document.getElementById(elem_id)
            },
            setup(ids) {
                this.ids = ids

                Object.entries(this.ids.fields).forEach(entry => {
                    const name = entry[0]
                    const field = entry[1]
                    this.register(name, field)
                    this.register(name + '.data', field + '_data')
                    this.register(name + '.input', field + '_input')
                    this.register(name + '.edit', field + '_edit')
                    this.watch(field)
                })
                calendar_date_options['onChange'] = (date, text, mode) => {
                    if (date === this.data.fecha) {
                        return
                    }
                    this.edit().fecha([date.getFullYear(), date.getMonth()+1, date.getDate()].join('-'))
                }
                calendar_date_options['onHide'] = () => {
                    this.draw().static('fecha', this.data.fecha)
                }
                $(this.elements.fecha).find('div.ui.calendar').calendar(calendar_date_options)
                $(this.elements.banco).find('div.ui.dropdown').dropdown({
                    onChange: (value, text, $element) => {
                        if (value === '' || value === this.data.banco.id) {
                            return
                        }
                        this.edit().banco(value)
                    },
                    onHide: () => {
                        this.draw().static('banco', this.data.banco.nombre)
                }
                })
                this.elements.valor.querySelector('input').addEventListener('blur', event => {
                    let valor = event.currentTarget.value
                    if (valor.includes(',')) {
                        valor = valor.replaceAll('.', '').replace(',', '.')
                    }
                    if (parseFloat(valor) === this.data.valor) {
                        this.draw().static('valor', this.data.valor)
                        return
                    }
                    this.edit().valor(valor)
                })
            }
        }
        $(document).ready(() => {
            credito.setup({
                fields: {
                    fecha: 'fecha',
                    banco: 'banco',
                    valor: 'valor'
                }
            })
        })
    </script>
@endpush
