load("dataset2.rdata")
load("Temperatura_Murcia.Rdata")
load("paro.rdata")
load("g1.Rdata")
load("g2.Rdata")
load("g3.Rdata")
load("g4.Rdata")
load("g5.Rdata")
load("g6.Rdata")
load("g7.Rdata")
####### RADAR CHART: COMERCIO

fifita_comercio<-function(cod,fecha1,renta,edad,sexo){
  

z<-datos2
if(renta!="todas" | edad!="todos" | sexo!="todos"){
z<-z%>%dplyr::filter(NUM_OP==1)}
  
  
if(renta=="baja"){z<-z%>%dplyr::filter(PROP_R_BAJA==1)
} 
if(renta=="media"){z<-z%>%dplyr::filter(PROP_R_MEDIA==1)
  }
if(renta=="alta"){z<-z%>%dplyr::filter(PROP_R_ALTA==1)
  }

if(edad=="jovenes"){z<-z%>%dplyr::filter(PROP_JOVEN==1)
} 
if(edad=="adultos"){z<-z%>%dplyr::filter(PROP_ADULTO==1)
}
if(edad=="jubilados"){z<-z%>%dplyr::filter(PROP_PENSIONISTA==1)
}

if(sexo=="hombres"){z<-z%>%dplyr::filter(HOMBRES==1)
} 
if(sexo=="mujeres"){z<-z%>%dplyr::filter(MUJERES==1)
}

  
  
codes<-cod
a<-z%>%dplyr::filter(FECHA>=as.Date(fecha1[1]) & FECHA<=as.Date(fecha1[2]))
a<-a%>%dplyr::filter(CP_COMERCIO%in% codes )%>%dplyr::select(CP_COMERCIO,SECTOR,IMPORTE,NUM_OP)%>%dplyr::group_by(SECTOR,CP_COMERCIO)%>%dplyr::summarise(IMPORTE=mean(IMPORTE),NUM_OP=mean(NUM_OP))
a<-a%>%dplyr::mutate(IMPORTE=IMPORTE/NUM_OP)

longitudes<-vector()
for(i in 1:length(codes)){
                          temp<-a%>%dplyr::filter(CP_COMERCIO==codes[i])
                          longitudes[i]<-length(unique(temp$SECTOR))
}
indice<-which.max(longitudes)                         
codes<-c(codes[indice],codes[!codes%in%codes[indice]])
df<-as.data.frame(a%>%dplyr::filter(CP_COMERCIO==codes[1]))
resto<-codes[!codes%in% codes[1]]

for(i in resto){
  nuevo<-as.data.frame(a%>%dplyr::filter(CP_COMERCIO==i))
  df<-left_join(df,nuevo,by="SECTOR")
}


for(i in names(df)[stringr::str_detect(names(df),"^CP_COMERCIO")]){
  temp<-unique(df[i])[1,]
  df[i]<-rep(temp,nrow(df[i]))
  
}

df[is.na(df)]<-0

series<-list()
for(i in 1:length(codes)){
                          temp<-a%>%dplyr::filter(CP_COMERCIO==codes[i])
                          
                          series[[i]]<-list(
                                        name = codes[i],
                                        data = df[,i*3],
                                        pointPlacement = "on"
                                      )
                         
                          
}
  
############################################ gráficas ############
if(length(codes)==1){  
a<-highchart() %>% 
  hc_chart( polar = TRUE, type = "line") %>% 
  hc_title(text = "") %>% 
  hc_xAxis(categories = df$SECTOR,
           tickmarkPlacement = "on",
           lineWidth = 0) %>% 
  hc_yAxis(gridLineInterpolation = "polygon",
           lineWidth = 0,
           min = 0) %>% 
  hc_series(
   series[[1]]
  )%>%
  hc_tooltip(valueDecimals = 2,
             pointFormat = "Ingesos promedio por compra: {point.y} \u20ac <br> ")%>% 
  hc_title(text = "Ingreso promedio por codigo postal de comercio", style = list(color = "black"))}


if(length(codes)==2){  
a<-  highchart() %>% 
    hc_chart( polar = TRUE, type = "line") %>% 
    hc_title(text = "") %>% 
    hc_xAxis(categories = df$SECTOR,
             tickmarkPlacement = "on",
             lineWidth = 0) %>% 
    hc_yAxis(gridLineInterpolation = "polygon",
             lineWidth = 0,
             min = 0) %>% 
    hc_series(
      series[[1]],series[[2]]
    )%>%
  hc_tooltip(valueDecimals = 2,
             pointFormat = "Ingesos promedio por compra: {point.y} \u20ac <br> ")%>% 
  hc_title(text = "Ingreso promedio por codigo postal de comercio", style = list(color = "black"))}

if(length(codes)==3){  
a<-highchart() %>% 
    hc_chart( polar = TRUE, type = "line") %>% 
    hc_title(text = "") %>% 
    hc_xAxis(categories = df$SECTOR,
             tickmarkPlacement = "on",
             lineWidth = 0) %>% 
    hc_yAxis(gridLineInterpolation = "polygon",
             lineWidth = 0,
             min = 0) %>% 
    hc_series(
      series[[1]],series[[2]],series[[3]]
    )%>%
  hc_tooltip(valueDecimals = 2,
             pointFormat = "Ingesos promedio por compra: {point.y} \u20ac <br> ")%>% 
  hc_title(text = "Ingreso promedio por codigo postal de comercio", style = list(color = "black"))}

if(length(codes)==4){  
a<-  highchart() %>% 
    hc_chart( polar = TRUE, type = "line") %>% 
    hc_title(text = "") %>% 
    hc_xAxis(categories = df$SECTOR,
             tickmarkPlacement = "on",
             lineWidth = 0) %>% 
    hc_yAxis(gridLineInterpolation = "polygon",
             lineWidth = 0,
             min = 0) %>% 
    hc_series(
      series[[1]],series[[2]],series[[3]],series[[4]]
    )%>%
  hc_tooltip(valueDecimals = 2,
             pointFormat = "Ingesos promedio por compra: {point.y} \u20ac <br> ")%>% 
  hc_title(text = "Ingreso promedio por codigo postal de comercio", style = list(color = "black"))}

if(length(codes)==5){  
a<-  highchart() %>% 
    hc_chart( polar = TRUE, type = "line") %>% 
    hc_title(text = "") %>% 
    hc_xAxis(categories = df$SECTOR,
             tickmarkPlacement = "on",
             lineWidth = 0) %>% 
    hc_yAxis(gridLineInterpolation = "polygon",
             lineWidth = 0,
             min = 0) %>% 
    hc_series(
      series[[1]],series[[2]],series[[3]],series[[4]],series[[5]]
    )%>%
  hc_tooltip(valueDecimals = 2,
             pointFormat = "Ingesos promedio por compra: {point.y} \u20ac <br> ")%>% 
  hc_title(text = "Ingreso promedio por codigo postal de comercio", style = list(color = "black"))}
a
#################################################################################
}

