

var toolbar_products = [
    {view: "button", id: "cmd_new_product", label: "Nuevo", type: "iconButton",
        autowidth: true, icon: "plus"},
    {view: "button", id: "cmd_edit_product", label: "Editar", type: "iconButton",
        autowidth: true, icon: "pencil"},
    {view: "button", id: "cmd_delete_product", label: "Eliminar",
        type: "iconButton", autowidth: true, icon: "minus"},
    {},
    {view: 'button', id: 'cmd_import_products', label: 'Importar',
        type: 'iconButton', autowidth: true, icon: 'upload'},
    {view: "button", id: "cmd_add_inventory", label: "Altas", hidden: true,
        type: "iconButton", autowidth: true, icon: "plus"},
    {view: "button", id: "cmd_products_add", label: "Altas CFDI", hidden: true,
        type: "iconButton", autowidth: true, icon: "plus"},
    {view: 'button', id: 'cmd_show_exists', label: 'Existencias', hidden: true,
        type: 'iconButton', autowidth: true, icon: 'table'},
]


var grid_products_cols = [
    { id: "id", header: "ID", width: 75, hidden: true},
    { id: 'es_activo', header: 'Activo', hidden: true},
    { id: "clave_sat", header: ["Clave SAT"], width: 100,},
    { id: "clave", header: ["Clave", {content: "textFilter"}], width: 100,
        sort: 'string', footer: {content: 'countRows', css: 'right'}},
    { id: "descripcion", header: ["Descripción", {content: "textFilter"}],
        fillspace:true, sort: 'string', footer: 'Productos y Servicios'},
    { id: "unidad", header: ["Unidad", {content: "selectFilter"}], width: 150,
        sort:"string" },
    { id: "valor_unitario", header: ["Precio", {content: "numberFilter"}],
        width: 150, sort: 'int', format: format_currency, css: "right" },
    { id: 'existencia', header: ['Existencia', {content: 'numberFilter'}],
        width: 100, sort: 'int', format: webix.i18n.numberFormat,
        hidden: true, css: 'right' },
]


var grid_products = {
    view: 'datatable',
    id: 'grid_products',
    select: 'row',
    adjust: true,
    footer: true,
    resizeColumn: true,
    headermenu: true,
    columns: grid_products_cols,
    scheme:{
        $change:function(item){
            if(!item.es_activo){
                item.$css = 'cancel'
            }
        }
    },
}


var suggest_categories = {
    view: 'datasuggest',
    type: 'tree',
    width: 400,
    body: {data: []},
}


var grid_product_taxes_cols = [
    {id:"id", header:"ID", hidden: true},
    {id:"name", header:'Nombre'},
    {id:"tipo", header:'Tipo'},
    {id:"tasa", header:'Tasa'},
]


var grid_product_taxes = {
    view: 'datatable',
    id: 'grid_product_taxes',
    select: 'row',
    multiselect: true,
    adjust: true,
    autoheight: true,
    autowidth: true,
    headermenu: true,
    columns: grid_product_taxes_cols,
}


var suggest_sat_producto = {
    view: 'gridsuggest',
    id: 'grid_producto_found',
    name: 'grid_producto_found',
    body: {
        autoConfig: false,
        scroll: true,
        autoheight: false,
        header: true,
        yCount: 10,
        columns: [
            {id: 'id', hidden: true},
            {id: 'key', adjust: 'data', header: 'Clave SAT'},
            {id: 'name', header: 'Producto', width: 750},
        ],
        dataFeed:function(text){
            if (text.length > 3){
                this.load('/values/satproductos?key=' + text)
            }else{
                this.hide()
            }
        }
    },
}


var opt_tax_object = [
    {id: '01', value: '[01] No objeto de impuesto.'},
    {id: '02', value: '[02] Sí objeto de impuesto.'},
    {id: '03', value: '[03] Sí objeto del impuesto y no obligado al desglose.'},
    {id: '04', value: '[04] Sí objeto del impuesto y no causa impuesto.'},
    {id: '05', value: '[05] Sí objeto del impuesto, IVA crédito PODEBI.'},
]


