var query = []
var msg = ''
var cfg_ticket = new Object()
var last_forma_pago = ''


var tickets_controllers = {
    init: function(){
        $$('cmd_nuevo_ticket').attachEvent('onItemClick', cmd_nuevo_ticket_click)
        $$('cmd_ticket_from_ticket').attachEvent('onItemClick', cmd_ticket_from_ticket_click)
        $$('cmd_ticket_to_invoice').attachEvent('onItemClick', cmd_ticket_to_invoice_click)
        $$('cmd_ticket_report_pdf').attachEvent('onItemClick', cmd_ticket_report_pdf_click)
        $$('cmd_ticket_report_xls').attachEvent('onItemClick', cmd_ticket_report_xls_click)
        $$('cmd_generar_ticket').attachEvent('onItemClick', cmd_generar_ticket_click)
        $$('cmd_cerrar_ticket').attachEvent('onItemClick', cmd_cerrar_ticket_click)
        $$('cmd_new_invoice_from_ticket').attachEvent('onItemClick', cmd_new_invoice_from_ticket_click)
        $$('cmd_close_ticket_invoice').attachEvent('onItemClick', cmd_cerrar_ticket_click)
        $$('cmd_cancelar_ticket').attachEvent('onItemClick', cmd_cancelar_ticket_click)
        $$('cmd_move_tickets_right').attachEvent('onItemClick', cmd_move_tickets_right_click)
        $$('cmd_move_tickets_left').attachEvent('onItemClick', cmd_move_tickets_left_click)
        $$('cmd_ticket_notes').attachEvent('onItemClick', cmd_ticket_notes_click)
        $$('tsearch_product_key').attachEvent('onKeyPress', tsearch_product_key_press)
        $$('grid_tickets').attachEvent('onItemClick', grid_tickets_click)
        $$('grid_tdetails').attachEvent('onItemClick', grid_ticket_details_click)
        $$('grid_tdetails').attachEvent('onBeforeEditStop', grid_tickets_details_before_edit_stop)
        $$('gt_productos_found').attachEvent('onValueSuggest', gt_productos_found_click)
        $$('cmd_ticket_filter_today').attachEvent('onItemClick', cmd_ticket_filter_today_click)
        $$('filter_year_ticket').attachEvent('onChange', filter_year_ticket_change)
        $$('filter_month_ticket').attachEvent('onChange', filter_month_ticket_change)
        $$('filter_dates_ticket').attachEvent('onChange', filter_dates_ticket_change)
        $$('chk_is_invoice_day').attachEvent('onChange', chk_is_invoice_day_change)
        $$('grid_tickets_active').attachEvent('onItemDblClick', grid_tickets_active_double_click)
        $$('grid_tickets_invoice').attachEvent('onItemDblClick', grid_tickets_invoice_double_click)
        $$('tsearch_client_key').attachEvent('onKeyPress', tsearch_client_key_press)
        $$('grid_ticket_clients_found').attachEvent('onValueSuggest', grid_ticket_clients_found_click)
        $$('grid_tdetails').attachEvent('onAfterRender', grid_tdetails_render)

        webix.extend($$('grid_tickets'), webix.ProgressBar)
        webix.extend($$('grid_tickets_active'), webix.ProgressBar)
    }
}


function current_dates_tickets(){
    var fy = $$('filter_year_ticket')
    var fm = $$('filter_month_ticket')
    var d = new Date()

    fy.blockEvent()
    fm.blockEvent()

    fm.setValue(d.getMonth() + 1)
    webix.ajax().sync().get('/values/filteryearsticket', function(text, data){
        var values = data.json()
        fy.getList().parse(values)
        fy.setValue(d.getFullYear())
    })

    fy.unblockEvent()
    fm.unblockEvent()
}


function get_tickets(filters){
    if(filters == undefined){
        filters = {'opt': 'today'}
    }

    var grid = $$('grid_tickets')
    grid.showProgress({type: 'icon'})

    webix.ajax().get('/tickets', filters, {
        error: function(text, data, xhr) {
            msg_error('Error al consultar')
        },
        success: function(text, data, xhr) {
            var values = data.json();
            grid.clearAll();
            if (values.ok){
                grid.parse(values.rows, 'json')
            }
        }
    })
}


