import pandas as pd
from app.Models.fox_products_models import ( fox_cmp,fox_descripc,fox_pedidos,fox_leyendas,fox_cmp_aper,fox_a_segmto,fox_a_tiposb,fox_a_linea,fox_a_color,fox_a_materl,fox_a_caract,fox_a_colecn) 
import csv
from django.http import JsonResponse, HttpResponse
from django.db.models import Q
from decimal import Decimal, ROUND_HALF_UP, ROUND_DOWN


def redondear_entero(valor):
    try:
        # Redondear al entero más cercano (como Excel: .5 sube, <.5 baja)
        valor_redondeado = Decimal(valor).quantize(Decimal("1"), rounding=ROUND_HALF_UP)
        return f"{valor_redondeado:.0f}".replace('.', ',')
    except:
        return ''
    
def truncate_entero(valor): 
    try:
        # Truncar hacia abajo (eliminar decimales sin redondear)
        valor_truncado = Decimal(valor).quantize(Decimal("1"), rounding=ROUND_DOWN)
        return f"{valor_truncado:.0f}".replace('.', ',')
    except:
        return ''    

#redondea a 4 decimales:
def redondear_decimal(valor): 
    try:
        valor_redondeado = Decimal(valor).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
        return f"{valor_redondeado:.4f}".replace('.', ',')
    except:
        return ''

def redondear_decimal_dos(valor):
    try:
        valor_redondeado = Decimal(valor).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
        return f"{valor_redondeado:.2f}".replace('.', ',')
    except:
        return ''
    
def redondear_decimal_cuatro(valor):
    try:
        # Forzar a string para que Decimal no pierda precisión
        valor_redondeado = Decimal(str(valor)).quantize(Decimal("0.0001"), rounding=ROUND_HALF_UP)
        # Convertir a string con 4 decimales y reemplazar '.' por ','
        return format(valor_redondeado, ".4f").replace('.', ',')
    except Exception:
        return ''


def calcular_fact_fac(row):
    try:
        if pd.notna(row['unid_fac']) and pd.notna(row['pr_oferta']) and pd.notna(row['coeficie']):
            resultado = Decimal(str(row['unid_fac'])) * Decimal(str(row['pr_oferta'])) * Decimal(str(row['coeficie']))
            return resultado
    except:
        return None
    


def report_exporta_data(data):
    try:
        camfromyear = int(data.get('camfromyear'))
        camtoyear = int(data.get('camtoyear'))
        camfromday = int(data.get('camfromday'))
        camtoday = int(data.get('camtoday'))    
        inp_codigo = data.get('inp_codigo')

        inp_division = data.get('inp_division')
        inp_sub_division = data.get('inp_sub_division')
        inp_segmento = data.get('inp_segmento')
        inp_forma_pt = data.get('inp_forma_pt')
        inp_target = data.get('inp_target')

        inp_descripcion = data.get('inp_descripcion')
        inp_categoria = data.get('inp_categoria')
        inp_procedencia = data.get('inp_procedencia')
        inp_cod_medida = data.get('inp_cod_medida')
        inp_cuotas = data.get('inp_cuotas')
        inp_linea = data.get('inp_linea')
        inp_sub_linea = data.get('inp_sub_linea')
        inp_tipo_de_subl = data.get('inp_tipo_de_subl')
        
        inp_peso = data.get('inp_peso')
        inp_cond_compra = data.get('inp_cond_compra')

        inp_uxp_estimado = data.get('inp_uxp_estimado')
        inp_uxp_real = data.get('inp_uxp_real')
        inp_uxp_facturado = data.get('inp_uxp_facturado')
        inp_alto = data.get('inp_alto')
        inp_ord_media_est = data.get('inp_ord_media_est')

        inp_unid_estim = data.get('inp_unid_estim')
        inp_unid_vendidas = data.get('inp_unid_vendidas')
        inp_unid_fact = data.get('inp_unid_fact')
        inp_largo = data.get('inp_largo')
        inp_ord_media_real = data.get('inp_ord_media_real')

        inp_tipo_de_oferta = data.get('inp_tipo_de_oferta')
        inp_consignacion = data.get('inp_consignacion')
        inp_grupo_fabric = data.get('inp_grupo_fabric')
        inp_ancho = data.get('inp_ancho')
        inp_uxp_tag = data.get('inp_uxp_tag')

        inp_precio_de_oferta = data.get('inp_precio_de_oferta')
        inp_cabecera = data.get('inp_cabecera')
        inp_elaboracion = data.get('inp_elaboracion')
        inp_volumen = data.get('inp_volumen')
        inp_unid_tag = data.get('inp_unid_tag')

        inp_precio_normal = data.get('inp_precio_normal')
        inp_coeficiente = data.get('inp_coeficiente')
        inp_packaging = data.get('inp_packaging')
        inp_talle_tamano = data.get('inp_talle_tamano')
        inp_pedidos_estm = data.get('inp_pedidos_estm')

        inp_margen_estimado = data.get('inp_margen_estimado')
        inp_margen_real = data.get('inp_margen_real')
        inp_envase_do_crit = data.get('inp_envase_do_crit')
        inp_color = data.get('inp_color')
        inp_pedidos_reales = data.get('inp_pedidos_reales')

        inp_costo_estimado = data.get('inp_costo_estimado')
        inp_costo_real = data.get('inp_costo_real')
        inp_canal = data.get('inp_canal')
        inp_material_tela = data.get('inp_material_tela')

        inp_fact_estimado = data.get('inp_fact_estimado')
        inp_fact_real = data.get('inp_fact_real')
        inp_fact_fact = data.get('inp_fact_fact')
        inp_caracterist = data.get('inp_caracterist')

        inp_empresa = data.get('inp_empresa')
        inp_multi_empresa = data.get('inp_multi_empresa')
        inp_equivalencia_mk = data.get('inp_equivalencia_mk')
        inp_coleccion = data.get('inp_coleccion')

        inp_nro_de_pagina = data.get('inp_nro_de_pagina')
        inp_estado = data.get('inp_estado')
        inp_punto_de_precio = data.get('inp_punto_de_precio')
        inp_sexo = data.get('inp_sexo')
        inp_procedencia = data.get('inp_procedencia')



        # Cargar todas las leyendas, no solo clave_camp=2 (para usos futuros)
        df_leyendas = pd.DataFrame(list(
            fox_leyendas.objects.all().values('clave_camp', 'clave', 'leyenda')
        ))




            
      
        cmp_fields = ['camp', 'ano']
        if inp_codigo:
            cmp_fields.append('codigon')
        if inp_uxp_estimado:
            cmp_fields.append('uxp')
        if inp_uxp_real:
            cmp_fields.append('uxp_real')
        if inp_uxp_facturado:
            cmp_fields.append('uxp_pre')
        if inp_uxp_facturado or inp_fact_fact or inp_unid_fact:
            cmp_fields.append('unid_fac')
        if inp_tipo_de_oferta:
            cmp_fields.append('tipo_of')
        if inp_precio_de_oferta or inp_fact_fact:
            cmp_fields.append('pr_oferta')
        if inp_precio_normal:
            cmp_fields.append('pr_normal')

        if inp_margen_estimado:
            cmp_fields.append('mar_est')
        if inp_margen_real:
            cmp_fields.append('mar_real')

        if inp_costo_estimado:
            cmp_fields.append('costo_est')
            cmp_fields.append('tipo_est')
            
        if inp_costo_real:
            cmp_fields.append('costo_real')
            
        if inp_fact_estimado:
            cmp_fields.append('fact_est')
        
        if inp_fact_real:
            cmp_fields.append('fact_real')

        if inp_fact_fact:
            cmp_fields.append('coeficie')
            
        if inp_unid_estim:
            cmp_fields.append('unid_est')
            
        if inp_unid_vendidas:
            cmp_fields.append('unidades')
        
        if inp_coeficiente:
            cmp_fields.append('coeficie')  
            
        
            
            
      

        #replace all fact_fac with cmp_hist.unid_fac * cmp_hist.pr_oferta * cmp_hist.coeficie
        #                                                        354   222*  119.99 * 0.5293 = 14099,3769 aprox a 2 dígitos queda igual
        #                                                              889 * 14.99  * 0,7561 = 10075,87
        
        if inp_nro_de_pagina:
            cmp_fields.append('pagina')
        
        
        
        
        
        
        
        

        cmp_qs = fox_cmp.objects

        # Filtrado de x campaña a x campaña el reporte de exportación 
        if camfromyear == camtoyear:
            cmp_qs = cmp_qs.filter(
                ano=camfromyear,
                camp__gte=camfromday,
                camp__lte=camtoday
            )
        else:
            cmp_qs = cmp_qs.filter(
                Q(ano=camfromyear, camp__gte=camfromday) |
                Q(ano__gt=camfromyear, ano__lt=camtoyear) |
                Q(ano=camtoyear, camp__lte=camtoday)
            )

        cmp_data = list(cmp_qs.values(*cmp_fields))
            
        df_cmp = pd.DataFrame(cmp_data) #datos de cmp