var controls_generals = [
    {view: 'checkbox', id: 'es_activo_producto', name: 'es_activo_producto',
        label: 'Activo: ', value: true,
        bottomLabel: 'Se recomienda solo desactivar y no eliminar'},
    {cols: [
        {view: 'combo', id: 'categoria', name: 'categoria', label: 'Categoría',
            labelPosition: 'top', suggest: suggest_categories},
        {view: 'text', id: 'clave', name: 'clave', label: 'Clave',
            labelPosition: 'top', readonly: true, required: true},
        {view: 'checkbox', id: 'chk_automatica', label: 'Automática',
            labelPosition: 'top', value: true, maxWidth: 80},
        {view: 'search', id: 'clave_sat', name: 'clave_sat', label: 'Clave SAT',
            labelPosition: 'top', required: true, suggest: suggest_sat_producto,
            placeholder: 'Al menos 4 caracteres...'},
    ]},
    {cols: [
        {view: 'text', id: 'codigo_barras', name: 'codigo_barras',
            label: 'Código de Barras', labelPosition: 'top', hidden: true},
        {view: 'text', id: 'cuenta_predial', name: 'cuenta_predial',
            label: 'Cuenta Predial', labelPosition: 'top', hidden: true},
    {id: 'txt_col1'}]},
    {view: "textarea", id: "descripcion", name: "descripcion", height: 200,
        label: "Descripción", required: true, labelPosition: "top",
        invalidMessage: "La Descripción es requerida",
        placeholder: 'El SAT solo permite 1000 caracteres en este campo'},
    {minHeight: 5},
    {cols: [
        {view: "richselect", id: "unidad", name: "unidad", label: "Unidad",
            width: 300, labelWidth: 130, labelAlign: "right", required: true,
            invalidMessage: "La Unidad es requerida", options: []},
        {view: 'richselect', id: 'objeto_impuesto', name: 'objeto_impuesto', label: 'Objeto de Impuestos',
            width: 500, labelWidth: 150, labelAlign: "right", required: true,
            invalidMessage: 'Este campo es requerido', options: opt_tax_object},
        {},
    ]},
    {cols: [
        {view: "currency", type: "text", id: "valor_unitario",
            name: "valor_unitario", label: "Valor Unitario", width: 300,
            labelWidth: 130, labelAlign: "right", required: true,
            invalidMessage: "Captura un valor númerico", inputAlign: "right"},
        {view: 'currency', type: 'text', id: 'precio_con_impuestos',
            name: 'precio_con_impuestos', label: 'Con Impuestos', width: 300,
            labelWidth: 115, labelAlign: 'right', required: false,
            invalidMessage: 'Captura un valor númerico', inputAlign: 'right'},
        {},]},
    {cols: [
        {view: 'checkbox', id: 'chk_inventario', name: 'inventario', hidden: true,
            label: 'Inventario', labelAlign: 'right', labelWidth: 130},
        {view: 'counter', id: 'txt_existencia', name: 'existencia',
            hidden: true, label: 'Existencia', step: 5, value: 0, min: 0,
            disabled: true, readonly: true},
        {view: 'counter', id: 'txt_minimo', name: 'minimo', hidden: true,
            label: 'Mínimo', step: 5, value: 0, min: 0, disabled: true},
        {},]},
    {cols:[{view:'label', label:'Impuestos', width: 300, align:'center'}, {}]},
    {cols:[grid_product_taxes, {}]}
]


var controls_products = [
    {
        view: "tabview",
        tabbar: { options: ["Datos"]}, animate: true,
        cells: [
            {id: "Datos", rows: controls_generals},
        ],
    },
    {rows: [
        {template: "", type: "section"},
        {margin: 10, cols: [{},
            {view: "button", id: "cmd_save_product", label: "Guardar" , type: "form", autowidth: true, align:"center"},
            {view: "button", id: "cmd_cancel_product", label: "Cancelar" , type: "danger", autowidth: true, align:"center"},
            {}]
        },
    ]}
]