function cmd_ticket_filter_today_click(){
    get_tickets()
}


function filter_year_ticket_change(nv, ov){
    var fm = $$('filter_month_ticket')
    filters = {'opt': 'yearmonth', 'year': nv, 'month': fm.getValue()}
    get_tickets(filters)
}


function filter_month_ticket_change(nv, ov){
    var fy = $$('filter_year_ticket')
    filters = {'opt': 'yearmonth', 'year': fy.getValue(), 'month': nv}
    get_tickets(filters)
}


function filter_dates_ticket_change(range){
    if(range.start != null && range.end != null){
        filters = {'opt': 'dates', 'range': range}
        get_tickets(filters)
    }
}


function configuracion_inicial_ticket(){
    current_dates_tickets()
    get_tickets()

    webix.ajax().sync().get('/values/configticket', function(text, data){
        var values = data.json()
        //~ showvar(values)
        cfg_ticket['open_pdf'] = values.open_pdf
        cfg_ticket['direct_print'] = values.direct_print
        cfg_ticket['edit_cant'] = values.edit_cant
        cfg_ticket['total_up'] = values.total_up
    })
}


function get_active_tickets(grid){
    filters = {'opt': 'active'}
    grid.showProgress({type: 'icon'})

    webix.ajax().get('/tickets', filters, {
        error: function(text, data, xhr) {
            msg_error('Error al consultar')
        },
        success: function(text, data, xhr) {
            var values = data.json();
            grid.clearAll();
            if (values.ok){
                grid.parse(values.rows, 'json')
            }
        }
    })
}


function configuracion_inicial_ticket_to_invoice(){
    var grid = $$('grid_tickets_active')
    var gridt = $$('grid_tickets_invoice')
    var form = $$('form_ticket_invoice')
    var chk = $$('chk_is_invoice_day')

    chk.setValue(false)
    get_active_tickets(grid)
    form.setValues({id_partner: 0, lbl_tclient: 'Ninguno'})
    gridt.attachEvent('onAfterAdd', function(id, index){
        gridt.adjustColumn('index')
        gridt.adjustColumn('folio', 'all')
        gridt.adjustColumn('fecha', 'all')
    });
    gridt.clearAll()
}


function configuracion_inicial_nuevo_ticket(){
    var grid = $$('grid_tdetails')

    webix.ajax().sync().get('/values/taxes', function(text, data){
        var values = data.json()
        table_taxes.clear()
        table_taxes.insert(values)
    })
    get_forma_pago('lst_ticket_forma_pago')
    grid.clearAll()
    table_pt.clear()
    table_totals.clear()
    show('grid_ticket_total_up', cfg_ticket['total_up'])
    $$('form_new_ticket').setValues({notas: '', forma_pago: last_forma_pago})
}


function cmd_nuevo_ticket_click(){
    configuracion_inicial_nuevo_ticket()
    $$('multi_tickets').setValue('tickets_new')
}


function cmd_ticket_from_ticket_click(){
    var grid = $$('grid_tickets')

    if(grid.count() == 0){
        return
    }

    var row = grid.getSelectedItem()
    if (row == undefined){
        msg_error('Selecciona un ticket')
        return
    }

    configuracion_inicial_nuevo_ticket()
    $$('multi_tickets').setValue('tickets_new')
    $$('grid_tdetails').load('ticketsdetails?opt=by_ticket_id&id=' + row.id)
}


function cmd_ticket_to_invoice_click(){
    configuracion_inicial_ticket_to_invoice()
    $$('multi_tickets').setValue('tickets_invoice')
}


function validar_ticket(){
    var grid = $$('grid_tdetails')

    if(!grid.count()){
        webix.UIManager.setFocus('tsearch_product_key')
        msg = 'Agrega al menos un producto'
        msg_error(msg)
        return false
    }

    var values = $$('form_new_ticket').getValues()
    if(!values.forma_pago){
        msg = 'La forma de pago es requerida'
        msg_error(msg)
        return false
    }

    return true
}