##=======================================================================================================================================#####


####### RADAR CHART: CLIENTES

fifita_cliente<-function(cod,fecha1,renta,edad,sexo){
  
  z<-datos2
  if(renta!="todas" | edad!="todos" | sexo!="todos"){
    z<-z%>%dplyr::filter(NUM_OP==1)}
  
  
  if(renta=="baja"){z<-z%>%dplyr::filter(PROP_R_BAJA==1)
  } 
  if(renta=="media"){z<-z%>%dplyr::filter(PROP_R_MEDIA==1)
  }
  if(renta=="alta"){z<-z%>%dplyr::filter(PROP_R_ALTA==1)
  }
  
  
  if(edad=="jovenes"){z<-z%>%dplyr::filter(PROP_JOVEN==1)
  } 
  if(edad=="adultos"){z<-z%>%dplyr::filter(PROP_ADULTO==1)
  }
  if(edad=="jubilados"){z<-z%>%dplyr::filter(PROP_PENSIONISTA==1)
  }
 
  
  if(sexo=="hombres"){z<-z%>%dplyr::filter(HOMBRES==1)
  } 
  if(sexo=="mujeres"){z<-z%>%dplyr::filter(MUJERES==1)
  }
  
  
  
  codes<-cod
  a<-z%>%dplyr::filter(FECHA>=as.Date(fecha1[1]) & FECHA<=as.Date(fecha1[2]))
  a<-a%>%dplyr::filter(CP_CLIENTE%in% codes)%>%dplyr::select(CP_CLIENTE,SECTOR,IMPORTE,NUM_OP)%>%dplyr::group_by(SECTOR,CP_CLIENTE)%>%dplyr::summarise_all(funs(mean))
  a<-a%>%dplyr::mutate(IMPORTE=IMPORTE/NUM_OP)
  
  longitudes<-vector()
  for(i in 1:length(codes)){
    temp<-a%>%dplyr::filter(CP_CLIENTE==codes[i])
    longitudes[i]<-length(unique(temp$SECTOR))
  }
  indice<-which.max(longitudes)                         
  codes<-c(codes[indice],codes[!codes%in%codes[indice]])
  df<-as.data.frame(a%>%dplyr::filter(CP_CLIENTE==codes[1]))
  resto<-codes[!codes%in% codes[1]]
  
  for(i in resto){
    nuevo<-as.data.frame(a%>%dplyr::filter(CP_CLIENTE==i))
    df<-left_join(df,nuevo,by="SECTOR")
  }
  
  
  for(i in names(df)[stringr::str_detect(names(df),"^CP_CLIENTE")]){
    temp<-unique(df[i])[1,]
    df[i]<-rep(temp,nrow(df[i]))
    
  }
  
  df[is.na(df)]<-0
  
  series<-list()
  for(i in 1:length(codes)){
    temp<-a%>%dplyr::filter(CP_CLIENTE==codes[i])
    
    series[[i]]<-list(
      name = codes[i],
      data = df[,i*3],
      pointPlacement = "on"
    )
    
    
  }
  
  ############################################ gráficas ############
  if(length(codes)==1){  
    a<-highchart() %>% 
      hc_chart( polar = TRUE, type = "line") %>% 
      hc_title(text = "") %>% 
      hc_xAxis(categories = df$SECTOR,
               tickmarkPlacement = "on",
               lineWidth = 0) %>% 
      hc_yAxis(gridLineInterpolation = "polygon",
               lineWidth = 0,
               min = 0) %>% 
      hc_series(
        series[[1]]
      )%>%
      hc_tooltip(valueDecimals = 2,
                 pointFormat = "Gastos promedio por compra: {point.y} \u20ac <br> ")%>% 
      hc_title(text = "Gasto promedio por codigo postal de cliente", style = list(color = "black"))}
  
  if(length(codes)==2){  
    a<-  highchart() %>% 
      hc_chart( polar = TRUE, type = "line") %>% 
      hc_title(text = "") %>% 
      hc_xAxis(categories = df$SECTOR,
               tickmarkPlacement = "on",
               lineWidth = 0) %>% 
      hc_yAxis(gridLineInterpolation = "polygon",
               lineWidth = 0,
               min = 0) %>% 
      hc_series(
        series[[1]],series[[2]]
      )%>%
      hc_tooltip(valueDecimals = 2,
                 pointFormat = "Gastos promedio por compra: {point.y} \u20ac <br> ")%>% 
      hc_title(text = "Gasto promedio por codigo postal de cliente", style = list(color = "black"))}
  
  if(length(codes)==3){  
    a<-highchart() %>% 
      hc_chart( polar = TRUE, type = "line") %>% 
      hc_title(text = "") %>% 
      hc_xAxis(categories = df$SECTOR,
               tickmarkPlacement = "on",
               lineWidth = 0) %>% 
      hc_yAxis(gridLineInterpolation = "polygon",
               lineWidth = 0,
               min = 0) %>% 
      hc_series(
        series[[1]],series[[2]],series[[3]]
      )%>%
      hc_tooltip(valueDecimals = 2,
                 pointFormat = "Gastos promedio por compra: {point.y} \u20ac <br> ")%>% 
      hc_title(text = "Gasto promedio por codigo postal de cliente", style = list(color = "black"))}
  
  if(length(codes)==4){  
    a<-  highchart() %>% 
      hc_chart( polar = TRUE, type = "line") %>% 
      hc_title(text = "") %>% 
      hc_xAxis(categories = df$SECTOR,
               tickmarkPlacement = "on",
               lineWidth = 0) %>% 
      hc_yAxis(gridLineInterpolation = "polygon",
               lineWidth = 0,
               min = 0) %>% 
      hc_series(
        series[[1]],series[[2]],series[[3]],series[[4]]
      )%>%
      hc_tooltip(valueDecimals = 2,
                 pointFormat = "Gastos promedio por compra: {point.y} \u20ac <br> ")%>% 
      hc_title(text = "Gasto promedio por codigo postal de cliente", style = list(color = "black"))}
  
  if(length(codes)==5){  
    a<-  highchart() %>% 
      hc_chart( polar = TRUE, type = "line") %>% 
      hc_title(text = "") %>% 
      hc_xAxis(categories = df$SECTOR,
               tickmarkPlacement = "on",
               lineWidth = 0) %>% 
      hc_yAxis(gridLineInterpolation = "polygon",
               lineWidth = 0,
               min = 0) %>% 
      hc_series(
        series[[1]],series[[2]],series[[3]],series[[4]],series[[5]]
      )%>%
      hc_tooltip(valueDecimals = 2,
                 pointFormat = "Gastos promedio por compra: {point.y} \u20ac <br> ") %>% 
      hc_title(text = "Gasto promedio por codigo postal de cliente", style = list(color = "black"))}
  a

}
####=====================================================================================================================================#####