var form_product = {
    type: "space",
    cols: [{
        view: "form",
        id: "form_product",
        scroll: true,
        complexData: true,
        elements: controls_products,
        rules: {
            descripcion: function(value){ return value.trim() != ""; },
            valor_unitario: function(value){ return value.trim() != "$"; },
        }
    }],
}


var toolbar_products_add = {view: 'toolbar', elements: [{},
    {view: 'button', id: 'cmd_add_products_from_xml', label: 'Desde XML',
        type: 'iconButton', autowidth: true, icon: 'upload'},
{}]}


var rows_pro_add_partner = [
    {view: 'fieldset', label: 'Buscar Proveedor', body: {rows: [
        {cols: [
            {view: 'search', id: 'search_partner_id', label: 'por Clave',
                labelPosition: 'top', maxWidth: 200, placeholder: 'Captura la clave'},
            {view: 'search', id: 'search_partner_name', label: 'por Nombre o RFC',
                labelPosition: 'top', placeholder: 'Captura al menos tres letras'},
        ]},
        {cols: [
            {view: 'label', id: 'lbl_partner_title', label: 'Seleccionado: ', autowidth: true},
            {view: 'label', id: 'lbl_partner', label: 'Ninguno'},
        ]}
    ]}},
]


var grid_partner_products_cols = [
    {id: 'select', header: '', template:'{common.checkbox()}', width:35},
    {id: 'key', header: {text: 'Clave', css: 'center'}, width: 100,
        adjust: 'data'},
    {id: 'key_sat', header:{text: 'Clave SAT', css: 'center'}, width: 100,
        adjust: 'data'},
    {id: 'description', header:{text: 'Descripción', css: 'center'},
        fillspace: true},
    {id: "pedimento", header: 'Pedimento', editor: 'text', hidden: true},
    {id: 'unit', header:{text: 'Unidad', css: 'center'}, width: 100,
        adjust: 'data'},
    {id: 'unit_value', header:{text: 'Valor Unitario', css: 'center'},
        width: 100, format: format_currency, css: 'right'},
    {id: 'cant', header: {text: 'Cantidad', css: 'center'}, width: 50,
        format: webix.i18n.numberFormat, css: 'right'},
    {id: 'separate', header: '', width: 25},
    {id: 'id_product', header: '', hidden: true},
    {id: 'key1', header:{text: 'Clave', css: 'center'}, width: 100,
        adjust: true, editor: 'text', hidden: true},
    {id: 'key_sat1', header:{text: 'Clave SAT', css: 'center'}, width: 100,
        adjust: true, editor: 'text'},
    {id: 'description1', header:{text: 'Descripción', css: 'center'},
        fillspace: true, editor: 'popup'},
    {id: 'unit_value1', header:{text: 'Valor Unitario', css: 'center'},
        width: 100, format: format_currency, css: 'right', editor: 'text'},
    {id: 'cant1', header: {text: 'Cantidad', css: 'center'}, width: 50,
        format: webix.i18n.numberFormat, css: 'right', editor: 'text'},
]


var grid_partner_products = {
    view: 'datatable',
    id: 'grid_partner_products',
    select: 'row',
    adjust: true,
    autoheight: true,
    editable: true,
    columns: grid_partner_products_cols,
    data: [],
    fixedRowHeight: false,
    on:{
        onCheck:function(rowId, colId, state){
            grid_partner_products_select(rowId, state);
        }
    }
}


var controls_products_add = [
    {minHeight: 10, maxHeight: 10},
    toolbar_products_add,
    {minHeight: 10, maxHeight: 10},
    {cols: [
        {rows: rows_pro_add_partner},
        {maxWidth: 10},
        {},
    ]},
    {view: 'label', label: 'Detalle', height: 30, align: 'left'},
    {cols: [
        grid_partner_products,
        //~ grid_products_add,
    ]},
    {rows: [
        {template:"", type: "section" },
        {margin: 10, cols: [{},
            {view: 'button', id: 'cmd_save_products_add', label: 'Guardar',
                autowidth: true, align: 'center'},
            {},
            {view: 'button', id: 'cmd_close_products_add', label: 'Cancelar',
                type: 'danger', autowidth: true, align: 'center'}
            ]
        },
    ]}
]