function get_ticket_pdf(id){
    window.open('/doc/tpdf/' + id, '_blank')
}


function guardar_ticket(values){
    var gd = $$('grid_tdetails')
    var grid = $$('grid_tickets')

    var rows = gd.data.getRange()
    for (i = 0; i < rows.length; i++) {
        delete rows[i]['id']
        delete rows[i]['delete']
        delete rows[i]['clave']
        delete rows[i]['clave_sat']
        delete rows[i]['unidad']
        delete rows[i]['importe']
        rows[i]['valor_unitario'] = parseFloat(rows[i]['valor_unitario'])
        rows[i]['descuento'] = parseFloat(rows[i]['descuento'])
    }

    last_forma_pago = values.forma_pago
    var data = new Object()
    data['opt'] = 'add'
    data['productos'] = rows
    data['forma_pago'] = values.forma_pago
    data['notas'] = values.notas

    webix.ajax().sync().post('tickets', data, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            values = data.json();
            if(values.ok){
                msg_ok('Ticket generado correctamente')
                $$('form_new_ticket').setValues({})
                gd.clearAll()
                grid.add(values.row)
                $$('multi_tickets').setValue('tickets_home')
                if(cfg_ticket.open_pdf){
                    get_ticket_pdf(values.row.id)
                }
                if(cfg_ticket.direct_print){
                    print_ticket(values.row.id)
                }
            }else{
                msg_error(values.msg)
            }
        }
    })

}


function cmd_generar_ticket_click(){
    var form = $$('form_new_ticket')

    if(!form.validate()) {
        msg_error('Valores inválidos')
        return
    }

    var values = form.getValues()
    if(!validar_ticket()){
        return
    }

    msg = '¿Todos los datos son correctos?<BR><BR>'
    msg += '¿Estás seguro de generar este Ticket?'

    webix.confirm({
        title: 'Generar Ticket',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                guardar_ticket(values)
            }
        }
    })
}


function cmd_cerrar_ticket_click(){
    $$('multi_tickets').setValue('tickets_home')
}


function calcular_precio_con_impuestos(precio, taxes){
    var precio_final = precio

    for(var tax of taxes){
        impuesto = table_taxes.findOne({'id': tax.tax})
        if(impuesto.tipo == 'E'){
            continue
        }
        var base = precio
        if(impuesto.tipo == 'R'){
            base = (precio * -1).round(DECIMALES)
        }
        precio_final += (impuesto.tasa * base).round(DECIMALES)
    }

    return precio_final
}


function edit_cant(id){
    if(!cfg_ticket['edit_cant']){
        return
    }
    $$('grid_tdetails').edit({row: id, column: 'cantidad'})
}


function agregar_producto(values){
    var taxes = values.taxes
    var producto = values.row
    var form = $$('form_new_ticket')
    var grid = $$('grid_tdetails')
    var row = grid.getItem(producto.id)
    var precio_final = 0.0

    if(row == undefined){
        producto['cantidad'] = 1
        producto['valor_unitario'] = calcular_precio_con_impuestos(
            parseFloat(producto['valor_unitario']), taxes)
        producto['importe'] = producto['valor_unitario']
        //~ var id = grid.add(producto, 0)
        //~ edit_cant(id)
    }else{
        producto['cantidad'] = parseFloat(row.cantidad) + 1
        producto['descuento'] = parseFloat(row.descuento)
        producto['valor_unitario'] = parseFloat(row.valor_unitario)
        precio_final = producto['valor_unitario'] - producto['descuento']
        producto['importe'] = (precio_final * producto['cantidad']).round(DECIMALES)
        //~ grid.updateItem(row.id, producto)
    }
    form.setValues({tsearch_product_key: '', tsearch_product_name: ''}, true)

    //~ Validate stock
    if(producto.inventario){
        if(producto.cantidad > producto.existencia){
            msg_error('No hay suficiente existencia de este producto')
            return
        }
    }

    if(row == undefined){
        var id = grid.add(producto, 0)
        edit_cant(id)
    }else{
        grid.updateItem(row.id, producto)
    }
}