####### BAR RADAR 2

BarRadar2<-function(cod,fecha1,renta,edad,sexo){
 
   z<-datos2
  if(renta!="todas" | edad!="todos" | sexo!="todos"){
    z<-z%>%dplyr::filter(NUM_OP==1)}
  
  
  if(renta=="baja"){z<-z%>%filter(PROP_R_BAJA==1)
  } 
  if(renta=="media"){z<-z%>%filter(PROP_R_MEDIA==1)
  }
  if(renta=="alta"){z<-z%>%filter(PROP_R_ALTA==1)
  }
  
  
  if(edad=="jovenes"){z<-z%>%filter(PROP_JOVEN==1)
  } 
  if(edad=="adultos"){z<-z%>%filter(PROP_ADULTO==1)
  }
  if(edad=="jubilados"){z<-z%>%filter(PROP_PENSIONISTA==1)
  }
  
  
  if(sexo=="hombres"){z<-z%>%filter(HOMBRES==1)
  } 
  if(sexo=="mujeres"){z<-z%>%filter(MUJERES==1)
  }
  
  
  

sectores<-c("ALIMENTACION","AUTO","BELLEZA","HIPERMERCADOS","HOGAR","MODA Y COMPLEMENTOS","OCIO Y TIEMPO LIBRE","OTROS" ,"RESTAURACION","SALUD","TECNOLOGIA")           
  
codes<-cod
a<-z%>%dplyr::filter(FECHA>=as.Date(fecha1[1]) & FECHA<=as.Date(fecha1[2]))
a<-a%>%dplyr::filter(CP_CLIENTE%in% cod)%>%dplyr::select(CP_CLIENTE,SECTOR,IMPORTE,NUM_OP)%>%dplyr::group_by(SECTOR,CP_CLIENTE)%>%dplyr::summarise_all(funs(sum))

############# CONSTRUCCION CP CLIENTES ####################
longitudes<-vector()
for(i in 1:length(codes)){
  temp<-a%>%dplyr::filter(CP_CLIENTE==codes[i])
  longitudes[i]<-length(unique(temp$SECTOR))
}
indice<-which.max(longitudes)                         
codes<-c(codes[indice],codes[!codes%in%codes[indice]])
df<-as.data.frame(a%>%dplyr::filter(CP_CLIENTE==codes[1]))
resto<-codes[!codes%in% codes[1]]




for(i in resto){
  nuevo<-as.data.frame(a%>%dplyr::filter(CP_CLIENTE==i))
  df<-left_join(df,nuevo,by="SECTOR")
}


for(i in names(df)[stringr::str_detect(names(df),"^CP_CLIENTE")]){
  temp<-unique(df[i])[1,]
  df[i]<-rep(temp,nrow(df[i]))
  
}

df[is.na(df)]<-0

series<-list()
for(i in 1:length(codes)){
  temp<-a%>%dplyr::filter(CP_CLIENTE==codes[i])
  
  series[[i]]<-list(
    CP_CLIENTE = paste0("CP CLIENTE:",codes[i]),
    ORDEN=as.numeric(codes[i]),
    UNION=as.factor(codes[i]),
    IMPORTE = df[,i*3],
    sector=df[,1],
    NUM_OP=df[,grep("^NUM_OP",names(df))[i]],
    pointPlacement = "on"
  )
  
  
}

b<-as.data.frame(as.data.frame(series[[1]]))
if(length(resto)>=1){
  for( i in 1:length(resto)){
    
    b<-as.data.frame(rbind(b,as.data.frame(series[[i+1]]))) 
  }  
}

names(b)<-c("CP_CLIENTE","ORDEN","UNION","IMPORTE","SECTOR","NUM_OP","pointPlacement") 
b<-b%>%dplyr::arrange(ORDEN)

################ COMERCIOS ###########################

a<-z%>%dplyr::filter(FECHA>=as.Date(fecha1[1]) & FECHA<=as.Date(fecha1[2]))
a<-a%>%dplyr::filter(CP_COMERCIO%in% cod)%>%dplyr::select(CP_COMERCIO,SECTOR,IMPORTE,NUM_OP)%>%group_by(SECTOR,CP_COMERCIO)%>%dplyr::summarise_all(funs(sum))


longitudes<-vector()
for(i in 1:length(codes)){
  temp<-a%>%filter(CP_COMERCIO==codes[i])
  longitudes[i]<-length(unique(temp$SECTOR))
}
indice<-which.max(longitudes)                         
codes<-c(codes[indice],codes[!codes%in%codes[indice]])
df<-as.data.frame(a%>%dplyr::filter(CP_COMERCIO==codes[1]))
resto<-codes[!codes%in% codes[1]]



#=============================================================================== NUEVO OJO VER QUE FUNCIONE BIEN ==============================================
SECTOR<-sectores[!sectores%in%unique(df$SECTOR)]
z<-as.data.frame(SECTOR)
z<-z%>%dplyr::mutate(CP_COMERCIO=rep(unique(df$CP_COMERCIO),nrow(z)),IMPORTE=rep(0,nrow(z)),NUM_OP=rep(0,nrow(z)))
df<-bind_rows(df,z)%>%dplyr::arrange(SECTOR)
#==============================================================================================================================================================

for(i in resto){
  nuevo<-as.data.frame(a%>%dplyr::filter(CP_COMERCIO==i))
  df<-left_join(df,nuevo,by="SECTOR")
}


for(i in names(df)[stringr::str_detect(names(df),"^CP_COMERCIO")]){
  temp<-unique(df[i])[1,]
  df[i]<-rep(temp,nrow(df[i]))
  
}

df[is.na(df)]<-0

series<-list()
for(i in 1:length(codes)){
  temp<-a%>%dplyr::filter(CP_COMERCIO==codes[i])
  
  series[[i]]<-list(
    CP_CLIENtE = paste0("CP COMERCIO:",codes[i]),
    ORDEN=as.numeric(codes[i]),
    UNION=as.factor(codes[i]),
    IMPORTE = df[,i*3],
    sector=df[,1],
    NUM_OP=df[,grep("^NUM_OP",names(df))[i]],
    pointPlacement = "on"
  )
  
  
}

c<-as.data.frame(as.data.frame(series[[1]]))
if(length(resto)>=1){
  for( i in 1:length(resto)){
    
    c<-as.data.frame(rbind(c,as.data.frame(series[[i+1]]))) 
  }  
}

names(c)<-c("CP_CLIENTE","ORDEN","UNION","IMPORTE","SECTOR","NUM_OP","pointPlacement")
c<-c%>%dplyr::arrange(ORDEN)





fin<-as.data.frame(rbind(c,b))







if(length(codes)==1){
a<-highchart() %>% 
  # Data
  hc_add_series(fin, "column", hcaes(x = as.factor(CP_CLIENTE), y =IMPORTE,group=SECTOR))%>% 
  hc_title(text = "Ingresos totales por codigo postal y sector.", style = list(color = "black")) %>%
  hc_xAxis(categories = unique(fin$CP_CLIENTE),plotBands = list(
    list(from = 0.5, to = JS("Infinity"), color = "rgb(225,225,225)",
         label = list(text = "")))) %>%
  hc_tooltip(valueDecimals = 2,
             pointFormat = "Sector:{point.SECTOR} <br>Gastos totales: {point.IMPORTE} \u20ac <br> Numero de operaciones: {point.NUM_OP}")%>%
  hc_plotOptions(series=list(allowPointSelect= FALSE,animation=list(duration=2000)))%>%
  hc_yAxis_multiples(list(title = list(text = "Ingresos Totales por CP Comercio y Sector")),
           list(title = list(text = "Gastos Totales por CP Cliente y Sector"), opposite = TRUE))  

}

if(length(codes)==2){
 a<- highchart() %>% 
    # Data
    hc_add_series(fin, "column", hcaes(x = as.factor(CP_CLIENTE), y =IMPORTE,group=SECTOR))%>% 
    hc_title(text = "Ingresos totales por codigo postal y sector.", style = list(color = "black")) %>%
    hc_xAxis(categories = unique(fin$CP_CLIENTE),plotBands = list(
      list(from = 1.5, to = JS("Infinity"), color = "rgb(225,225,225)",
           label = list(text = "")))) %>%
    hc_tooltip(valueDecimals = 2,
               pointFormat = "Sector:{point.SECTOR} <br>Gastos totales: {point.IMPORTE} \u20ac <br> Numero de operaciones: {point.NUM_OP}")%>%
    hc_plotOptions(series=list(allowPointSelect= FALSE,animation=list(duration=2000)))%>%
   hc_yAxis_multiples(list(title = list(text = "Ingresos Totales por CP Comercio y Sector")),
                      list(title = list(text = "Gastos Totales por CP Cliente y Sector"), opposite = TRUE))
}
if(length(codes)==3){
  a<-highchart() %>% 
    # Data
    hc_add_series(fin, "column", hcaes(x = as.factor(CP_CLIENTE), y =IMPORTE,group=SECTOR))%>% 
    hc_title(text = "Ingresos totales por codigo postal y sector.", style = list(color = "black")) %>%
    hc_xAxis(categories = unique(fin$CP_CLIENTE),plotBands = list(
      list(from = 2.5, to = JS("Infinity"), color = "rgb(225,225,225)",
           label = list(text = "")))) %>%
    hc_tooltip(valueDecimals = 2,
               pointFormat = "Sector:{point.SECTOR} <br>Gastos totales: {point.IMPORTE} \u20ac <br> Numero de operaciones: {point.NUM_OP}")%>%
    hc_plotOptions(series=list(allowPointSelect= FALSE,animation=list(duration=2000)))%>%
    hc_yAxis_multiples(list(title = list(text = "Ingresos Totales por CP Comercio y Sector")),
                       list(title = list(text = "Gastos Totales por CP Cliente y Sector"), opposite = TRUE))
}
a   


 
}
#####====================================================================================================================================#####


