let Core = {
    units: {"alternativa":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"arius":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"bagy":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"bling":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"blingv3":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"conectahub":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"hostgator":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"lojaintegrada":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"mercadolivre":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"nuvemshop":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"openk":{"weightUnit":"kg","lengthUnit":"m","heightUnit":"m","widthUnit":"m"},"publicapi":{"weightUnit":"g","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"tiny":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"tray":{"weightUnit":"g","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"wap":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"},"wbuy":{"weightUnit":"kg","lengthUnit":"cm","heightUnit":"cm","widthUnit":"cm"}},
    mainIdFields: {"vtex":"Product Id","bling":"codigo","lojaintegrada":"id","nuvemshop":"id","bagy":"id","tiny":"id","tray":"id","openk":"id","alternativa":"codigo","arius":"id","blingv3":"id","conectahub":"codigo","hostgator":"id","mercadolivre":"id","publicapi":["id"]},
    slugFields: undefined,
    requiredFields: {"template":{"update":["name","brand"],"create":["name","brand"],"seo":[]},"alternativa":{"create":["reference","height","width","length"],"update":["reference","height","width","length"]},"arius":{"create":[],"update":[]},"bagy":{"create":["height","width","length"],"update":["height","width","length"]},"bling":{"update":["height","width","length","weight"],"create":["reference","height","width","length","weight"]},"blingv3":{},"conectahub":{"create":["reference","weight","width","length","height"],"update":["reference","weight","width","length","height"]},"hostgator":{"create":["name","description","category"],"update":["name","description"]},"lojaintegrada":{"create":["reference","weight","height","width","length"],"update":["reference","weight","height","width","length"]},"mercadolivre":{"create":["Preço *"],"update":["Preço *"]},"nuvemshop":{"create":["category","height","width","length","weight"],"update":["height","width","length","weight"]},"tiny":{"create":["weight","height","width","length"],"update":["reference","weight","height","width","length"]},"tray":{"create":["category","height","width","length"],"update":["category","height","width","length"]},"vtex":{"create":["category","images","weight","height","width","length"],"update":["images","category","weight","height","width","length"]}},
    fieldsValidationRules: {"lojaintegrada":{"reference":{"max":255,"regex":{"pattern":"^[a-zA-Z0-9_-]+$","errorDescription":"O campo de referência apenas pode conter números, letras e os seguintes caracteres: - ou _"}},"height":{"regex":{"pattern":"^\\d+$","errorDescription":"O campo de altura deve ser um número sem ponto ou virgula"}},"width":{"regex":{"pattern":"^\\d+$","errorDescription":"O campo de largura deve ser um número sem ponto ou virgula"}},"length":{"regex":{"pattern":"^\\d+$","errorDescription":"O campo de comprimento deve ser um número sem ponto ou virgula"}}},"tray":{"images":{"max":15},"weight":{"regex":{"pattern":"^\\d+$","errorDescription":"Peso em Gramas não pode conter ponto ou vírgula."}}}},
    idFields: {"vtex":["Ref Id","Product Id","Sku Id"],"bling":["codigo"],"lojaintegrada":["Sku","id"],"nuvemshop":["id","Sku"],"bagy":["id","Sku Id"],"tiny":["id"],"tray":["id"],"openk":["id"],"alternativa":["codigo"],"arius":["id","ean"],"blingv3":["id"],"conectahub":["codigo"],"hostgator":["id"],"mercadolivre":["id"],"publicapi":["id"]},
    columns: {"bagy":{"product":["external_id","hotsite_id","slug","short_description","relevance","tags","min_quantity","max_quantity","sell_in_kit_only","kit","kit_markup","is_virtual","video","sell_out_of_stock","price_out_of_stock","additional_time_out_of_stock","price_compare","billet_discount","warranty","model","gender","age_group","stock_location","st","ncm","ipi","has_gift_wrapping","active"]},"vtex":{"product":["LinkId","ShowWithoutStock","TaxCode"],"sku":["ShowWithoutStock","ShowIfNotAvailable","ActivateIfPossible"]},"bling":{"product":["descricaoComplementar","situacao","tipo","un","vlr_unit","preco_custo","peso_bruto","peso_liq","class_fiscal","cest","origem","idGrupoProduto","condicao","freteGratis","linkExterno","observacoes","producao","unidadeMedida","dataValidade","idFabricante","codigoFabricante","gtin","gtinEmbalagem","estoqueMinimo","estoqueMaximo","volumes","urlVideo","localizacao","crossdocking","garantia","spedTipoItem","descricaoFornecedor"]},"lojaintegrada":{"product":["id_externo","mpn","ncm","apelido","ativo","destaque","tipo","usado","removido","url_video_youtube"],"prices":["cheio","custo","promocional","sob_consulta"],"stocks":["gerenciado","situacao_em_estoque","situacao_sem_estoque","quantidade"]},"nuvemshop":{"product":["published","free_shipping","video_url","requires_shipping"]},"tiny":{"product":["preco_promocional","ncm","gtin_embalagem","localizacao","peso_liquido","estoque_minimo","estoque_maximo","id_fornecedor","codigo_fornecedor","codigo_pelo_fornecedor","unidade_por_caixa","preco_custo","classe_ipi","valor_ipi_fixo","cod_lista_servicos","obs","garantia","cest","codigo_anvisa","valor_max","motivo_isencao","dias_preparacao","tipo_embalagem","classe_produto"]},"tray":{"product":["ncm","description_small","cost_price","promotional_price","start_promotion","end_promotion","model","availability","available","warranty","hot","release","additional_button","release_date"]},"alternativa":{"prices":["PrecoCusto","PrecoVenda","PrecoFicticio","PrecoSite","PrecoFicticioSite"]},"arius":{"product":[]},"blingv3":{"product":["tipo","situacao","descricaoCurta","dataValidade","unidade","pesoLiquido","pesoBruto","volumes","itensPorCaixa","gtinEmbalagem","tipoProducao","condicao","freteGratis","descricaoComplementar","linkExterno","observacoes","descricaoEmbalagemDiscreta"],"tributacao":["origem","nFCI","ncm","cest","codigoListaServicos","spedTipoItem","codigoItem","percentualTributos","valorBaseStRetencao","valorStRetencao","valorICMSSubstituto","codigoExcecaoTipi","classeEnquadramentoIpi","valorIpiFixo","codigoSeloIpi","valorPisFixo","valorCofinsFixo","codigoANP","descricaoANP","percentualGLP","percentualGasNacional","valorPartida","tipoArmamento","descricaoCompletaArmamento","dadosAdicionais","idGrupoProduto"]},"conectahub":{"product":["departamento","tipo","fabricante","modelo","garantia","textoGarantia","leadTime","condicao","ncm","origem","embalagem","genero","palavraschave","unidadeMedida","titulo"]},"mercadolivre":{"product":["currency_id","available_quantity","buying_mode","condition","listing_type_id","official_store_id","WARRANTY_TYPE","WARRANTY_TIME"]}},
    infos: {"recreateMax":3,"recreateSeoMax":3},
    validateRequiredFields: async function(api, content) {

        let kind;

        if(content.origin == 'enriquecimento em massa') kind = 'update';
        else kind = 'create';

        if(content.origin == 'categoria seo' || content.origin == 'redator seo') kind = 'seo';

        if(!kind) throw 'Ocorreu um problema';

        let requiredFields = Object.assign([], Core.requiredFields['template'][kind]);
        
        let result = {
            isValid: true,
            errors: []
        }

        if(kind == 'seo') return Promise.resolve(result);

        let platformRequiredFields = Core.requiredFields[api] || {};

        let apiFields = Object.assign([], platformRequiredFields[kind]);

        if(!apiFields) return Promise.resolve(result);

        for (let value of apiFields) {
            requiredFields.push(value)
        }

        let validationRules = Core.fieldsValidationRules[api];

        for (let field in content) {

            if(field == 'images' && requiredFields.includes(field)) {

                if(!content['images'].length) {
                    result.isValid = false;
                    result.errors.push(__(`Produto sem ${__(field)}`));
                }
                
            }
            
            if(field == 'category' && requiredFields.includes(field)) {
                
                if(!content['category']?.name){
                    result.isValid = false;
                    result.errors.push(__(`Produto sem ${__(field)}`));
                } 
                
            }

            if(field == 'tags' || field == 'description' || field == 'title' && requiredFields.includes(field)) {

                if(!content['meta'][field]) {
                    result.isValid = false;
                    result.errors.push(__(`Produto sem ${__(field)}`));
                }

            }

            if(!content[field] && requiredFields.includes(field)) {

                result.isValid = false;
                result.errors.push(__(`Produto sem ${__(field)}`));

            }

            if(validationRules && validationRules[field]) {

                await Core.validateFieldRule(validationRules, { key: field, value: content[field] }, api).catch(err => {

                    result.isValid = false;
                    result.errors.push(__(err));

                });
            
            }

        }

        return Promise.resolve(result);

    },
    validateFieldRule: async function(fieldRules, field, api) {

        let fieldKey = field.key;
        let fieldValue = field.value;

        let rules = fieldRules[fieldKey];

        if (rules) {

            for (let ruleKey in rules) {

                let ruleValue = rules[ruleKey];

                switch (ruleKey) {
                    case 'max':

                        if(fieldKey == 'images'){

                            if(Array.from(new Set(fieldValue)).length > ruleValue) throw `Você só pode adicionar no máximo ${ruleValue} imagens`;
                            
                        }

                        if (typeof fieldValue === 'number' && fieldValue > ruleValue) throw `Você só pode adicionar no máximo ${ruleValue} itens para o campo ${fieldKey}`;
                        
                        if (typeof fieldValue === 'string' && fieldValue.length > ruleValue) throw `O máximo de caracteres para o campo ${fieldKey} é ${ruleValue}.`;
                        
                    break;
                    case 'min':

                        if (typeof fieldValue === 'number' && fieldValue < ruleValue) throw `Você deve adicionar no mínimo ${ruleValue} itens para o campo ${fieldKey}`;

                    break;
                    case 'regex':
                        
                        let errorDescription = 'Campo ' + fieldKey + ' inválido.';

                        if(ruleValue.errorDescription) errorDescription = ruleValue.errorDescription;

                        if(ruleValue.pattern) {
                            ruleValue = ruleValue.pattern;
                        }

                        let regex = new RegExp(ruleValue);

                        if(!regex.test(fieldValue)) {

                            throw errorDescription;

                        };

                    break;
                    default:
                    break;

                }
            
            }
        }
        
    },
    apiVars: {"alternativa":{"blockCategoryChange":true},"arius":{"blockCategoryChange":true},"hostgator":{"actions":true,"generativeFields":{"descricao_resumida *":{"label":"Descrição Resumida","type":"text","required":true}}},"lojaintegrada":{"blockCategoryChange":true},"mercadolivre":{"searchCategoryByApi":true,"disableHtml":true,"guessCategoryByProductDiscovery":true,"multipleCategorySelection":false,"guessImagesByProductDiscovery":true,"waitForInfosAfterCategoryChange":true,"disableCategoryPage":true},"nuvemshop":{"blockCategoryChange":true},"publicapi":{"actions":true},"tiny":{"actions":true}},
    syncSettings: {"alternativa":{"categories":{"label":"Categorias","entity":"categories","old":86400000},"provider":{"label":"Fabricante","entity":"provider","old":86400000},"products":{"label":"Produtos","entity":"products","old":86400000}},"blingv3":{"attributes":{"label":"Atributos","old":86400000}},"conectahub":{"brands":{"label":"Marcas","entity":"brands","old":86400000}},"hostgator":{"brands":{"label":"Marcas","entity":"brands"}},"lojaintegrada":{"categories":{"label":"Categorias","old":86400000}},"publicapi":{"categories":{"label":"Categorias"}}},
    defaultColumns: {"mercadolivre":[{"id":"currency_id","required":true,"default":"BRL","name":"Moeda","type":"enum","options":[{"name":"Real","value":"BRL"}]},{"id":"buying_mode","required":true,"default":"buy_it_now","name":"Modo de compra","type":"enum","options":[{"name":"Comprar agora","value":"buy_it_now"}]},{"id":"condition","required":true,"default":"new","name":"Condição","type":"enum","options":[{"name":"Novo","value":"new"},{"name":"Usado","value":"used"}]},{"id":"listing_type_id","required":true,"default":"free","name":"Tipo de anúncio","type":"enum","options":[{"name":"Grátis","value":"free"},{"name":"Bronze","value":"bronze"},{"name":"Prata","value":"silver"},{"name":"Ouro","value":"gold"},{"name":"Clássico","value":"gold_special"},{"name":"Diamante","value":"gold_premium"},{"name":"Premium","value":"gold_pro"}]},{"id":"official_store_id","required":false,"default":"","name":"ID da loja oficial","type":"text"},{"id":"WARRANTY_TYPE","required":true,"name":"Tipo de garantia","type":"enum","options":[{"name":"Garantia de fábrica","value":"Garantia de fábrica"},{"name":"Garantia do vendedor","value":"Garantia do vendedor"}]},{"id":"WARRANTY_TIME","required":true,"default":0,"name":"Tempo de garantia (dias)","type":"number","min":0}]}
}