function buscar_producto_key(key){

    var filters = {
        opt: 'by_key',
        key: key,
    }

    webix.ajax().get('/products', filters, {
        error: function(text, data, xhr) {
            msg_error('Error al consultar')
        },
        success: function(text, data, xhr){
            var values = data.json()
            if (values.ok){
                agregar_producto(values)
            } else {
                msg = 'No se encontró la clave<BR><BR>' + key
                msg_error(msg)
            }
        }
    })
    //~ webix.ajax().get('/values/productokey', {'key': key}, {
        //~ error: function(text, data, xhr) {
            //~ msg_error('Error al consultar')
        //~ },
        //~ success: function(text, data, xhr){
            //~ var values = data.json()
            //~ if (values.ok){
                //~ agregar_producto(values)
            //~ } else {
                //~ msg = 'No se encontró la clave<BR><BR>' + key
                //~ msg_error(msg)
            //~ }
        //~ }
    //~ })

}


function tsearch_product_key_press(code, e){
    var value = this.getValue()
    if(code == 13 && value.trim().length > 0){
        buscar_producto_key(value.trim())
    }
}



function grid_ticket_details_click(id, e, node){
    if(id.column != 'delete'){
        return
    }
    var grid = $$('grid_tdetails')
    grid.remove(id.row)
}


function grid_tickets_details_before_edit_stop(state, editor){
    var grid = $$('grid_tdetails')
    pause(500)
    var row = grid.getItem(editor.row)

    if(editor.column == 'cantidad'){
        var cantidad = parseFloat(state.value)
        if(isNaN(cantidad)){
            msg = 'La cantidad debe ser un número'
            msg_error(msg)
            grid.blockEvent()
            state.value = state.old
            grid.editCancel()
            grid.unblockEvent()
            return true
        }else if(cantidad <= 0){
            msg = 'La cantidad no puede cero o menor'
            msg_error(msg)
            grid.blockEvent()
            state.value = state.old
            grid.editCancel()
            grid.unblockEvent()
            return true
        }

        //~ Validate stock
        if(row['inventario']){
            if(cantidad > row['existencia']){
                msg = 'No hay suficiente existencia de este producto'
                msg_error(msg)
                grid.blockEvent()
                state.value = state.old
                grid.editCancel()
                grid.unblockEvent()
                return true
            }
        }

        var valor_unitario = parseFloat(row['valor_unitario'])
        var descuento = parseFloat(row['descuento'])
    }

    if(editor.column == 'valor_unitario'){
        var valor_unitario = parseFloat(state.value)
        if(isNaN(valor_unitario)){
            msg = 'El valor unitario debe ser un número'
            msg_error(msg)
            grid.blockEvent()
            state.value = state.old
            grid.editCancel()
            grid.unblockEvent()
            return true
        }else if(valor_unitario <= 0){
            msg = 'El valor unitario no puede cero o menor'
            msg_error(msg)
            grid.blockEvent()
            state.value = state.old
            grid.editCancel()
            grid.unblockEvent()
            return true
        }
        var cantidad = parseFloat(row['cantidad'])
        var descuento = parseFloat(row['descuento'])
    }

    if(editor.column == 'descuento'){
        var descuento = parseFloat(state.value)
        if(isNaN(descuento)){
            msg = 'El descuento debe ser un número'
            msg_error(msg)
            grid.blockEvent()
            state.value = state.old
            grid.editCancel()
            grid.unblockEvent()
            return true
        }
        var cantidad = parseFloat(row['cantidad'])
        var valor_unitario = parseFloat(row['valor_unitario'])
    }

    var precio_final = valor_unitario - descuento
    row['importe'] = (cantidad * precio_final).round(DECIMALES)

    grid.refresh()
    if(cfg_ticket['edit_cant']){
        focus('tsearch_product_name')
    }
}


function gt_productos_found_click(obj){
    buscar_producto_key(obj.clave)
}