#######CLIMATOLOGIA

clima<-function(sectoricus){

temperatura<-temperatura%>%dplyr::filter(Date<=as.Date("2017-09-29"))
a<-xts(x=temperatura[,c(3)],order.by = temperatura$Date)
b<-xts(x=temperatura[,c(14)],order.by = temperatura$Date)

if(sectoricus=="todos"){
  importe_total<-datos2%>%dplyr::select(IMPORTE,FECHA)%>%dplyr::group_by(FECHA)%>%dplyr::summarise_all(funs(sum))
  c<-importe_total
  c<-xts(x=c[,c(2)],order.by = c$FECHA)
  
}
if(sectoricus!="todos"){
importe_total<-datos%>%dplyr::select(IMPORTE,FECHA,SECTOR)%>%dplyr::group_by(FECHA,SECTOR)%>%dplyr::summarise_all(funs(sum))
c<-importe_total%>%dplyr::filter(SECTOR==sectoricus)%>%dplyr::select(-SECTOR)
c<-xts(x=c[,c(2)],order.by = c$FECHA)}



highchart(type = "stock")%>% 
  hc_yAxis_multiples(create_yaxis(2, height = c(2, 2), turnopposite = TRUE))%>%
  hc_add_series(c,name="Importe Total",yAxis=0)%>%
  hc_add_series(b,name="Velocidad media del viento",yAxis=1)%>% 
  hc_add_series(a,name="Temperatura media",yAxis=1)%>%hc_title(text="Ingresos <b>vs</b> Clima")
  
}

