<div class="row" id="appBalancedoc" v-cloak>
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="card-head-row">
                    <div class="card-title" style="cursor: pointer;" data-toggle="modal" data-target="#modal_buscar_movimientos_mensuales_documento">
                        <button class="btn btn-secondary"> <span class="fa fa-search"></span> Buscar</button>
                    </div>
                    <div class="card-tools">
                        <div class="text-right">
                            <h6 class="fw-bold text-uppercase text-success op-8">Total</h6>
                            <h3 class="fw-bold">{{ total }}</h3>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="display table table-striped table-hover dataTable table-head-bg-primary table-bordered-bd-primary" id="tabla_balanced">
                        <thead>
                            <tr>
                                <th>Fecha</th>
                                <th>Empleado</th>
                                <th>Descripción</th>
                                <th>Divisa</th>
                                <th>Cliente</th>
                                <th>Tasa</th>
                                <th>Documento</th>
                                <th class="text-right">Monto</th>
                                <th>Cuenta</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="row in balance">
                                <td style="width: 12%;">{{ row.fecha }}</td>
                                <td>{{ row.empleado }}</td>
                                <td>{{ row.descripcion }}</td>
                                <td>{{row.divisa}}</td>
                                <td>{{ row.cliente }}</td>
                                <td>{{ row.tasa }}</td>
                                <td><a v-if="row.url!=''" :href="row.url">{{ row.correlativo }}</a><b v-else>{{ row.correlativo }}</b></td>
                                <td class="text-right">{{ row.monto }}</td>
                                <td>{{row.cuenta}}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="card-head-row">
                    <div class="card-title"></div>
                    <div class="card-tools">
                        <div class="text-right">
                            <h6 class="fw-bold text-uppercase text-success op-8">Total Credito</h6>
                            <h3 class="fw-bold">{{ total_credito }}</h3>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="display nowrap table table-striped table-hover dataTable table-head-bg-primary table-bordered-bd-primary" id="tabla_balance_creditosd">
                        <thead>
                            <tr>
                                <th>Fecha</th>
                                <th>Descripción</th>
                                <th>Divisa</th>
                                <th class="text-right">Monto</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="row in balance_creditos">
                                <td style="width: 12%;">{{ row.fecha }}</td>
                                <td>{{ row.descripcion }}</td>
                                <td>{{ row.divisa }}</td>
                                <td class="text-right">{{ row.monto }}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <form autocomplete="off" @submit.prevent="buscar" id="b_form_busquedad">
        <div class="modal fade" id="modal_buscar_movimientos_mensuales_documento" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Buscar movimiento</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-row">
                            <div class="col-sm-4">
                                <div class="form-group form-floating-label">
                                    <input id="b_fecha_desde" type="date" class="form-control input-border-bottom" v-model="fecha_desde">
                                    <label for="b_fecha_desde" class="placeholder">Fecha desde</label>
                                </div>
                            </div>
                            <div class="col-sm-4">
                                <div class="form-group form-floating-label">
                                    <input id="b_fecha_hasta" type="date" class="form-control input-border-bottom" v-model="fecha_hasta">
                                    <label for="b_fecha_hasta" class="placeholder">Fecha hasta</label>
                                </div>
                            </div>
                            <div class="col-sm-4">
                                <div class="form-group form-floating-label">
                                    <select class="form-control input-border-bottom" v-model="tipo" id="b_ing_egr">
                                        <option value="0">TODOS</option>
                                        <option value="1">INGRESO</option>
                                        <option value="2">EGRESO</option>
                                    </select>
                                    <label for="b_ing_egr" class="placeholder">Ingreso / Egreso</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-row">
                            <div class="col-sm-4">
                                <div class="form-group form-floating-label">
                                    <select class="form-control input-border-bottom" id="b_divisa_pagard" @change="obtenerMetodosSegunDivisad">
                                        <option value="">&nbsp;</option>
                                        <?php foreach ($divisas as $row) : ?>
                                            <option value="<?= $row['div_id'] ?>"><?= $row['div_nombre'] ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                    <label for="b_divisa_pagar" class="placeholder">Divisa</label>
                                </div>
                            </div>
                            <div class="col-sm-4">
                                <div class="form-group form-floating-label">
                                    <select class="form-control input-border-bottom" id="b_metodo_pagard" @change="obtenerCuentasSegunMetodod">
                                        <option value="">&nbsp;</option>
                                        <option v-for="row in metodos_de_pagos" :value="row.md_id">{{ row.mp_nombre }}</option>
                                    </select>
                                    <label for="b_metodo_pagar" class="placeholder">Metodo de pago</label>
                                </div>
                            </div>
                            <div class="col-sm-4">
                                <div class="form-group form-floating-label">
                                    <select class="form-control input-border-bottom" id="b_cuenta_pagard">
                                        <option value="">&nbsp;</option>
                                        <option v-for="row in cuentas" :value="row.id">{{ row.alias }} - {{ row.tipo }} - {{ row.codigo }}</option>
                                    </select>
                                    <label for="b_cuenta_pagar" class="placeholder">Cuenta</label>
                                </div>
                            </div>
                        </div>
                        <div class="form-group form-floating-label">
                            <select class="form-control input-border-bottom" v-model="b_categoria" id="b_cateagoriad">
                                <option value="">TODOS</option>
                                <?php foreach ($t_categorias as $row) : ?>
                                    <option value="<?= $row['id'] ?>"><?= $row['categoria'] ?></option>
                                <?php endforeach; ?>
                            </select>
                            <label for="b_cateagoriad" class="placeholder">Categoria</label>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class="alert alert-warning" role="alert" v-for="row in errorForm">
                                    {{ row }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary  btn-sm" data-dismiss="modal">Cerrar</button>
                        <button class="btn btn-sm btn-secondary" type="button" @click="resetearFormulario">
                            <span class="d-none d-sm-inline-block">Mes actual</span>
                        </button>
                        <button v-if="cargando" class="btn btn-sm btn-primary" disabled>
                            <i class="loader loader-info"></i>
                        </button>
                        <button v-else class="btn btn-sm btn-primary" type="submit">
                            <i class="fas fa-save fa-fw" aria-hidden="true"></i>
                            <span class="d-none d-sm-inline-block">Buscar</span>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>
<script>
    new Vue({
        el: '#appBalancedoc',
        data: {
            div_locale: '',
            div_simbolo: '',
            div_decimal: 2,
            fecha_desde: moment().format('YYYY-MM-DD'),
            fecha_hasta: moment().format('YYYY-MM-DD'),
            b_categoria: '',
            tipo: '',
            cuentas: [],
            metodos_de_pagos: [],
            balance_creditos: [],
            balance: [],
            total: 0,
            total_credito: 0,
            errorForm: [],
            cargando: false,
            cargando_tabla: '',
        },
        created() {
            this.total = 0;
            this.obtenerBalanceDelMes();
        },
        methods: {
            resetearFormulario() {
                this.obtenerBalanceDelMes();
                document.getElementById('b_form_busquedad').reset();
                this.fecha_desde = '';
                this.fecha_hasta = moment().format('YYYY-MM-DD');
                this.errorForm = [];
            },
            obtenerBalanceDelMes(event) {
                $("#tabla_balanced, #tabla_balance_creditosd").DataTable().destroy();
                this.cargando_tabla = 'is-loading is-loading-lg';
                axios.get('ingresosegresos/obtenerBalanceDelMesPorDocumento').then(response => {
                    if (response.data.errors == null) {
                        this.balance = response.data.balance;
                        this.total = response.data.total
                        this.balance_creditos = response.data.balance_creditos;
                        this.total_credito = response.data.total_credito;
                    } else {
                        let total_errores = response.data.errors.length
                        for (let i = 0; i < total_errores; i++) {
                            notificacion('fa fa-ban', 'Advertencia', response.data.errors[i], 'warning');
                        }
                    }
                }).catch(e => notificacion()).finally(() => {
                    this.cargando_tabla = '';

                    let buttonCommonA = {
                        exportOptions: {
                            format: {
                                body: function(data, row, column, node) {
                                    if (column === 5 || column === 7) {
                                        return convertir_a_float(data)
                                    } else {
                                        return data.replace(/<[^>]*>?/g, '');
                                    }
                                }
                            }
                        }
                    };

                    let buttonCommonB = {
                        exportOptions: {
                            format: {
                                body: function(data, row, column, node) {
                                    if (column === 3) {
                                        return convertir_a_float(data)
                                    } else {
                                        return data.replace(/<[^>]*>?/g, '');
                                    }
                                }
                            }
                        }
                    };

                    $("#tabla_balanced").DataTable({
                        order: [],
                        dom: 'Bfrtip',
                        buttons: [
                            $.extend(true, {}, buttonCommonA, {
                                extend: 'excelHtml5',
                                title: 'Balance de movimiento desde ' + moment(this.fecha_desde).format('DD-MM-YYYY') + ' hasta ' + moment(this.fecha_desde).format('DD-MM-YYYY'),
                            }),
                        ]
                    });

                    $("#tabla_balance_creditosd").DataTable({
                        order: [],
                        dom: 'Bfrtip',
                        buttons: [
                            $.extend(true, {}, buttonCommonB, {
                                extend: 'excelHtml5',
                                title: 'Balance de movimiento (CREDITOS) desde ' + moment(this.fecha_desde).format('DD-MM-YYYY') + ' hasta ' + moment(this.fecha_desde).format('DD-MM-YYYY'),
                            }),
                        ]
                    });
                });
            },
            obtenerMetodosSegunDivisad() {

                let divisa = document.getElementById('b_divisa_pagard');

                document.getElementById('b_metodo_pagard').selectedIndex = 0;
                document.getElementById('b_cuenta_pagard').selectedIndex = 0;
                this.errorForm = [];
                this.metodos_de_pagos = [];
                this.cuentas = [];

                if (divisa.value && this.errorForm.length == 0) {
                    axios.get('ingresosegresos/obtenerMetodosSegunDivisaYCuentas/' + Number(divisa.value)).then(response => {
                        if (response.data.errors == null) {
                            this.metodos_de_pagos = response.data.metodos;
                            this.cuentas = response.data.cuentas;
                        } else {
                            this.divisa.selectedIndex = 0;
                            let total_errores = response.data.errors.length
                            for (let i = 0; i < total_errores; i++) {
                                notificacion('fa fa-ban', 'Advertencia', response.data.errors[i], 'warning');
                            }
                        }
                    }).catch(e => notificacion());
                }
            },
            obtenerCuentasSegunMetodod() {

                let metodo = document.getElementById('b_metodo_pagard');
                document.getElementById('b_cuenta_pagard').selectedIndex = 0;

                this.errorForm = [];
                this.cuentas = [];

                if (metodo.value && this.errorForm.length == 0) {
                    axios.get('ingresosegresos/obtenerCuentasSegunMetodo/' + Number(metodo.value)).then(response => {
                        if (response.data.errors == null) {
                            this.cuentas = response.data;
                        } else {
                            let total_errores = response.data.errors.length
                            for (let i = 0; i < total_errores; i++) {
                                notificacion('fa fa-ban', 'Advertencia', response.data.errors[i], 'warning');
                            }
                        }
                    }).catch(e => notificacion());
                } else {
                    this.obtenerMetodosSegunDivisa();
                }
            },
            buscar() {

                this.errorForm = [];
                this.cargando = true;
                this.cargando_tabla = 'is-loading is-loading-lg';
                $("#tabla_balanced, #tabla_balance_creditosd").DataTable().destroy();

                axios({
                    method: 'post',
                    url: 'ingresosegresos/buscarBalanceDocumento',
                    data: {
                        id_divisa: document.getElementById('b_divisa_pagard').value,
                        id_metodo_divisa: document.getElementById('b_metodo_pagard').value,
                        id_cuenta_metodo: document.getElementById('b_cuenta_pagard').value,
                        fecha_desde: this.fecha_desde,
                        fecha_hasta: this.fecha_hasta,
                        tipo: this.tipo,
                        categoria: this.b_categoria
                    },
                    transformRequest: serializar(),
                }).then(response => {
                    if (response.data.errors == null) {
                        this.balance = response.data.balance;
                        this.total = response.data.total;
                        this.balance_creditos = response.data.balance_creditos;
                        this.total_credito = response.data.total_credito;
                    } else {
                        let total_errores = response.data.errors.length
                        for (let i = 0; i < total_errores; i++) {
                            notificacion('fa fa-ban', 'Advertencia', response.data.errors[i], 'warning');
                        }
                    }
                }).catch(e => notificacion()).finally(() => {
                    this.cargando = false;
                    this.cargando_tabla = '';

                    let buttonCommonA = {
                        exportOptions: {
                            format: {
                                body: function(data, row, column, node) {
                                    if (column === 5 || column === 7) {
                                        return convertir_a_float(data)
                                    } else {
                                        return data.replace(/<[^>]*>?/g, '');
                                    }
                                }
                            }
                        }
                    };

                    let buttonCommonB = {
                        exportOptions: {
                            format: {
                                body: function(data, row, column, node) {
                                    if (column === 3) {
                                        return convertir_a_float(data)
                                    } else {
                                        return data.replace(/<[^>]*>?/g, '');
                                    }
                                }
                            }
                        }
                    };

                    $("#tabla_balanced").DataTable({
                        order: [],
                        dom: 'Bfrtip',
                        buttons: [
                            $.extend(true, {}, buttonCommonA, {
                                extend: 'excelHtml5',
                                title: 'Balance de movimiento desde ' + moment(this.fecha_desde).format('DD-MM-YYYY') + ' hasta ' + moment(this.fecha_desde).format('DD-MM-YYYY'),
                            }),
                        ]
                    });

                    $("#tabla_balance_creditosd").DataTable({
                        order: [],
                        dom: 'Bfrtip',
                        buttons: [
                            $.extend(true, {}, buttonCommonB, {
                                extend: 'excelHtml5',
                                title: 'Balance de movimiento (CREDITOS) desde ' + moment(this.fecha_desde).format('DD-MM-YYYY') + ' hasta ' + moment(this.fecha_desde).format('DD-MM-YYYY'),
                            }),
                        ]
                    });
                });
            },
            moneda(num, div_locale, div_simbolo, decimal = 2) {
                return monedaMoneda(num, div_locale, div_simbolo, decimal);
            },
            decimal(num, div_locale, decimal = 2) {
                return monedaDecimal(num, div_locale, decimal);
            },
        }
    });
</script>