var controls_form_products_add = [
    {
        view: 'tabview',
        id: 'tv_invoice',
        animate: true,
        cells: [
            {id: 'Altas a inventario', rows: controls_products_add},
        ]
    },
]


var form_products_add = {
    type: 'space',
    responsive: true,
    cols: [{
        view: 'form',
        id: 'form_products_add',
        complexData: true,
        scroll: true,
        elements: controls_form_products_add,
    }]
}


var multi_products = {
    id: "multi_products",
    animate: true,
    cells:[
        {id: "products_home", rows:[
            {view:"toolbar", elements: toolbar_products},
            grid_products,
        ]},
        {id: "product_new", rows:[form_product]},
        {id: "product_add", rows:[form_products_add]}
    ],
}


var app_products = {
    id: 'app_products',
    rows:[
        {view: 'template', id: 'th_products', type: 'header',
            template: 'Administración de Productos y Servicios'},
        multi_products
    ],
}


var body_import_products = {rows: [
    {view: 'form', id: 'form_upload_products', rows: [
        {cols: [{},
            {view: 'uploader', id: 'up_products', autosend: false,
                link: 'lst_upload_products', value: 'Seleccionar Archivo',
                upload: '/files/products'}, {}]},
        {cols: [
            {view: 'list',  id: 'lst_upload_products', name: 'lst_upload_products',
                type: 'uploader', autoheight: true, borderless: true}]},
        {cols: [{}, {view: 'button', id: 'cmd_upload_products',
            label: 'Importar Productos'}, {}]},
    ]},
]}


var win_import_products = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_import_products',
            width: 400,
            modal: true,
            position: 'center',
            head: 'Importar Productos',
            body: body_import_products,
        })
        $$('cmd_upload_products').attachEvent('onItemClick', cmd_upload_products_click)
        $$('up_products').attachEvent('onUploadComplete', up_products_upload_complete)
    }
}


var body_add_products_from_xml = {rows: [
    {view: 'form', id: 'form_upload_products_from_xml', rows: [
        {cols: [{},
            {view: 'uploader', id: 'up_products_from_xml', autosend: false,
                link: 'lst_up_products_from_xml', value: 'Seleccionar Archivo',
                upload: '/files/productsadd'}, {}]},
        {cols: [
            {view: 'list',  id: 'lst_up_products_from_xml', type: 'uploader',
                autoheight: true, borderless: true}]},
        {cols: [{}, {view: 'button', id: 'cmd_upload_products_from_xml',
            label: 'Cargar Productos'}, {}]},
    ]},
]}


var win_add_products_from_xml = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_add_products_from_xml',
            width: 400,
            modal: true,
            position: 'center',
            head: 'Agregar Productos desde XML',
            body: body_add_products_from_xml,
        })
        $$('cmd_upload_products_from_xml').attachEvent('onItemClick', cmd_upload_products_from_xml_click)
        $$('up_products_from_xml').attachEvent('onUploadComplete', up_products_from_xml_upload_complete)
    }
}


var body_add_inventory = {rows: [{minHeight: 10},
    {view: 'text', id: 'txt_add_id', readonly: true, hidden: true},
    {cols: [
        {view: 'text', id: 'txt_add_key', label: 'Clave',
            labelPosition: 'top', readonly: true},
        {view: 'text', id: 'txt_add_unit', label: 'Unidad',
            labelPosition: 'top', readonly: true},
        ]},
    {view: 'textarea', id: 'txt_add_description', height: 100,
        label: 'Descripción', readonly: true, labelPosition: 'top'},
    {minHeight: 10},
    {cols: [
        {view: 'counter', id: 'txt_new_cant', label: 'Cantidad a agregar',
            labelWidth: 'auto', step: 1, value: 0, min: 0.01},
        {view: 'richselect', id: 'lst_warehouses', label: 'Almacen: ',
            labelPosition: 'left', required: false, options: [], hidden: false},
        ]},
    {minHeight: 20},
    {cols: [{},
        {view: 'button', id: 'cmd_add_inventory_save', label: 'Guardar'}, {},
        {view: 'button', id: 'cmd_add_inventory_cancel', label: 'Cancelar', type: 'danger'}, {}
        ]},
    {minHeight: 20},
]}