#######==================================================================================================================================#####

 
 
###### Paro
 
paro2<-function(region){
  
  
  fechas<-names(p[,2:62]) 
  parito<-p
  
  parito<-p%>%dplyr::filter(MUNICIPIOS%in%region)
  
  barras<-list()
  for( i in 1:length(region)){
    barras[[i]]<-as.data.frame(parito[i,])
    barras[[i]]<-barras[[i]]%>%dplyr::select(-MUNICIPIOS) 
  }
  
  
  barras2<-list()
  
  for(i in 1:length(region)){
    barras2[[i]]<-as.data.frame(t(barras[[i]]))
    barras2[[i]]$FECHAS<-fechas
    
  }
  if(length(region)==1){
    a<-highchart()%>%hc_add_series(barras2[[1]],"column",hcaes(x=FECHAS,y=V1),name=paste("Paro  en:",parito$MUNICIPIOS[1]))%>%
      hc_xAxis(categories=fechas)
  }    
  if(length(region)==2){
    a<-highchart()%>%hc_add_series(barras2[[1]],"column",hcaes(x=FECHAS,y=V1),name=paste("Paro en:",parito$MUNICIPIOS[1]))%>%
      hc_add_series(barras2[[2]],"column",hcaes(x=FECHAS,y=V1),name=paste("Paro en :",parito$MUNICIPIOS[2]))%>%
      hc_xAxis(categories=fechas)
  }  
  if(length(region)==3){
    a<- highchart()%>%hc_add_series(barras2[[1]],"column",hcaes(x=FECHAS,y=V1),name=paste("Paro en:",parito$MUNICIPIOS[1]))%>%
      hc_add_series(barras2[[2]],"column",hcaes(x=FECHAS,y=V1),name=paste("Paro en:",parito$MUNICIPIOS[2]))%>%
      hc_add_series(barras2[[3]],"column",hcaes(x=FECHAS,y=V1),name=paste("Paro en:",parito$MUNICIPIOS[3]))%>%
      hc_xAxis(categories=fechas)
  }  
  a
  
}

######====================================================================================================================================#####


######Series Temorales comparacon de Codigos postales de comercio y cliente

######====================================================================================================================================#####




###### GRAFOS DE CLIENTES