#------------------------------Inicio Calculo de Valores de Varibles----------------------------------------------------#

            
        # === CARGAR ped_reales y ped_estim desde fox_pedidos ===
        if inp_uxp_facturado or inp_pedidos_estm or inp_pedidos_reales or inp_unid_tag or inp_uxp_tag:
            print("=== Cargando fox_pedidos ===")
        
            pedidos_fields = ['anio', 'campania', 'ped_reales', 'ped_estim','ped_tag']
            print("Cargando desde fox_pedidos con campos:", pedidos_fields)
            df_pedidos = pd.DataFrame(list(fox_pedidos.objects.all().values(*pedidos_fields)))
            print("Columnas realmente obtenidas:", df_pedidos.columns.tolist())    
             

            df_pedidos = df_pedidos[df_pedidos['ped_reales'].notna()]
                

            # Crear claves para merge
            df_cmp['clave'] = df_cmp['ano'].astype(str) + df_cmp['camp'].astype(int).astype(str)
            df_pedidos['clave'] = df_pedidos['anio'].astype(str) + df_pedidos['campania'].astype(str)

                

            df_cmp = pd.merge(df_cmp, df_pedidos[['clave', 'ped_reales', 'ped_estim','ped_tag']], on='clave', how='left')
                            

            # Calcular UXP_FAC: unid_fac / ped_reales (si ped_reales ≠ 0)
            df_cmp['UXP_FAC'] = df_cmp.apply(
                lambda row: row['unid_fac'] / row['ped_reales']
                if pd.notna(row['unid_fac']) and pd.notna(row['ped_reales']) and row['ped_reales'] != 0
                else None,
                axis=1
            )
            
                          
            df_cmp.rename(columns={
                'ped_estim': 'PED_ESTIM',
                'ped_reales': 'PED_REALES',
                'ped_tag':'UNID_TAG'
            }, inplace=True)
               
            if 'uxp_pre' in df_cmp.columns:
                df_cmp.rename(columns={'uxp_pre': 'UXP_TAG'}, inplace=True)
            

            #print("Columnas en df_cmp:", df_cmp.columns.tolist())

            if 'coeficie' in df_cmp.columns and 'pr_oferta' in df_cmp.columns and 'unid_fac' in df_cmp.columns:
                df_cmp['FACT_FAC'] = df_cmp.apply(calcular_fact_fac, axis=1)
                #fin nuevo UXP_FAC
                
            if inp_unid_estim and inp_costo_estimado:
                    # === COS_ESTOT = UNID_EST * COSTO_EST (cálculo seguro y vectorizado) ===
                if {'unid_est', 'costo_est'}.issubset(df_cmp.columns):
                    # Convertir a numérico sin romper si vienen strings; NaN si no se puede
                    unid_est_num  = pd.to_numeric(df_cmp['unid_est'],  errors='coerce')
                    costo_est_num = pd.to_numeric(df_cmp['costo_est'], errors='coerce')

                    # Multiplicar sólo cuando ambos existen
                    df_cmp['COS_ESTOT'] = (unid_est_num * costo_est_num).where(
                        unid_est_num.notna() & costo_est_num.notna(),
                        other=None
                    )

                    # Redondear y pasar a string con coma decimal
                    df_cmp['COS_ESTOT'] = df_cmp['COS_ESTOT'].apply(redondear_decimal_dos)

                else:
                    # Si faltan columnas, no hacemos nada (no rompemos el flujo)
                    df_cmp['COS_ESTOT'] = None
                    
                    
            if inp_costo_real and inp_unid_vendidas:
                    # === COS_REATOT = UNIDADES * COSTO_REAL (cálculo seguro y vectorizado) ===
                if {'unidades', 'costo_real'}.issubset(df_cmp.columns):
                    # Convertir a numérico sin romper si vienen strings; NaN si no se puede
                    unidades_num   = pd.to_numeric(df_cmp['unidades'],  errors='coerce')
                    costo_real_num = pd.to_numeric(df_cmp['costo_real'], errors='coerce')

                    # Multiplicar sólo cuando ambos existen
                    df_cmp['COS_REATOT'] = (unidades_num * costo_real_num).where(
                        unidades_num.notna() & costo_real_num.notna(),
                        other=None
                    )

                    # Redondear y pasar a string con coma decimal
                    df_cmp['COS_REATOT'] = df_cmp['COS_REATOT'].apply(redondear_decimal_dos)

                else:
                    # Si faltan columnas, no hacemos nada (no rompemos el flujo)
                    df_cmp['COS_REATOT'] = None
    
#------------------------------ Fin Calculo de Valores de Varibles------------------------------------- #        

#------------------------------Inicio Inicio Zona Valores Leyendas-------------------------------------- -#

        
        if inp_tipo_de_oferta:
            df_ley_tipo_of = df_leyendas[df_leyendas['clave_camp'] == 2].copy()
            df_ley_tipo_of.rename(columns={'clave': 'tipo_of', 'leyenda': 'ley_tipo_of'}, inplace=True)
            

            # Unir a df_cmp por tipo_of (puede venir como float si hay nulos)
            df_cmp['tipo_of'] = df_cmp['tipo_of'].astype(pd.Int64Dtype())
            df_ley_tipo_of['tipo_of'] = df_ley_tipo_of['tipo_of'].astype(pd.Int64Dtype())

            df_cmp = pd.merge(df_cmp, df_ley_tipo_of, on='tipo_of', how='left')

            #futuro otras leyendas
            #df_ley_sublinea = df_leyendas[df_leyendas['clave_camp'] == 5].copy()
            #df_ley_sublinea.rename(columns={'clave': 'sub_linea', 'leyenda': 'ley_subl'}, inplace=True)
            #df_desc = pd.merge(df_desc, df_ley_sublinea, on='sub_linea', how='left')

        