var win_add_inventory = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_add_inventory',
            width: 600,
            modal: true,
            position: 'center',
            head: 'Agregar entrada manualmente',
            body: body_add_inventory,
        })
        $$('cmd_add_inventory_save').attachEvent('onItemClick', cmd_add_inventory_save_click)
        $$('cmd_add_inventory_cancel').attachEvent('onItemClick', cmd_add_inventory_cancel_click)
    }
}


var grid_warehouse_exists_cols = [
    { id: 'id', header: 'ID', width: 75, hidden: true},
    { id: 'warehouse', header: ['Almacen'], fillspace:true,
        footer: {text: 'Total', css: 'right'}},
    { id: 'exists', header: ['Existencia'], width: 100, sort: 'int',
        format: webix.i18n.numberFormat, css: 'right',
        footer: {content: 'summColumn', css: 'right'} },
]


var grid_warehouse_exists = {
    view: 'datatable',
    id: 'grid_warehouse_exists',
    adjust: true,
    autoheight: true,
    select: 'row',
    footer: true,
    columns: grid_warehouse_exists_cols,
}


var body_win_show_exists = {rows: [{maxHeight: 10, minHeight: 10},
    {minWidth: 500},
    {cols: [
        {maxWidth: 10},
        {view: 'text', id: 'txt_id_product', readonly: true, hidden: true},
        grid_warehouse_exists,
        {maxWidth: 10}
    ]},
    {maxHeight: 10},
    {cols: [{maxWidth: 10},
        {view: 'label', id: 'lbl_title_move', label: 'Primero, selecciona el almacen origen en la tabla superior.'},
        ]},
    {cols: [{maxWidth: 10},
        {view: 'counter', id: 'txt_cant_to_move', label: 'Cantidad a mover:',
            labelPosition: 'top', step: 1, value: 0, min: 0.01},
        {view: 'richselect', id: 'lst_warehouse_target', label: 'Almacen destino: ',
            labelPosition: 'top', required: false, options: []}, {maxWidth: 10},
        {view: 'button', id: 'cmd_warehouse_move', label: 'Mover', maxWidth: 100},
        {maxWidth: 10}]},
    {minHeight: 25, maxHeight: 25},
    {template: 'Ajuste de almacen', type: 'section'},
    {cols: [{maxWidth: 10},
        {view: 'counter', id: 'txt_cant_to_adjust', label: 'Cantidad a ajustar:',
            labelPosition: 'top', step: 1, value: 0, min: -1000000},
        {view: 'button', id: 'cmd_adjust_stock', label: 'Ajustar', maxWidth: 100},
        {maxWidth: 10}]},
    {maxHeight: 20, minHeight: 20},
    {cols: [{},
        {view: 'button', id: 'cmd_win_show_exists_close', label: 'Cerrar', type: 'danger'},
        {}]},
    {maxHeight: 20, minHeight: 20},
]}


var win_show_exists = {
    init: function(){
        webix.ui({
            view: 'window',
            id: 'win_show_exists',
            width: 500,
            modal: true,
            position: 'center',
            head: 'Existencia por Almacen',
            body: body_win_show_exists,
        })
        $$('cmd_win_show_exists_close').attachEvent('onItemClick', cmd_win_show_exists_close_click)
        $$('cmd_warehouse_move').attachEvent('onItemClick', cmd_warehouse_move_click)
        $$('cmd_adjust_stock').attachEvent('onItemClick', cmd_adjust_stock_click)
    }
}