grafo<-function(codes,sexo,renta,edad){

Grafo<-datos2
if(sexo=="hombres"){Grafo<-Grafo%>%dplyr::filter(PROP_SEX==1)}
if(sexo=="mujeres"){Grafo<-Grafo%>%dplyr::filter(PROP_SEX==0)}

  
if(edad=="jovenes"){Grafo<-Grafo%>%dplyr::filter(PROP_JOVEN==1)}
if(edad=="adultos"){Grafo<-Grafo%>%dplyr::filter(PROP_ADULTO==1)}
if(edad=="jubilados"){Grafo<-Grafo%>%dplyr::filter(PROP_PENSIONISTA==1)}

if(renta=="baja"){Grafo<-Grafo%>%dplyr::filter(PROP_R_BAJA==1)}
if(renta=="media"){Grafo<-Grafo%>%dplyr::filter(PROP_R_MEDIA==1)}
if(renta=="alta"){Grafo<-Grafo%>%dplyr::filter(PROP_R_ALTA==1)}

Grafo<-Grafo%>%dplyr::select(CP_CLIENTE,CP_COMERCIO,IMPORTE)%>%dplyr::filter(CP_CLIENTE%in%codes)%>%dplyr::group_by(CP_CLIENTE,CP_COMERCIO)%>%dplyr::summarise_all(funs(sum))
Grafo<-Grafo%>%dplyr::group_by(CP_CLIENTE)%>%mutate(ANCHURA=IMPORTE/max(IMPORTE)*15)%>%dplyr::ungroup()


df<-datos2

if(sexo=="hombres"){df<-df%>%dplyr::filter(PROP_SEX==1)}
if(sexo=="mujeres"){df<-df%>%dplyr::filter(PROP_SEX==0)}


if(edad=="jovenes"){df<-df%>%dplyr::filter(PROP_JOVEN==1)}
if(edad=="adultos"){df<-df%>%dplyr::filter(PROP_ADULTO==1)}
if(edad=="jubilados"){df<-df%>%dplyr::filter(PROP_PENSIONISTA==1)}

if(renta=="baja"){df<-df%>%dplyr::filter(PROP_R_BAJA==1)}
if(renta=="media"){df<-df%>%dplyr::filter(PROP_R_MEDIA==1)}
if(renta=="alta"){df<-df%>%dplyr::filter(PROP_R_ALTA==1)}



df<-df%>%dplyr::filter(CP_CLIENTE%in%codes)%>%dplyr::select(CP_CLIENTE,CP_COMERCIO,IMPORTE,SECTOR)%>%
            dplyr::group_by(CP_CLIENTE,CP_COMERCIO,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
df<-df%>%dplyr::filter(CP_COMERCIO %in%unique(Grafo$CP_COMERCIO))


maximos<-vector()
sectores<-vector()
j=0
for(w in unique(df$CP_CLIENTE)){
for(i in unique(df$CP_COMERCIO)){
  j=j+1
  medio<-df%>%dplyr::filter(CP_CLIENTE==w&CP_COMERCIO==i)%>%dplyr::select(IMPORTE,SECTOR)
  if(nrow(medio)!=0){
  sectores[j]<-as.character(medio$SECTOR[which.max(medio$IMPORTE)])
  maximos[j]=max(medio$IMPORTE)}else{maximos[j]=0}
}}
sectores<-sectores[is.na(sectores)!=TRUE]
maximos<-maximos[maximos!=0]


nodes <- data.frame(id = unique(c(paste0("Cli_",Grafo$CP_CLIENTE),paste0("Com_",Grafo$CP_COMERCIO))),
                    group=c(rep("Cliente",length(unique(Grafo$CP_CLIENTE))),rep("Comercio",length(unique(Grafo$CP_COMERCIO)))),
                    label = unique(c(paste0("Cli_",Grafo$CP_CLIENTE),paste0("Com_",Grafo$CP_COMERCIO))))
nodes$color.border <- "black"

edges <- data.frame(from = paste0("Cli_",Grafo$CP_CLIENTE), to = paste0("Com_",Grafo$CP_COMERCIO),
                    width = Grafo$ANCHURA,# arrows
                    arrows = c("to"))
edges$title <- paste0(paste0("Transacciones de ",Grafo$CP_CLIENTE," a ",Grafo$CP_COMERCIO,":"), "<br> Cantidad : ", round(Grafo$IMPORTE, 0),"\u20ac", "<br> Sector de mayor gasto : ", "<br>",sectores," ",round(maximos,0),"\u20ac")

if(length(codes)==1){
network<<-visNetwork(nodes, edges,width = "100%",main = "<span style='font-weight:normal;'><font face='Arial' color='black' size='4px'>Flujo de las transacciones</font></span>")%>% 
  visNodes(font=list(size=23))%>%
  visEdges(shadow = TRUE,
           arrows =list(to = list(enabled = TRUE)),
           color = list(color = "f44747", highlight = "eedc31")) %>%
  visLayout(randomSeed = 4,improvedLayout=T)%>%
  visOptions(highlightNearest = F, 
             nodesIdSelection = F)%>%
  visGroups(groupname = "Cliente", shape = "icon", icon = list(code = "f007", size = 75,color="black")) %>%
  visGroups(groupname = "Comercio", shape = "icon", icon = list(code = "f07a", size = 75, color = "0e68ce")) %>%
  visLegend(width=0.09) %>%
  addFontAwesome()%>%
  visInteraction(keyboard = T, dragNodes = T,dragView = T, tooltipDelay = 10)%>%
  visIgraphLayout(layout = "layout_with_gem",type="square",randomSeed = 123,physics = F, smooth = F) %>%
  visEvents(selectNode  = "function(e){
            var label_info = this.body.data.nodes.get({
            fields: ['label', 'label_long'],
            filter: function (item) {
            return item.id === e.node
            },
            returnType :'Array'
            });
            this.body.data.nodes.update({id: e.node, label : label_info[0].label_long, label_long : label_info[0].label});
}")
}
if(length(codes)!=1){
  network<<-visNetwork(nodes, edges,width = "100%",main = "<span style='font-weight:normal;'><font face='Arial' color='black' size='4px'>Flujo de las transacciones</font></span>")%>% 
    visNodes(font=list(size=23))%>%
    visEdges(shadow = TRUE,
             arrows =list(to = list(enabled = TRUE)),
             color = list(color = "f44747", highlight = "eedc31")) %>%
    visLayout(randomSeed = 4,improvedLayout=T)%>%
    visOptions(highlightNearest = F, 
               nodesIdSelection = F)%>%
    visGroups(groupname = "Cliente", shape = "icon", icon = list(code = "f007", size = 75,color="black")) %>%
    visGroups(groupname = "Comercio", shape = "icon", icon = list(code = "f07a", size = 75, color = "0e68ce")) %>%
    visLegend(width=0.09) %>%
    addFontAwesome()%>%
    visInteraction(keyboard = T, dragNodes = T,dragView = T, tooltipDelay = 10)%>%
    visIgraphLayout(layout = "layout_in_circle",type="square",randomSeed = 123,physics = F, smooth = F)
}
network
#FORMA 1: layout_with_gem
}

######====================================================================================================================================#####


###### COMPARACION TEMPORAL CP_CLIENTES

temp_clientes<-function(sector,clientes,sexo,renta,edad){
  
  
  df<-datos2
  
  if(sexo=="hombres"){df<-df%>%dplyr::filter(PROP_SEX==1)}
  if(sexo=="mujeres"){df<-df%>%dplyr::filter(PROP_SEX==0)}
  
  
  if(edad=="jovenes"){df<-df%>%dplyr::filter(PROP_JOVEN==1)}
  if(edad=="adultos"){df<-df%>%dplyr::filter(PROP_ADULTO==1)}
  if(edad=="jubilados"){df<-df%>%dplyr::filter(PROP_PENSIONISTA==1)}
  
  if(renta=="baja"){df<-df%>%dplyr::filter(PROP_R_BAJA==1)}
  if(renta=="media"){df<-df%>%dplyr::filter(PROP_R_MEDIA==1)}
  if(renta=="alta"){df<-df%>%dplyr::filter(PROP_R_ALTA==1)}
  
  if(sector!="Todos"){
  df<-df%>%dplyr::filter(SECTOR==sector,CP_CLIENTE%in%clientes)%>%dplyr::select(SECTOR,CP_CLIENTE,NUM_OP,IMPORTE,FECHA)
  df<-df%>%dplyr::group_by(CP_CLIENTE,FECHA,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
  }
  
  if(sector=="Todos"){
    df<-df%>%dplyr::filter(CP_CLIENTE%in%clientes)%>%dplyr::select(CP_CLIENTE,NUM_OP,IMPORTE,FECHA)
    df<-df%>%dplyr::group_by(CP_CLIENTE,FECHA)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    
  }
  
  
  df$CP_CLIENTE<-paste(df$CP_CLIENTE, sector)
  df <- data.table(df)
  df <- df[,list(IMPORTE = sum(IMPORTE)), by = 'FECHA,CP_CLIENTE']
  
  sectores<-as.vector(unique(df$CP_CLIENTE))
  df<-dcast(df,FECHA~CP_CLIENTE,value.var = "IMPORTE")
  df<-arrange(df,FECHA)
  df[is.na(df)]<-0
  df$FECHA<-as.POSIXct(df$FECHA,format="%Y/%m/%d")
  df$SECTOR<-rep_len(sector,nrow(df))
  
  
  
 
amTimeSeries(df,col_date = "FECHA",col_series = as.character(sectores),ylab="Importe ( \u20ac  )",
                                       main = "Serie temporal de los importes por sector y codigo postal de cliente.",
                                       linewidth = 2.3,
                                       linetype = 0,
                                       bullet="round",
                                       bulletSize = 8,
                                       aggregation="Sum",
                                       color=c("#88d8b0","#ff6f69","#ffcc5c"))
                          
  
  
}

######====================================================================================================================================#####


###### COMPARACION TEMPORAL CP_CLIENTES

temp_comercios<-function(sector,comercios,sexo,renta,edad){
  
  df<-datos2
  
  if(sexo=="hombres"){df<-df%>%dplyr::filter(PROP_SEX==1)}
  if(sexo=="mujeres"){df<-df%>%dplyr::filter(PROP_SEX==0)}
  
  
  if(edad=="jovenes"){df<-df%>%dplyr::filter(PROP_JOVEN==1)}
  if(edad=="adultos"){df<-df%>%dplyr::filter(PROP_ADULTO==1)}
  if(edad=="jubilados"){df<-df%>%dplyr::filter(PROP_PENSIONISTA==1)}
  
  if(renta=="baja"){df<-df%>%dplyr::filter(PROP_R_BAJA==1)}
  if(renta=="media"){df<-df%>%dplyr::filter(PROP_R_MEDIA==1)}
  if(renta=="alta"){df<-df%>%dplyr::filter(PROP_R_ALTA==1)}
  
  if(sector!="Todos"){
                      df<-df%>%dplyr::filter(SECTOR==sector,CP_COMERCIO%in%comercios)%>%dplyr::select(SECTOR,CP_COMERCIO,NUM_OP,IMPORTE,FECHA)
                      df<-df%>%dplyr::group_by(CP_COMERCIO,FECHA,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
  }
  if(sector=="Todos"){
                      df<-df%>%dplyr::filter(CP_COMERCIO%in%comercios)%>%dplyr::select(CP_COMERCIO,NUM_OP,IMPORTE,FECHA)
                      df<-df%>%dplyr::group_by(CP_COMERCIO,FECHA)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    
  }
  
  df$CP_COMERCIO<-paste(df$CP_COMERCIO, sector)
  df <- data.table(df)
  df <- df[,list(IMPORTE = sum(IMPORTE)), by = 'FECHA,CP_COMERCIO']
  sectores<-as.vector(unique(df$CP_COMERCIO))
  df<-dcast(df,FECHA~CP_COMERCIO,value.var = "IMPORTE")
  df<-arrange(df,FECHA)
  df[is.na(df)]<-0
  df$FECHA<-as.POSIXct(df$FECHA,format="%Y/%m/%d")
  df$SECTOR<-rep_len(sector,nrow(df))
  
  
  
  
  z<-amTimeSeries(df,col_date = "FECHA",col_series = as.character(sectores),ylab="Importe ( \u20ac  )",
               main = "Serie temporal de los importes por sector y codigo postal de comercio.",
               linewidth = 2.3,
               linetype = 0,
               bullet="round",
               bulletSize = 8,
               aggregation="Sum",
               color=c("#88d8b0","#ff6f69","#ffcc5c"))
  
  
  
}

######====================================================================================================================================#####


###### RESULTADOS GENERALES CÓDIGOS POSTALES

stack<-function(sectoricus){
  
  if(sectoricus!="todos"){
    prueba<-datos2%>%dplyr::filter(SECTOR==sectoricus)%>%dplyr::select(IMPORTE,CP_COMERCIO,SECTOR)%>%
                     dplyr::group_by(CP_COMERCIO,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    
    prueba$IMPORTE<-round(prueba$IMPORTE,0)
    prueba$CP_COMERCIO<-as.factor(prueba$CP_COMERCIO)
    a<-hchart(prueba, "column",hcaes(x=CP_COMERCIO,y=IMPORTE,group=as.factor(SECTOR)))%>%
      hc_plotOptions(column=list(stacking="normal"))%>%
      hc_tooltip(pointFormat = "<b>{point.SECTOR}</b>: {point.IMPORTE} \u20ac")%>%
      hc_yAxis(max=max(prueba$IMPORTE)*2)
    
  }
  
  if(sectoricus=="todos"){
  prueba<-datos2%>%dplyr::select(SECTOR,IMPORTE,CP_COMERCIO)%>%dplyr::group_by(CP_COMERCIO,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
  
  
  
  prueba$IMPORTE<-round(prueba$IMPORTE,0)
  prueba$CP_COMERCIO<-as.factor(prueba$CP_COMERCIO)
  a<-hchart(prueba, "column",hcaes(x=as.factor(CP_COMERCIO),y=IMPORTE,group=as.factor(SECTOR)))%>%
    hc_plotOptions(column=list(stacking="normal"))%>%
    hc_tooltip(pointFormat = "<b>{point.SECTOR}</b>: {point.IMPORTE} \u20ac")%>%
    hc_yAxis(max=max(prueba$IMPORTE)*2)
  }
  a
}


mosaicos1<-function(sectoricus){
  
  if(sectoricus!="todos"){
    
    prueba<-datos2%>%dplyr::filter(SECTOR==sectoricus)%>%dplyr::select(IMPORTE,CP_COMERCIO,SECTOR)%>%
      dplyr::group_by(CP_COMERCIO,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    
  
    prueba$IMPORTE<-round(prueba$IMPORTE,0)
    prueba$CP_COMERCIO<-as.factor(prueba$CP_COMERCIO)
 
    
  }else{
  
  
    prueba<-datos2%>%dplyr::select(IMPORTE,CP_COMERCIO)%>%dplyr::group_by(CP_COMERCIO)%>%
    dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    prueba$IMPORTE<-round(prueba$IMPORTE,0)
    prueba$CP_COMERCIO<-as.factor(prueba$CP_COMERCIO)
  
  }
    hchart(prueba,"treemap",hcaes(x=CP_COMERCIO,value=IMPORTE,color=IMPORTE))%>%
    hc_tooltip(pointFormat = "<b>Codigo Postal {point.CP_COMERCIO}</b>: {point.IMPORTE} \u20ac")%>% 
    hc_title(text = "Comercios", style = list(color = "black"))
  
  
}

mosaicos2<-function(sectoricus){
  
  if(sectoricus!="todos"){
    
    prueba2<-datos2%>%dplyr::filter(SECTOR==sectoricus)%>%dplyr::select(IMPORTE,CP_CLIENTE,SECTOR)%>%
      dplyr::group_by(CP_CLIENTE,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    prueba2<-prueba2[1:25,]
    
    prueba2$IMPORTE<-round(prueba2$IMPORTE,0)
    prueba2$CP_CLIENTE<-as.factor(prueba2$CP_CLIENTE)
    
    
  }else{
    
    prueba2<-datos2%>%dplyr::select(IMPORTE,CP_CLIENTE)%>%
      dplyr::group_by(CP_CLIENTE)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()%>%
      dplyr::arrange(desc(IMPORTE))
    prueba2<-prueba2[1:25,]
    
    prueba2$IMPORTE<-round(prueba2$IMPORTE,0)
    prueba2$CP_CLIENTE<-as.factor(prueba2$CP_CLIENTE)
    
  }
 
  hchart(prueba2,"treemap",hcaes(x=CP_CLIENTE,value=IMPORTE,color=IMPORTE))%>%
    hc_tooltip(pointFormat = "<b>Codigo Postal {point.CP_CLIENTE}</b>: {point.IMPORTE} \u20ac")%>% 
    hc_title(text = "Clientes", style = list(color = "black"))
}


mosaicos_or<-function(sectoricus){

  
  
  if(sectoricus!="todos"){
    
    
    prueba<-datos2%>%dplyr::filter(SECTOR==sectoricus)%>%dplyr::select(IMPORTE,CP_COMERCIO,SECTOR)%>%
      dplyr::group_by(CP_COMERCIO,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    
    
    prueba$IMPORTE<-round(prueba$IMPORTE,0)
    prueba$CP_COMERCIO<-as.factor(prueba$CP_COMERCIO)
    
    
    prueba2<-datos2%>%dplyr::filter(SECTOR==sectoricus)%>%dplyr::select(IMPORTE,CP_CLIENTE,SECTOR)%>%
      dplyr::group_by(CP_CLIENTE,SECTOR)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    prueba2<-prueba2[1:25,]
    
    prueba2$IMPORTE<-round(prueba2$IMPORTE,0)
    prueba2$CP_CLIENTE<-as.factor(prueba2$CP_CLIENTE)
    
    
  }else{
    
    
    prueba<-datos2%>%dplyr::select(IMPORTE,CP_COMERCIO)%>%dplyr::group_by(CP_COMERCIO)%>%
      dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()
    prueba$IMPORTE<-round(prueba$IMPORTE,0)
    prueba$CP_COMERCIO<-as.factor(prueba$CP_COMERCIO)
    
    prueba2<-datos2%>%dplyr::select(IMPORTE,CP_CLIENTE)%>%
      dplyr::group_by(CP_CLIENTE)%>%dplyr::summarise_all(funs(sum))%>%dplyr::ungroup()%>%
      dplyr::arrange(desc(IMPORTE))
    prueba2<-prueba2[1:25,]
    
    prueba2$IMPORTE<-round(prueba2$IMPORTE,0)
    prueba2$CP_CLIENTE<-as.factor(prueba2$CP_CLIENTE)
    
  }
  
  a<-hchart(prueba,"treemap",hcaes(x=CP_COMERCIO,value=IMPORTE,color=IMPORTE))%>%
    hc_tooltip(pointFormat = "<b>Codigo Postal {point.CP_COMERCIO}</b>: {point.IMPORTE} \u20ac")%>% 
    hc_title(text = "Comercios", style = list(color = "black"))
  
  
  b<-hchart(prueba2,"treemap",hcaes(x=CP_CLIENTE,value=IMPORTE,color=IMPORTE))%>%
    hc_tooltip(pointFormat = "<b>Codigo Postal {point.CP_CLIENTE}</b>: {point.IMPORTE} \u20ac")%>% 
    hc_title(text = "Clientes", style = list(color = "black"))
  
  return(list(a,b))
  
}