#------------------------------Fin  Zona Valores Leyendas-------------------------------------------------#



        descripc_fields = ['codigon']
        if inp_descripcion:
            descripc_fields.append('descrip')
        if inp_division:
            descripc_fields.append('division')
        if inp_sub_division:
            descripc_fields.append('sub_divi')
        if inp_segmento:
            descripc_fields.append('segmento')
        if inp_forma_pt:
            descripc_fields.append('forma_pt')
        if inp_target:
            descripc_fields.append('target')
        if inp_categoria:
            descripc_fields.append('categoria')   
        if inp_sub_linea:
            descripc_fields.append('sub_linea')   
        if inp_tipo_de_subl:
            descripc_fields.append('tipo_subl')
        if inp_linea:
            descripc_fields.append('linea')  # nombre en la base de datos  
        if inp_color:
            descripc_fields.append('det_color')
        if inp_talle_tamano:
            descripc_fields.append('talle')  
        if inp_material_tela:
            descripc_fields.append('material') 
        if inp_caracterist:
            descripc_fields.append('caracteris')
        if inp_coleccion:
            descripc_fields.append('coleccion')
        if inp_punto_de_precio:
            descripc_fields.append('pto_precio')   
        if inp_packaging:
            descripc_fields.append('packaging')
        if inp_envase_do_crit:
            descripc_fields.append('envase_2do')
        if inp_sexo:
            descripc_fields.append('sexo')
        if inp_procedencia:
            descripc_fields.append('proc')
        if inp_consignacion:
            descripc_fields.append('consig')
        if inp_empresa:
            descripc_fields.append('empresa')
        if inp_multi_empresa:
            descripc_fields.append('mul_emp')
        if inp_grupo_fabric:
            descripc_fields.append('grupo_fabr')
        if inp_elaboracion:
            descripc_fields.append('elaborac')
        if inp_canal:
            descripc_fields.append('canal')
        if inp_cod_medida:
            descripc_fields.append('cod_medi')
        if inp_peso:
            descripc_fields.append('peso')
        if inp_alto:
            descripc_fields.append('alto')
        if inp_largo:
            descripc_fields.append('largo')
        if inp_ancho:
            descripc_fields.append('ancho')
        if inp_volumen:
            descripc_fields.append('volumen')
        if inp_cuotas:
            descripc_fields.append('cuotas')
        if inp_cond_compra:
            descripc_fields.append('con_compra')
        
            
        
        
        codigon_list = df_cmp['codigon'].dropna().unique()
        descrip_data = fox_descripc.objects.filter(codigon__in=codigon_list).values(*descripc_fields)
        df_desc = pd.DataFrame(list(descrip_data)) #datos de descripc
        
        if inp_sub_division:
            df_aux_subd = df_leyendas[df_leyendas['clave_camp'] == 7][['clave', 'leyenda']].copy()
            df_aux_subd.rename(columns={'clave': 'sub_divi', 'leyenda': 'LEYESUBD'}, inplace=True)
            df_desc = pd.merge(df_desc, df_aux_subd, on='sub_divi', how='left')

        if inp_categoria:
            df_ley_categoria = df_leyendas[df_leyendas['clave_camp'] == 3].copy()
            df_ley_categoria.rename(columns={'clave': 'categoria', 'leyenda': 'LEYENDA'}, inplace=True)
            df_desc = pd.merge(df_desc, df_ley_categoria, on='categoria', how='left')
            
            
        if inp_sub_linea:
            df_aux_subl = df_leyendas[df_leyendas['clave_camp'] == 5][['clave', 'leyenda']].copy()
            df_aux_subl.rename(columns={'clave': 'sub_linea', 'leyenda': 'LEYESUBL'}, inplace=True)
            df_desc = pd.merge(df_desc, df_aux_subl, on='sub_linea', how='left')
            
        if inp_packaging:
            df_ley_pack = df_leyendas[df_leyendas['clave_camp'] == 19][['clave', 'leyenda']].copy()
            df_ley_pack.rename(columns={'clave': 'packaging', 'leyenda': 'LEYPACK'}, inplace=True)
            df_desc = pd.merge(df_desc, df_ley_pack, on='packaging', how='left')
            
        if inp_envase_do_crit: 
            df_envase_do = df_leyendas[df_leyendas['clave_camp'] == 20][['clave', 'leyenda']].copy()
            df_envase_do.rename(columns={'clave': 'envase_2do', 'leyenda': 'LEYENV2'}, inplace=True)
            df_desc = pd.merge(df_desc, df_envase_do, on='envase_2do', how='left')
            
        if inp_punto_de_precio: 
            df_ptopre = df_leyendas[df_leyendas['clave_camp'] == 18][['clave', 'leyenda']].copy()
            df_ptopre.rename(columns={'clave': 'pto_precio', 'leyenda': 'LEY_PTOPRE'}, inplace=True)
            df_desc = pd.merge(df_desc, df_ptopre, on='pto_precio', how='left')
            
        if inp_sexo: 
            df_sexo = df_leyendas[df_leyendas['clave_camp'] == 16][['clave', 'leyenda']].copy()
            df_sexo.rename(columns={'clave': 'sexo', 'leyenda': 'LEY_SEXO'}, inplace=True)
            df_desc = pd.merge(df_desc, df_sexo, on='sexo', how='left')
            
        if inp_target: 
            df_target = df_leyendas[df_leyendas['clave_camp'] == 17][['clave', 'leyenda']].copy()
            df_target.rename(columns={'clave': 'target', 'leyenda': 'LEY_TARG'}, inplace=True)
            df_desc = pd.merge(df_desc, df_target, on='target', how='left')

        if inp_procedencia: 
            df_proc = df_leyendas[df_leyendas['clave_camp'] == 6][['clave', 'leyenda']].copy()
            df_proc.rename(columns={'clave': 'proc', 'leyenda': 'LEYEPRO'}, inplace=True)
            df_desc = pd.merge(df_desc, df_proc, on='proc', how='left')

        if inp_grupo_fabric: 
            df_fabr = df_leyendas[df_leyendas['clave_camp'] == 9][['clave', 'leyenda']].copy()
            df_fabr.rename(columns={'clave': 'grupo_fabr', 'leyenda': 'LEY_FABR'}, inplace=True)
            df_desc = pd.merge(df_desc, df_fabr, on='grupo_fabr', how='left')

        if inp_elaboracion: 
            df_elaboracion = df_leyendas[df_leyendas['clave_camp'] == 11][['clave', 'leyenda']].copy()
            df_elaboracion.rename(columns={'clave': 'elaborac', 'leyenda': 'LEY_ELAB'}, inplace=True)
            df_desc = pd.merge(df_desc, df_elaboracion, on='elaborac', how='left')
            
           
        if inp_canal:
            df_canal = df_leyendas[df_leyendas['clave_camp'] == 15][['clave', 'leyenda']].copy()
            df_canal.rename(columns={'clave': 'canal', 'leyenda': 'LEY_CNL'}, inplace=True)
            df_desc = pd.merge(df_desc, df_canal, on='canal', how='left')    
            
        if inp_forma_pt:
            df_forma_pt = df_leyendas[df_leyendas['clave_camp'] == 12][['clave', 'leyenda']].copy()
            df_forma_pt.rename(columns={'clave': 'forma_pt', 'leyenda': 'LEY_FOR'}, inplace=True)
            df_desc = pd.merge(df_desc, df_forma_pt, on='forma_pt', how='left') 
            
        if inp_cod_medida:
            df_cod_medida = df_leyendas[df_leyendas['clave_camp'] == 13][['clave', 'leyenda']].copy()
            df_cod_medida.rename(columns={'clave': 'cod_medi', 'leyenda': 'LEY_MED'}, inplace=True)
            df_desc = pd.merge(df_desc, df_cod_medida, on='cod_medi', how='left')    
            