function cancel_ticket(id){
    var grid = $$('grid_tickets')
    var data = new Object()
    data['opt'] = 'cancel'
    data['id'] = id

    webix.ajax().sync().post('tickets', data, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            values = data.json();
            if(values.ok){
                grid.updateItem(id, values.row)
                msg_ok(values.msg)
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function cmd_cancelar_ticket_click(){
    var grid = $$('grid_tickets')

    if(grid.count() == 0){
        return
    }

    var row = grid.getSelectedItem()
    if (row == undefined){
        msg_error('Selecciona un ticket')
        return
    }

    if(row['estatus']=='Cancelado'){
        msg_error('El ticket ya esta cancelado')
        return
    }

    if(row['estatus']=='Facturado'){
        msg_error('El ticket esta facturado')
        return
    }

    msg = '¿Estás seguro de cancelar el siguiente Ticket?<BR><BR>'
    msg += 'Folio: ' + row['folio']
    msg += '<BR><BR>ESTA ACCIÓN NO SE PUEDE DESHACER'
    webix.confirm({
        title:'Cancelar Ticket',
        ok:'Si',
        cancel:'No',
        type:'confirm-error',
        text:msg,
        callback:function(result){
            if (result){
                cancel_ticket(row['id'])
            }
        }
    })

}


function chk_is_invoice_day_change(new_value, old_value){
    var value = Boolean(new_value)

    show('fs_ticket_search_client', !value)
    enable('lst_global_periodicidad_2', value)
    enable('lst_global_months_2', value)

    var current_date = new Date()
    var current_month = (current_date.getMonth() + 1).toString().padStart(2, '0')
    $$('lst_global_months_2').setValue(current_month)
}


function send_timbrar_invoice(id){
    webix.ajax().post('invoices', {opt: 'timbrar', id: id, update: false}, function(text, data){
        var values = data.json()
        if(values.ok){
            msg_ok(values.msg)
        }else{
            webix.alert({
                title: 'Error al Timbrar',
                text: values.msg,
                type: 'alert-error'
            })
        }
    })

}


function save_ticket_to_invoice(data){
    webix.ajax().sync().post('tickets', data, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            values = data.json();
            if(values.ok){
                msg_ok(values.msg)
                send_timbrar_invoice(values.id)
                $$('chk_is_invoice_day').setValue(false)
                $$('multi_tickets').setValue('tickets_home')
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function cmd_new_invoice_from_ticket_click(){
    var form = this.getFormView();
    var chk = $$('chk_is_invoice_day')
    var grid = $$('grid_tickets_invoice')
    var values = form.getValues()
    var tickets = []

    if(!chk.getValue()){
        if(values.id_partner == 0){
            webix.UIManager.setFocus('tsearch_client_name')
            msg = 'Selecciona un cliente'
            msg_error(msg)
            return false
        }
    }

    if(!grid.count()){
        msg = 'Agrega al menos un ticket a facturar'
        msg_error(msg)
        return false
    }

    grid.eachRow(function(row){
        tickets.push(row)
    })

    var data = new Object()
    data['opt'] = 'invoice'

    data['client'] = values.id_partner
    data['tickets'] = tickets
    data['is_invoice_day'] = chk.getValue()

    var periodicidad = ''
    if(data['is_invoice_day']){
        periodicidad = $$('lst_global_periodicidad_2').getValue() + '|'
        periodicidad += $$('lst_global_months_2').getValue() + '|'
        periodicidad += new Date().getFullYear()
    }
    data['periodicidad'] = periodicidad

    msg = 'Todos los datos son correctos.<BR><BR>'
    if(data['is_invoice_day']){
        msg += 'Es Factura Global.<BR><BR>'
    }
    msg += '¿Estás seguro de generar esta factura?'

    webix.confirm({
        title: 'Generar Factura',
        ok: 'Si',
        cancel: 'No',
        type: 'confirm-error',
        text: msg,
        callback:function(result){
            if(result){
                save_ticket_to_invoice(data)
            }
        }
    })
}


function grid_tickets_active_double_click(id, e, node){
    this.move(id.row, -1, $$('grid_tickets_invoice'))
}


function grid_tickets_invoice_double_click(id, e, node){
    this.move(id.row, -1, $$('grid_tickets_active'))
}


function cmd_move_tickets_right_click(){
    var source = $$('grid_tickets_active')
    var target = $$('grid_tickets_invoice')
    _move_tickets(source, target)
}


function cmd_move_tickets_left_click(){
    var target = $$('grid_tickets_active')
    var source = $$('grid_tickets_invoice')
    _move_tickets(source, target)
}


function _move_tickets(source, target){
    var rows = source.getSelectedItem()

    if(rows == undefined){
        source.eachRow(
            function(row){
                this.copy(row, -1, target)
            }
        )
        source.clearAll()
    }
}


function ticket_set_client(row){
    var form = $$('form_ticket_invoice')
    var html = '<span class="webix_icon fa-user"></span><span class="lbl_partner">'
    form.setValues({
        id_partner: row.id,
        tsearch_client_key: '',
        tsearch_client_name: ''}, true)
    html += row.nombre + ' (' + row.rfc + ')</span>'
    $$('lbl_tclient').setValue(html)
}


function ticket_search_client_by_id(id){
    webix.ajax().get('/values/client', {'id': id}, {
        error: function(text, data, xhr) {
            msg_error('Error al consultar')
        },
        success: function(text, data, xhr){
            var values = data.json()
            if (values.ok){
                ticket_set_client(values.row)
            }else{
                msg = 'No se encontró un cliente con la clave: ' + id
                msg_error(msg)
            }
        }
    })

}


function tsearch_client_key_press(code, e){
    var value = this.getValue()
    if(code == 13 && value.length > 0){
        var id = parseInt(value, 10)
        if (isNaN(id)){
            msg_error('Captura una clave válida')
        }else{
            ticket_search_client_by_id(id)
        }
    }
}


function grid_ticket_clients_found_click(obj){
    ticket_set_client(obj)
}


function cmd_ticket_notes_click(){
    win_ticket_notes.init()
    var values = $$('form_new_ticket').getValues()
    $$('ticket_notes').setValue(values.notas)
    $$('win_ticket_notes').show()
    to_end('ticket_notes')
}


function cmd_ticket_save_note_click(){
    var value = $$('ticket_notes').getValue()
    $$('form_new_ticket').setValues({notas: value}, true)
    $$('win_ticket_notes').close()

}


function print_ticket(id){
    var data = new Object()
    data['opt'] = 'print'
    data['id'] = id

    webix.ajax().post('tickets', data, {
        error:function(text, data, XmlHttpRequest){
            msg = 'Ocurrio un error, consulta a soporte técnico'
            msg_error(msg)
        },
        success:function(text, data, XmlHttpRequest){
            values = data.json();
            if(values.ok){
                msg_ok(values.msg)
            }else{
                msg_error(values.msg)
            }
        }
    })
}


function grid_tickets_click(id, e, node){
    if(id.column == 'pdf'){
        //~ window.open('/doc/tpdf/' + id, '_blank')
        get_ticket_pdf(id.row)
        return
    }

    if(id.column == 'print'){
        print_ticket(id.row)
        return
    }
}


function cmd_ticket_report_pdf_click(){
    webix.toPDF($$('grid_tickets'), {
        ignore: {'pdf': true, 'print': true},
        filename: 'Reporte_Tickets',
        width: 612,
        height: 792,
        columns:{
            index: true,
            serie: {width: 50},
            folio: {width: 50},
            fecha: {width: 125},
            estatus: true,
            total: {css: 'right'},
        }
    })
}


function cmd_ticket_report_xls_click(){
    webix.toExcel($$('grid_tickets'), {
        filename: 'Reporte_Tickets',
        name: 'Tickets',
        ignore: {'pdf': true, 'print': true},
        rawValues: true,
    })
}


function grid_tdetails_render(data){
    var total = 0.0
    this.eachRow(function(id){
        var item = this.getItem(id)
        total += item.importe
    })
    var id = $$('grid_ticket_total_up').getFirstId()
    $$('grid_ticket_total_up').updateItem(id, {total: total})
}
