

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'},
]


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 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: 'text', id: 'cant_by_packing', name: 'cant_by_packing',
            labelAlign: 'right', labelWidth: 150, inputAlign: "right",
            label: 'Cantidad por empaque:'},
        {},
        //~ {view: 'text', id: 'tags_producto', name: 'tags_producto',
            //~ labelAlign: 'right', label: 'Etiquetas',
            //~ placeholder: 'Separadas por comas'}
    ]},
    {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},
        {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 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]}
    ],
}


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)
    }
}