#------------------------------Inicio Inicio Zona Valores Aper--------------------------------------------#

        
        if inp_cabecera: 
            # Cargar datos de la tabla fox_cmp_aper con el campo 'codigon' y 'cabecera'
            cmp_aper_fields = ['codigon', 'cabecera']
            df_cmp_aper = pd.DataFrame(list(fox_cmp_aper.objects.filter(codigon__in=codigon_list).values(*cmp_aper_fields)))

            # Unir df_cmp con df_cmp_aper usando 'codigon' como clave
            df_cmp = pd.merge(df_cmp, df_cmp_aper[['codigon', 'cabecera']], on='codigon', how='left')

            # Ahora puedes acceder a 'cabecera' desde el DataFrame df_cmp


#------------------------------Fin  Zona Valores Aper----------------------------------------------------#

#------------------------------Inicio Inicio Zona Valores Segmento--------------------------------------------#
#inp_segmento
#     
        if inp_segmento: 
            segmento_list = df_desc['segmento'].dropna().unique()

            df_segmento_leyendas = pd.DataFrame(
                list(fox_a_segmto.objects.filter(clave__in=segmento_list).values('clave', 'leyenda'))
            )
            df_segmento_leyendas.rename(columns={'clave': 'segmento', 'leyenda': 'leyenda_segmento'}, inplace=True)

            # Asegurar el mismo tipo de dato en ambas columnas
            df_desc['segmento'] = df_desc['segmento'].astype(str)
            df_segmento_leyendas['segmento'] = df_segmento_leyendas['segmento'].astype(str)

            # Merge seguro
            df_desc = pd.merge(df_desc, df_segmento_leyendas, on='segmento', how='left')
#------------------------------Fin  Zona Valores Segmento----------------------------------------------------#
#------------------------------Inicio Inicio Zona Valores fox_a_tiposb--------------------------------------------#
#inp_sub_linea
#     
        if inp_tipo_de_subl:
            tipo_subl_list = df_desc['tipo_subl'].dropna().unique()

            df_tipo_subl_leyendas = pd.DataFrame(
                list(fox_a_tiposb.objects.filter(clave__in=tipo_subl_list).values('clave', 'leyenda'))
            )
            df_tipo_subl_leyendas.rename(columns={'clave': 'tipo_subl', 'leyenda': 'leyenda_tipo_subl'}, inplace=True)

            # Asegurar el mismo tipo de dato en ambas columnas
            df_desc['tipo_subl'] = df_desc['tipo_subl'].astype(str)
            df_tipo_subl_leyendas['tipo_subl'] = df_tipo_subl_leyendas['tipo_subl'].astype(str)

            # Merge seguro
            df_desc = pd.merge(df_desc, df_tipo_subl_leyendas, on='tipo_subl', how='left')


#------------------------------Fin  Zona Valores fox_a_tiposb----------------------------------------------------#
#------------------------------Inicio Inicio Zona Valores fox_a_linea LEY_LIN--------------------------------------------#
#inp_sub_linea
#     
        if inp_linea: 
            
            tipo_linea_list = df_desc['linea'].dropna().unique()
            df_linea_leyendas = pd.DataFrame(
                list(fox_a_linea.objects.filter(clave__in=tipo_linea_list).values('clave', 'leyenda'))
            )
            df_linea_leyendas.rename(columns={'clave': 'linea', 'leyenda': 'LEY_LIN'}, inplace=True)
            df_desc['linea'] = df_desc['linea'].astype(str)
            df_linea_leyendas['linea'] = df_linea_leyendas['linea'].astype(str)
            df_desc = pd.merge(df_desc, df_linea_leyendas, on='linea', how='left')


#------------------------------Fin  Zona Valores fox_a_linea LEY_LIN ----------------------------------------------------#f
#------------------------------Inicio Zona Valores fox_a_color LEY_COLOR--------------------------------------------#
# inp_color

        if inp_color: 
            color_list = df_desc['det_color'].dropna().unique()
            df_color_leyendas = pd.DataFrame(
                list(fox_a_color.objects.filter(clave__in=color_list).values('clave', 'leyenda'))
            )
            df_color_leyendas.rename(columns={'clave': 'det_color', 'leyenda': 'LEY_COLOR'}, inplace=True)
            df_desc['det_color'] = df_desc['det_color'].astype(str)
            df_color_leyendas['det_color'] = df_color_leyendas['det_color'].astype(str)
            df_desc = pd.merge(df_desc, df_color_leyendas, on='det_color', how='left')
         

#------------------------------Fin Zona Valores fox_a_color LEY_COLOR----------------------------------------------------#
#------------------------------Inicio Zona Valores fox_a_materl LEY_MATE--------------------------------------------#
# inp_material_tela

        if inp_material_tela:
            material_list = df_desc['material'].dropna().unique()

            df_material_leyendas = pd.DataFrame(
                list(fox_a_materl.objects.filter(clave__in=material_list).values('clave', 'leyenda'))
            )
            df_material_leyendas.rename(columns={'clave': 'material', 'leyenda': 'LEY_MATE'}, inplace=True)

            # Asegurar que ambos campos sean string
            df_desc['material'] = df_desc['material'].astype(str)
            df_material_leyendas['material'] = df_material_leyendas['material'].astype(str)

            # Merge seguro
            df_desc = pd.merge(df_desc, df_material_leyendas, on='material', how='left')
            
#------------------------------Fin Zona Valores fox_a_materl LEY_MATE----------------------------------------------------#
#------------------------------Inicio Zona Valores fox_a_caract LEY_CARA--------------------------------------------#
# inp_caracterist 
        if inp_caracterist:
            caracteris_list = df_desc['caracteris'].dropna().unique()

            df_caracterist_leyendas = pd.DataFrame(
                list(fox_a_caract.objects.filter(clave__in=caracteris_list).values('clave', 'leyenda'))
            )
            df_caracterist_leyendas.rename(columns={'clave': 'caracteris', 'leyenda': 'LEY_CARA'}, inplace=True)

            # Asegurar que ambos campos sean string
            df_desc['caracteris'] = df_desc['caracteris'].astype(str)
            df_caracterist_leyendas['caracteris'] = df_caracterist_leyendas['caracteris'].astype(str)

            # Merge seguro
            df_desc = pd.merge(df_desc, df_caracterist_leyendas, on='caracteris', how='left')
            
#------------------------------Fin Zona Valores fox_a_caract LEY_CARA----------------------------------------------------#


#------------------------------Inicio Zona Valores fox_a_colecn LEY_COLE--------------------------------------------#
# inp_coleccion  7x
        if inp_coleccion:
            coleccion_list = df_desc['coleccion'].dropna().unique()

            df_coleccion_leyendas = pd.DataFrame(
                list(fox_a_colecn.objects.filter(clave__in=coleccion_list).values('clave', 'leyenda'))
            )
            df_coleccion_leyendas.rename(columns={'clave': 'coleccion', 'leyenda': 'LEY_COLE'}, inplace=True)

            # Asegurar que ambos campos sean string
            df_desc['coleccion'] = df_desc['coleccion'].astype(str)
            df_coleccion_leyendas['coleccion'] = df_coleccion_leyendas['coleccion'].astype(str)

            # Merge seguro
            df_desc = pd.merge(df_desc, df_coleccion_leyendas, on='coleccion', how='left')
            
