from   spirit.spirit       import   spirit # 
import json,unidecode


class tratoraco(spirit):
    def __init__(self, argv:list):
        self.options = {}
        super(tratoraco, self, ).__init__(argv)
        
        
    """ def order_customer_group_id(self, data):
        # 8 - consumidor final | 11 - Revendedor | 12 DIFAL menos parana
        tab_precos = {
            'tratoraco': {
                8   : "DIF",
                11  : "CON",
                12  : "CON",
            }
        }
        
        return tab_precos.get(self.nmlkgrupo.lower(),{}).get(data,"") """
    # ! Remover
    """ def rote_filter_orders(self):
        return  self.mountRouteParams({"order_integrated"     : '1'}) """
        
    def tabprecoxgrupocliente(self):
        """Usado para montar o preco por empresa
        """
        return  {
            #"8"   : "DIF"
            "11"   : "CON",
            "12"   : "CON"
        }
        
        
    def product_ipi(self, data):
        # 8 - consumidor final | 11 - Revendedor
        return """
            (
                SELECT
                    IF(
                        LEFT(TBPRODUTO.CDSITTRIBUTARIA,1) IN (1, 6),
                        '8,11,12',
                        ''
                    ) as tmp
                FROM
                    TBPRODUTO
                WHERE
                    TBPRODUTO.CDPRODUTO = TBIMPOSTOS.CDPRODUTO
            )
        """
        
    
    def shipping_method(self, data):
        return "T99999"
        
    def produtos_filhos(self, data):
        #COALESCE
        return """
            (
                SELECT
                    MD5(
                        GROUP_CONCAT(
                            CONCAT(
                                COALESCE(TP.DTULTALTERACAO, ''),
                                COALESCE(TP.VLQTDEATUAL, '')
                            )
                        )
                    ) as MD5_checksum
                FROM
                    TBPRODUTO TP
                WHERE
                    TP.CDREFERENCIA = TBPRODUTO.CDPRODUTO
            )
        """
        
    def produtos_quantidade(self, data):
        return """
            (SELECT
                IF(
                    (
                        SELECT
                            COUNT(TBPRO.CDREFERENCIA)
                        FROM
                            TBPRODUTO TBPRO
                        WHERE
                            TBPRO.CDREFERENCIA = TBPRODUTO.CDPRODUTO
                    ) > 0,
                    (
                        SELECT
                            SUM(TBPRO2.VLQTDEATUAL)
                        FROM
                            TBPRODUTO TBPRO2
                        WHERE
                            TBPRO2.CDREFERENCIA = TBPRODUTO.CDPRODUTO
                    ),
                    TBPRODUTO.VLQTDEATUAL
                )
            )
        """
        
        
    
    def get_spirit_options(self) :
        if self.options:
            return
        
        
        req = self.throttling(rote="options")
        
        if req.ok:
            data = self.tryJson(req) or {}
            self.options = data.get('options')
            return
            
        
        self.options = {}
        
        
        
        
    def montar_options(self, data):
        """Tratamento para precos 
        """
        options = []
        if data:
            self.get_spirit_options()
            
            produtos_filhos = self.select(f"SELECT * FROM TBPRODUTO WHERE CDREFERENCIA ={self.current_data.get('sku')}")
            option_type = None
            options_value = []
            option_data = {}
            
            
            for produto in produtos_filhos :
                codigo = produto.get('CDPRODUTO','')
                variacao = codigo[-2:]
                
                if not option_type :
                    option_type = "Numeracao" if  variacao.isdigit() else "Tamanho"
                    
                option_data,  = list(filter(lambda options : options.get('name') == option_type, self.options                 )) or [None]
                option_value, = list(filter(lambda value   : value  .get('name') == variacao, option_data.get('options_value'))) or [None]
                
                
                if (option_value) :
                    options_value +=  [{
                            "option_value_id"   : option_value.get("option_value_id"),
                            "sku"               : codigo,
                            "name"              : produto.get('DSPRODUTO',''),
                            "quantity"          : str(produto.get('VLQTDEATUAL','')),
                            #"price"             : str(produto.get('VLVENDA','')),
                            "weight"            : str(produto.get('VLPESOBRUTO','')),
                            "subtract"          : 1
                        }]
            
            options = [{
                "product_option_id" : self.current_data.get('sku'),
                "option_id"         : option_data.get('option_id'),
                "name"              : self.current_data.get('name'),
                "required"          : 1,
                "option_value"      : options_value
            }]
            
            
            
        return json.dumps(options)
        
        
        
    def payment_method(self, metodo_pagamento):
        """
            {"payments_code":[{"code":"bank_transfer"},{"code":"pagseguro"},{"code":"mercadopago2"},{"code":"rede_acquiring"},{"code":"pp_standard"}]}
            Tratamento de dados de pagamento relacionado a empresa esj empresa 1 filial 1
        """
        result = {}
        payment_code = self.current_order.get('payment_code',{})
        if payment_code and "pagar_me_cartao" in payment_code :
            parcela  = self.current_order.get('parcela', '')
            metodo_pagamento = unidecode.unidecode(metodo_pagamento).upper()
            metodo_pagamento = f"{metodo_pagamento} {parcela}X"
        
            result =  self.getDb().simple_select(
                    fields  =["CDCONDPGTO"]
                ,   table   ="TBCONDPGTO"
                ,   where   =[f"DSCONDPGTO='{metodo_pagamento}'"],
                    onlyFirst=True
            )
        elif payment_code and "pix" in payment_code : 
            result =  self.getDb().simple_select(
                    fields  =["CDCONDPGTO"]
                ,   table   ="TBCONDPGTO"
                ,   where   =[f"DSCONDPGTO LIKE 'PIX%'"],
                    onlyFirst=True
            )
            
        elif payment_code and "boleto" in payment_code : 
            result =  self.getDb().simple_select(
                    fields  =["CDCONDPGTO"]
                ,   table   ="TBCONDPGTO"
                ,   where   =[f"DSCONDPGTO LIKE 'BOLETO%'"],
                    onlyFirst=True
            )

        return result.get('CDCONDPGTO', '0')
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    