#------------------------------Fin Zona Valores fox_a_colecn LEY_COLE----------------------------------------------------#








        df_cmp['UXP'] = df_cmp['uxp'].apply(redondear_decimal)
        df_cmp['UXP_REAL'] = df_cmp['uxp_real'].apply(redondear_decimal)
        #antes: df_cmp['UXP_FAC'] = df_cmp['uxp_pre'].apply(redondear_decimal)
        df_cmp['UXP_FAC'] = df_cmp['UXP_FAC'].apply(redondear_decimal)

        if inp_precio_de_oferta:
            df_cmp['PR_OFERTA'] = df_cmp['pr_oferta'].apply(redondear_decimal)

        if inp_precio_normal:
            df_cmp['PR_NORMAL'] = df_cmp['pr_normal'].apply(redondear_decimal)

        if inp_margen_estimado:
            df_cmp['MAR_EST'] = df_cmp['mar_est'].apply(redondear_decimal)

        if inp_margen_real:
            df_cmp['MAR_REAL'] = df_cmp['mar_real'].apply(redondear_decimal)

        if inp_costo_estimado:
            df_cmp['COSTO_EST'] = df_cmp['costo_est'].apply(redondear_decimal)


        if inp_costo_real:
            df_cmp['COSTO_REAL'] = df_cmp['costo_real'].apply(redondear_decimal)
            
        if inp_fact_estimado:
            df_cmp['FACT_EST'] = df_cmp['fact_est'].apply(redondear_decimal_dos)
        
        if inp_fact_real:
            df_cmp['FACT_REAL'] = df_cmp['fact_real'].apply(redondear_decimal_dos)
        
        if inp_fact_fact:
            df_cmp['FACT_FAC'] = df_cmp['FACT_FAC'].apply(redondear_decimal_dos)

        if inp_unid_estim:
            df_cmp['UNID_EST'] = df_cmp['unid_est'].apply(redondear_decimal_dos)
        if inp_unid_vendidas:
            df_cmp['UNIDADES'] = df_cmp['unidades'].apply(redondear_decimal_dos)
        if inp_unid_fact:
            df_cmp['UNID_FAC'] = df_cmp['unid_fac'].apply(redondear_decimal_dos)
        if inp_coeficiente:
            df_cmp['COEFICIE'] = df_cmp['coeficie']#.apply(redondear_decimal_dos)
        #if inp_uxp_tag:
        #    df_cmp['UXP_TAG'] = df_cmp['coeficie']#.apply(redondear_decimal_dos)    
            

            


        # JOIN (merge)
        df_merged = pd.merge(df_cmp, df_desc, on='codigon', how='left')

        rename_dict = {
            'camp': 'CAMP',
            'ano': 'ANO',
            'codigon': 'CODIGON'
        }
        
        
        #lo que no esta antes del Merged, se renombra:

        if inp_descripcion:  # Solo renombrar si el campo fue solicitado
            rename_dict['descrip'] = 'DESCRIP'

        if inp_division:
            rename_dict['division'] = 'DIVISION'
        if inp_sub_division:
            rename_dict['sub_divi'] = 'SUB_DIVI'
            
        if inp_segmento:
            rename_dict['segmento'] = 'SEGMENTO'
            rename_dict['leyenda_segmento'] = 'LEY_SEG'
        if inp_forma_pt:
            rename_dict['forma_pt'] = 'FORMA_PT'
        if inp_target:
            rename_dict['target'] = 'TARGET'
        if inp_tipo_de_oferta:
            rename_dict['tipo_of'] = 'TIPO_OF'
            rename_dict['ley_tipo_of'] = 'LEYEOFE'
        if inp_costo_estimado:
            rename_dict['tipo_est'] = 'TIPO_EST'
        if inp_nro_de_pagina:
            rename_dict['pagina'] = 'PAGINA'     
        if inp_categoria:
            rename_dict['categoria'] = 'CATEGORIA'
        if inp_sub_linea:
            rename_dict['sub_linea'] = 'SUB_LINEA'
        if inp_tipo_de_subl:
            rename_dict['tipo_subl'] = 'TIPO_SUBL'
            rename_dict['leyenda_tipo_subl'] = 'LEY_TSLIN'
                
        if inp_linea:
            rename_dict['linea'] = 'LINEA'    
        if inp_color:
            rename_dict['det_color'] = 'DET_COLOR'
        if inp_talle_tamano:
            rename_dict['talle'] = 'TALLE'
        if inp_material_tela:
            rename_dict['material'] = 'MATERIAL'
        if inp_caracterist:
            rename_dict['caracteris'] = 'CARACTERIS'
        if inp_coleccion:
            rename_dict['coleccion'] = 'COLECCION'
        if inp_punto_de_precio:
            rename_dict['pto_precio'] = 'PTO_PRECIO'
        if inp_packaging:
            rename_dict['packaging'] = 'PACKAGING'
        if inp_envase_do_crit:
            rename_dict['envase_2do'] = 'ENVASE_2DO'
        if inp_sexo:
            rename_dict['sexo'] = 'SEXO'
        if inp_procedencia:
            rename_dict['proc'] = 'PROC'
        if inp_consignacion:
            rename_dict['consig'] = 'CONSIG'    
        if inp_cabecera:
            rename_dict['cabecera'] = 'CABECERA'
        if inp_empresa:
            rename_dict['empresa'] = 'EMPRESA'
        if inp_multi_empresa:
            rename_dict['mul_emp'] = 'MUL_EMP'   
        if inp_grupo_fabric:
            rename_dict['grupo_fabr'] = 'GRUPO_FABR'     
        if inp_elaboracion:
            rename_dict['elaborac'] = 'ELABORAC'
        if inp_canal:
            rename_dict['canal'] = 'CANAL'
        if inp_cod_medida:
            rename_dict['cod_medi'] = 'COD_MEDI'
        if inp_peso:
            rename_dict['peso'] = 'PESO'  
        if inp_alto:
            rename_dict['alto'] = 'ALTO'
        if inp_largo:
            rename_dict['largo'] = 'LARGO'
        if inp_ancho:
            rename_dict['ancho'] = 'ANCHO'
        if inp_volumen:
            rename_dict['volumen'] = 'VOLUMEN'
        if inp_cuotas:
            rename_dict['cuotas'] = 'CUOTAS'    
        if inp_cond_compra:
            rename_dict['con_compra'] = 'CON_COMPRA'
        
        
        
        
        df_merged.rename(columns=rename_dict, inplace=True)


        # Preparar respuesta
        filename = f'parametros_premios.csv'
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        writer = csv.writer(response, delimiter=';', quoting=csv.QUOTE_MINIMAL)

        # Cabecera
        header = ['CAMP', 'ANO']
        if inp_codigo:
            header.append('CODIGON')
      
        if inp_descripcion:
            header.append('DESCRIP')
            
        if inp_division:
            header.append('DIVISION')
       
        if inp_uxp_estimado:
            header.append('UXP')
        if inp_uxp_real:
            header.append('UXP_REAL')
        if inp_uxp_facturado:
            header.append('UXP_FAC')

        if inp_tipo_de_oferta:
            header.append('TIPO_OF')
            header.append('LEYEOFE')

        if inp_precio_de_oferta:
            header.append('PR_OFERTA')
        if inp_precio_normal:
            header.append('PR_NORMAL')


        if inp_margen_estimado:
            header.append('MAR_EST')
        if inp_margen_real:
            header.append('MAR_REAL')

        if inp_costo_estimado:
            header.append('COSTO_EST')
            header.append('TIPO_EST')


        if inp_costo_real:
            header.append('COSTO_REAL')
            
        if inp_fact_estimado:
            header.append('FACT_EST')
            
        if inp_fact_real:
            header.append('FACT_REAL')
            
        if inp_fact_fact:
            header.append('FACT_FAC')
        
        
        if inp_fact_fact:
            header.append('PAGINA')

            
            

        if inp_sub_division:
            header.append('SUB_DIVI')
            header.append('LEYESUBD')
        
        
        if inp_categoria:
            header.append('CATEGORIA')
            header.append('LEYENDA')
        
            
        if inp_segmento:
            header.append('SEGMENTO')
            header.append('LEY_SEG')
        if inp_sub_linea:
            header.append('SUB_LINEA')
            header.append('LEYESUBL')
        
        if inp_tipo_de_subl:
            header.append('TIPO_SUBL') #Encabezado Excel
            header.append('LEY_TSLIN')
        if inp_linea:
            header.append('LINEA') #Encabezado Excel
            header.append('LEY_LIN')
        if inp_color:
            header.append('DET_COLOR')
            header.append('LEY_COLOR')
        if inp_talle_tamano:
            header.append('TALLE')    
        if inp_material_tela:
            header.append('MATERIAL')
            header.append('LEY_MATE')
        if inp_caracterist:
            header.append('CARACTERIS')
            header.append('LEY_CARA')  
        if inp_coleccion:
            header.append('COLECCION')
            header.append('LEY_COLE')
        if inp_punto_de_precio:
            header.append('PTO_PRECIO')
            header.append('LEY_PTOPRE')
        if inp_packaging:
            header.append('PACKAGING')
            header.append('LEY_PACK')
        if inp_envase_do_crit:
            header.append('ENVASE_2DO')
            header.append('LEY_ENV2')
        if inp_sexo:
            header.append('SEXO')
            header.append('LEY_SEXO')
        if inp_target:
            header.append('TARGET')
            header.append('LEY_TARG')
        
        if inp_procedencia:
            header.append('PROC')
            header.append('LEYEPRO')
        if inp_unid_estim:
            header.append('UNID_EST')
        if inp_unid_vendidas:   
            header.append('UNIDADES')
        if inp_unid_fact:
            header.append('UNID_FAC')
        if inp_consignacion:
            header.append('CONSIG')
        if inp_cabecera:
            header.append('CABECERA')
        if inp_coeficiente:
            header.append('COEFICIE')
        if inp_empresa:
            header.append('EMPRESA')
        if inp_multi_empresa:
            header.append('MUL_EMP')
        if inp_grupo_fabric:
            header.append('GRUPO_FABR')
            header.append('LEY_FABR')      
        if inp_elaboracion:
            header.append('ELABORAC')
            header.append('LEY_ELAB')
        if inp_canal:
            header.append('CANAL')
            header.append('LEY_CNL')
        if inp_forma_pt:
            header.append('FORMA PT')
            header.append('LEY_FOR')
        if inp_cod_medida:
            header.append('COD_MEDI')
            header.append('LEY_MED')
        if inp_peso:
            header.append('PESO')    
        if inp_alto:
            header.append('ALTO')     
        if inp_largo:
            header.append('LARGO')    
        if inp_ancho:
            header.append('ANCHO')  
        if inp_volumen:
            header.append('VOLUMEN')
        if inp_cuotas:
            header.append('CUOTAS')
        if inp_cond_compra:
            header.append('CON_COMPRA')
        
        if inp_ord_media_est:  
            header.append('OM_EST')
        if inp_ord_media_real:
            header.append('OM_REAL')
        if inp_uxp_tag:
            header.append('UXP_TAG')     
            
        if inp_unid_tag:
            header.append('UNID_TAG')   
    
        
        if inp_pedidos_estm:
            header.append('PED_ESTIM')
        if inp_pedidos_reales:
            header.append('PED_REALES')
            
        if inp_unid_estim and inp_costo_estimado:
            header.append('COS_ESTOT')
            
        if inp_costo_real and inp_unid_vendidas:
            header.append('COS_REATOT')
        

        

   
       

   


            
        
           
        # row = [
            #         'CAMP',  listo
            #         'ANO',   listo  
            #         'CODIGON', listo     
            #         'DESCRIP', listo    
            #         'DIVISION', listo    
            #         'UXP', listo    
            #         'UXP_REAL', listo    
            #         'UXP_FAC', listo    
            #         'TIPO_OF', listo      
            #         'LEYEOFE', listo    
            #         'PR_OFERTA', listo          
            #         'PR_NORMAL', listo         
            #         'MAR_EST', listo    
            #         'MAR_REAL', listo    
            #         'COSTO_EST', listo    
            #         'TIPO_EST', listo
            #         'COSTO_REAL', listo
            #         'FACT_EST', listo
            #         'FACT_REAL', listo
            #         'FACT_FAC', listo
            #         'PAGINA',  listo
            #         'SUB_DIVI', listo
            #         'LEYESUBD', listo 
            #         'CATEGORIA', listo
            #         'LEYENDA', listo
            #         'SEGMENTO', listo
            #         'LEY_SEG',  -------> Falta tabla L_SEGMTO toma el dato del campo ---> ley_seg || LISTO
            #         'SUB_LINEA', listo
            #         'LEYESUBL', listo
            #         'TIPO_SUBL', listo 
            #         'LEY_TSLIN',-------> Falta tabla L_TIPOSB toma el dato del campo ---> LEY_TSLIN
            #         'LINEA', listo 
            #         'LEY_LIN',  -------> Falta tabla l_linea  toma el dato del campo ---> leyenda se renombra ley_lin LEYENDAS.CLAVE_CAMP = 3
            #         'DET_COLOR', listo
            #         'LEY_COLOR',-------> Falta tabla L_COLOR  toma el dato del campo --->	Alias de LEYENDAS.leyenda donde clave_camp=6
            #         'TALLE', listo 
            #         'MATERIAL', listo
            #         'LEY_MATE', ------->Falta tabla L_MATE  toma el dato del campo  LEY_MATE --->	Alias de LEYENDAS.leyenda donde clave_camp=10
            #         'CARACTERIS',listo
            #         'LEY_CARA', ------->Falta tabla L_CARAC  toma el dato del campo  LEY_CARAC  --->	Alias de LEYENDAS.leyenda donde clave_camp=15
            #         'COLECCION',listo
            #         'LEY_COLE',------->Falta tabla L_COLE  toma el dato del campo  LEY_COLE  --->	Alias de LEYENDAS.leyenda donde clave_camp=8
            #         'PTO_PRECIO', listo
            #         'LEY_PTOPRE',------->Falta tabla L_PTOPRE  toma el dato del campo  LEY_PTOPRE  --->	Alias de LEYENDAS.leyenda donde clave_camp=14
            #         'PACKAGING',listo
            #         'LEY_PACK',listo
            #         'ENVASE_2DO', listo
            #         'LEY_ENV2',listo
            #         'SEXO',listo
            #         'LEY_SEXO', ------->Falta tabla L_SEXO  toma el dato del campo  LEY_SEXO  --->	Alias de LEYENDAS.LEYENDA donde clave_camp=5
            #         'TARGET',listo
            #         'LEY_TARG', ------->Falta tabla L_TARG  toma el dato del campo  LEY_SEXO  --->	Alias de LEYENDAS.LEYENDA donde clave_camp=11
            #         'PROC', listo
            #         'LEYEPRO', ------->Falta tabla L_EPROV  toma el dato del campo  LEYEPRO  --->	Alias de LEYENDAS.LEYENDA donde clave_camp=6
            #         'UNID_EST',listo
            #         'UNIDADES' listo
            #         'UNID_FAC',listo
            #         'CONSIG', listo
            #         'CABECERA', listo
            #         'COEFICIE', listo
            #         'EMPRESA',listo
            #         'MUL_EMP',listo
            #         'CODIGO_MK',------->Falta tabla GCMK  toma el dato del campo codigo_mk
            #         'GRUPO_FABR',listo
            #         'LEY_FABR',-------> Falta tabla L_FABRICA toma el dato del campo LEY_FABR
            #         'ELABORAC',listo
            #         'LEY_ELAB',-------> Falta tabla L_ELABORAC toma el dato del campo LEY_ELAB
            #         'ESTADO', -------> Falta tabla L_ESTADO toma el dato del campo LEY_ESTAD
            #         'CMP_ESTA', -------> Falta tabla L_ESTADO toma el dato del campo LEY_ESTAD agregando la condición CAMPO = 14 AND CLAVE = DESCRIPC.ESTADO.
            #         'CANAL', listo
            #         'LEY_CNL', -------> Falta tabla L_CANAL toma el dato del campo LEY_CNL
            #         'FORMA_PT',listo
            #         'LEY_FOR', -------> Falta tabla L_FORMULA toma el dato del campo LEY_FOR.
            #         'COD_MEDI',listo
            #         'LEY_MED',-------> Falta tabla L_MEDIDA toma el dato del campo LEY_MED.
            #         'PESO',listo
            #         'ALTO',listo
            #         'LARGO',listo
            #         'ANCHO',listo
            #         'VOLUMEN',listo
            #         'CUOTAS',listo
            #         'CON_COMPRA',listo
            #         'OM_EST',listo
            #         'OM_REAL',listo
            #         'UXP_TAG',listo
            #         'UNID_TAG',listo
            #         'PED_EST',listo
            #         'PED_REAL',list
            #         'COS_ESTOT', listo
            #         'COS_REATOT',
            #     ]



        writer.writerow(header)


        if 'CODIGON' in df_merged.columns:
            df_merged.sort_values(by=['CODIGON', 'CAMP'], ascending=[True, True], inplace=True)

        print("Columnas reales en df_cmp:", df_cmp.columns.tolist())
        # Filas
        for _, row in df_merged.iterrows():
            fila = []

                

            fila.append(int(row['CAMP']) if pd.notna(row['CAMP']) else '')
            fila.append(int(row['ANO']) if pd.notna(row['ANO']) else '')

            if inp_codigo:
                fila.append(int(row['CODIGON']) if pd.notna(row['CODIGON']) else '')
            if inp_descripcion:
                fila.append(str(row['DESCRIP']) if pd.notna(row['DESCRIP']) else '')
            if inp_division:
                fila.append(str(row['DIVISION']) if pd.notna(row['DIVISION']) else '')
            
            if inp_uxp_estimado:
                fila.append(row['UXP'] if pd.notna(row['UXP']) else '')
            if inp_uxp_real:
                fila.append(row['UXP_REAL'] if pd.notna(row['UXP_REAL']) else '')
            if inp_uxp_facturado:
                fila.append(row['UXP_FAC'] if pd.notna(row['UXP_FAC']) else '')
            
            if inp_tipo_de_oferta:
                fila.append(str(row['TIPO_OF']) if pd.notna(row['TIPO_OF']) else '')
                fila.append(str(row['LEYEOFE']) if pd.notna(row['LEYEOFE']) else '')

            
            if inp_precio_de_oferta:
                fila.append(str(row['PR_OFERTA']) if pd.notna(row['PR_OFERTA']) else '')
            if inp_precio_normal:
                fila.append(str(row['PR_NORMAL']) if pd.notna(row['PR_NORMAL']) else '')

            if inp_margen_estimado:
                fila.append(row['MAR_EST'] if pd.notna(row['MAR_EST']) else '')
            if inp_margen_real:
                fila.append(row['MAR_REAL'] if pd.notna(row['MAR_REAL']) else '')

            if inp_costo_estimado:
                fila.append(row['COSTO_EST'] if pd.notna(row['COSTO_EST']) else '')
                fila.append(row['TIPO_EST'] if pd.notna(row['TIPO_EST']) else '')


            if inp_costo_real:
                fila.append(row['COSTO_REAL'] if pd.notna(row['COSTO_REAL']) else '')
            if inp_fact_estimado:
                fila.append(row['FACT_EST'] if pd.notna(row['FACT_EST']) else '')
            if inp_fact_real:
                fila.append(row['FACT_REAL'] if pd.notna(row['FACT_REAL']) else '')
            if inp_fact_fact:
                fila.append(row['FACT_FAC'] if pd.notna(row['FACT_FAC']) else '')
            
            

            if inp_fact_fact:
                fila.append(row['PAGINA'] if pd.notna(row['PAGINA']) else '')
            





            if inp_sub_division:
                fila.append(str(row['SUB_DIVI']) if pd.notna(row['SUB_DIVI']) else '')
                fila.append(str(row['LEYESUBD']) if pd.notna(row['LEYESUBD']) else '')
                
            if inp_categoria:
                fila.append(str(row['CATEGORIA']) if pd.notna(row['CATEGORIA']) else '')
                fila.append(str(row['LEYENDA']) if pd.notna(row['LEYENDA']) else '')
            if inp_segmento:
                fila.append(str(row['SEGMENTO']) if pd.notna(row['SEGMENTO']) else '')
                fila.append(str(row['LEY_SEG']) if pd.notna(row['LEY_SEG']) else '')
            if inp_sub_linea:
                fila.append(str(row['SUB_LINEA']) if pd.notna(row['SUB_LINEA']) else '')   
                fila.append(str(row['LEYESUBL']) if pd.notna(row['LEYESUBL']) else '')
            if inp_tipo_de_subl:
                fila.append(str(row['TIPO_SUBL']) if pd.notna(row['TIPO_SUBL']) else '')
                fila.append(str(row['LEY_TSLIN']) if pd.notna(row['LEY_TSLIN']) else '')
            if inp_linea:
                fila.append(str(row['LINEA']) if pd.notna(row['LINEA']) else '')  
                fila.append(str(row['LEY_LIN']) if pd.notna(row['LEY_LIN']) else '') 
            if inp_color:
                fila.append(str(row['DET_COLOR']) if pd.notna(row['DET_COLOR']) else '')
                fila.append(str(row['LEY_COLOR']) if pd.notna(row['LEY_COLOR']) else '') 
            if inp_talle_tamano:
                fila.append(str(row['TALLE']) if pd.notna(row['TALLE']) else '')
            if inp_material_tela:
                fila.append(str(row['MATERIAL']) if pd.notna(row['MATERIAL']) else '')
                fila.append(str(row['LEY_MATE']) if pd.notna(row['LEY_MATE']) else '')   
            if inp_caracterist:
                fila.append(str(row['CARACTERIS']) if pd.notna(row['CARACTERIS']) else '')
                fila.append(str(row['LEY_CARA']) if pd.notna(row['LEY_CARA']) else '')   
            if inp_coleccion:
                fila.append(str(row['COLECCION']) if pd.notna(row['COLECCION']) else '')
                fila.append(str(row['LEY_COLE']) if pd.notna(row['LEY_COLE']) else '')
            if inp_punto_de_precio:
                fila.append(str(row['PTO_PRECIO']) if pd.notna(row['PTO_PRECIO']) else '')
                fila.append(str(row['LEY_PTOPRE']) if pd.notna(row['LEY_PTOPRE']) else '')
            if inp_packaging:
                fila.append(str(row['PACKAGING']) if pd.notna(row['PACKAGING']) else '')       
                fila.append(str(row['LEYPACK']) if pd.notna(row['LEYPACK']) else '') 
            if inp_envase_do_crit:
                fila.append(str(row['ENVASE_2DO']) if pd.notna(row['ENVASE_2DO']) else '')
                fila.append(str(row['LEYENV2']) if pd.notna(row['LEYENV2']) else '')
            if inp_sexo:
                fila.append(str(row['SEXO']) if pd.notna(row['SEXO']) else '')
                fila.append(str(row['LEY_SEXO']) if pd.notna(row['LEY_SEXO']) else '')
            if inp_target:
                fila.append(str(row['TARGET']) if pd.notna(row['TARGET']) else '')
                fila.append(str(row['LEY_TARG']) if pd.notna(row['LEY_TARG']) else '')
            if inp_procedencia:
                fila.append(str(row['PROC']) if pd.notna(row['PROC']) else '')
                fila.append(str(row['LEYEPRO']) if pd.notna(row['LEYEPRO']) else '')
            if inp_unid_estim:
                fila.append(row['UNID_EST'] if pd.notna(row['UNID_EST']) else '')
            if inp_unid_vendidas:
                fila.append(row['UNIDADES'] if pd.notna(row['UNIDADES']) else '') 
            if inp_unid_fact:
                fila.append(row['UNID_FAC'] if pd.notna(row['UNID_FAC']) else '')   
            if inp_consignacion:
                fila.append(row['CONSIG'] if pd.notna(row['CONSIG']) else '')     
            if inp_cabecera:
                fila.append(row['CABECERA'] if pd.notna(row['CABECERA']) else '')
            if inp_coeficiente:
                fila.append(row['COEFICIE'] if pd.notna(row['COEFICIE']) else '')  
            if inp_empresa:
                fila.append(row['EMPRESA'] if pd.notna(row['EMPRESA']) else '')
            if inp_multi_empresa:
                fila.append(row['MUL_EMP'] if pd.notna(row['MUL_EMP']) else '')
            if inp_grupo_fabric:
                fila.append(row['GRUPO_FABR'] if pd.notna(row['GRUPO_FABR']) else '')
                fila.append(row['LEY_FABR'] if pd.notna(row['LEY_FABR']) else '')           
            if inp_elaboracion:
                fila.append(row['ELABORAC'] if pd.notna(row['ELABORAC']) else '')
                fila.append(row['LEY_ELAB'] if pd.notna(row['LEY_ELAB']) else '')
            if inp_canal:
                fila.append(row['CANAL'] if pd.notna(row['CANAL']) else '')
                fila.append(row['LEY_CNL'] if pd.notna(row['LEY_CNL']) else '')
            if inp_forma_pt:
                fila.append(str(row['FORMA_PT']) if pd.notna(row['FORMA_PT']) else '')
                fila.append(str(row['LEY_FOR']) if pd.notna(row['LEY_FOR']) else '')
            if inp_cod_medida:
                fila.append(row['COD_MEDI'] if pd.notna(row['COD_MEDI']) else '')
                fila.append(row['LEY_MED'] if pd.notna(row['LEY_MED']) else '')       
            if inp_peso:
                fila.append(row['PESO'] if pd.notna(row['PESO']) else '')
            if inp_alto:
                fila.append(row['ALTO'] if pd.notna(row['ALTO']) else '')     
            if inp_largo:
                fila.append(row['LARGO'] if pd.notna(row['LARGO']) else '')
            if inp_ancho:
                fila.append(row['ANCHO'] if pd.notna(row['ANCHO']) else '')
            if inp_volumen:
                fila.append(row['VOLUMEN'] if pd.notna(row['VOLUMEN']) else '')
            if inp_cuotas:
                fila.append(row['CUOTAS'] if pd.notna(row['CUOTAS']) else '')
            if inp_cond_compra:
                fila.append(row['CON_COMPRA'] if pd.notna(row['CON_COMPRA']) else '')
                
                
                
                
                
            # OM_EST = FACT_EST / PED_EST
            # OM_EST = FACT_EST / PED_EST
            # OM_EST = FACT_EST / PED_EST
            # OM_EST = FACT_EST / PED_EST
            if inp_ord_media_est:
                try:
                    fact_est = float(str(row['FACT_EST']).replace(',', '.'))
                    ped_est = float(row['PED_ESTIM'])
                    if ped_est != 0:
                        om_est = fact_est / ped_est
                    else:
                        om_est = ''
                except (ValueError, TypeError):
                    om_est = ''
                
                fila.append(redondear_decimal_dos(om_est))

            # OM_REAL = FACT_REAL / PED_REAL
            if inp_ord_media_real:
                try:
                    fact_real = float(str(row['FACT_REAL']).replace(',', '.'))
                    ped_real = float(row['PED_REALES'])
                    if ped_real != 0:
                        om_real = fact_real / ped_real
                    else:
                        om_real = ''
                except (ValueError, TypeError):
                    om_real = ''
                
                fila.append(redondear_decimal_dos(om_real))

            if inp_uxp_tag:
                fila.append(str(row['UXP_TAG']) if pd.notna(row['UXP_TAG']) else '')
            
            
            
            #if inp_unid_tag:
                #fila.append(str(row['UNID_TAG']) if pd.notna(row['UNID_TAG']) else '')
            
            #if XXXX:
            #    fila.append(row[''] if pd.notna(row['']) else '') 
            
            
            if inp_unid_tag:
                try:
                    # Convertir las columnas a float (asegurarse de que sean numéricas)
                    unid_tag = float(str(row['UNID_TAG']).replace(',', '.')) if pd.notna(row['UNID_TAG']) else 0
                    uxp_tag  = float(str(row['UXP_TAG']).replace(',', '.')) if pd.notna(row['UXP_TAG']) else 0

                    # Realizar la multiplicación
                    unid_tag_resultado = unid_tag * uxp_tag

                    # Redondear a 4 decimales con coma decimal
                    unid_tag_redondeado = redondear_decimal_cuatro(unid_tag_resultado)

                    # Verificar si la multiplicación es válida y agregar el resultado
                    fila.append(unid_tag_redondeado if unid_tag_redondeado else '')
                except (ValueError, TypeError):
                    # Si ocurre un error al convertir o multiplicar, asignar un valor vacío
                    fila.append('')
                # 2 2017 pedidos tag *27289  3291,0534  el orden es asi, necesito hacer el truncate de la funcion de redondeo porque viendo este ejemplo me lo redondeo a 3292 

                print(redondear_decimal_cuatro(123.456789))  # "123,4568"
                print(redondear_decimal_cuatro(10.5))  
                
            
            if inp_pedidos_estm:
                fila.append(str(row['PED_ESTIM']) if pd.notna(row['PED_ESTIM']) else '')
            if inp_pedidos_reales:
                fila.append(str(row['PED_REALES']) if pd.notna(row['PED_REALES']) else '')

            if inp_unid_estim and inp_costo_estimado:
                fila.append(str(row['COS_ESTOT']) if pd.notna(row['COS_ESTOT']) else '')

            if inp_costo_real and inp_unid_vendidas:
                fila.append(str(row['COS_REATOT']) if pd.notna(row['COS_REATOT']) else '')
            


            writer.writerow(fila)


        return response

    except Exception as e:
        return JsonResponse({'error': f'Error interno al generar el archivo: {str(e)}'}, status=500)










