#! /usr/bin/env Rscript

# librerias --------------------------------------------------------------------
library(tidyverse)
library(janitor)
library(lubridate)
library(echarts4r)
library(DT)
library(scales)
library(sf)
library(rio)
library(rmapshaper)
library(bslib)
library(htmltools)
library(ggthemes)
library(gdata)

# constantes -------------------------------------------------------------------
vec_edad_quin <- c("5-9", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39",
                   "40-44", "45-49", "50-54", "55-59", "60-64", "65-69", "70-74", 
                   "75-79", "80 a más")
vec_edad_ev <- c('Niño', 'Adolescente', 'Joven', 'Adulto', 'Adulto mayor')

# ARGUMENTOS ----

args <- commandArgs(trailingOnly = TRUE)

# Verficar si se cuenta con argumentos
if (length(args) == 0) {
  args[1] <- format(Sys.Date(), "%Y-%m-%d")
  rlang::inform(c("i" = "Se está usando la fecha actual como fecha de actualización"))
} else if (length(args) == 1) {
  rlang::inform(c("i" = glue::glue("La fecha de actualización es: {args[1]}")))
}

# UTILIDADES ----

# Fechas
adate <- as.Date(args[1])
cdate <- floor_date(adate, unit = "week") - 1
cmnth <- floor_date(adate, unit = "month") - 1
cweek <- epiweek(cdate)
cyear <- epiyear(cdate)

# Base de datos ----------------------------------------------------------------

shp_departamento <- st_read('data/geo/CDC_DepartamentosLimet_Simplificado.shp') %>% 
  rename(departamento = departamen) %>% 
  ms_simplify()

shp_provincia <- st_read('data/geo/CDC_Provincias_Simplificado_2022.shp') %>% 
  rename(departamento = departamen) %>% 
  ms_simplify()

shp_distrito <- st_read('data/geo/CDC_Distritos_Simplificado_2022.shp') %>% 
  rename(departamento = departamen) %>% 
  ms_simplify()

unidades_not <- import('data/raw/unidades_notificantes.rds') %>% 
  clean_names()%>% 
  select(departamento = region, diresas = nombre_reg) %>% 
  mutate_all(., as.character) %>% 
  mutate(diresas = ifelse(diresas == "DIRIS LIMA CENTR", "DIRIS LIMA CENTRO", diresas),
         diresas = ifelse(diresas == "MORROPON-HUANCAB", "MORROPON-HUANCABAMBA", diresas)) %>% 
  as.data.frame() %>% 
  distinct()

es_cat <- import('data/raw/unidades_notificantes.rds') %>% 
  select(categoria, eess = cod_est)

base_diabetes_tend <- import('data/raw/tendecias_sexo_region.xlsx') %>% 
  clean_names() %>% 
  filter(ano < 2022) %>% 
  select(diresa, ano, masculino, femenino) %>% 
  pivot_longer(names_to = 'sexo', values_to = 'casos', -c(ano, diresa)) %>% 
  mutate(sexo = str_to_title(sexo)) %>%  
  rename(diresas = diresa) %>% 
  left_join(unidades_not, by = 'diresas') %>% 
  mutate(departamento2 = case_when(
    str_detect('DIRIS', diresas) ~ 'LIMA METROPOLITANA',
    diresas == 'LIMA PROVINCIAS' ~ 'LIMA',
    T ~ departamento
  ))

# base_diabetes_2022 <- import('data/raw/base_diabetes_2022.xlsx') %>% 
#   clean_names() %>%  
#   mutate(ano = 2022) %>% 
#   select(fecha_cap, diresas, ubigeo= ubigeo_res, tcaso, tdiabetes, edad, sexo, hemoglic, glicemia,
#          establecimiento, eess, ano, hta:tbc, neuropatia:enfarterial, nefropatia, evaluado)
# 
# base_diabetes_2023 <- import('data/raw/base_diabetes_2023.xlsx')%>% 
#   clean_names() %>%  
#   mutate(ano = 2023) %>% 
#   select(fecha_cap = fecha_cap, diresas, ubigeo= ubigeo_res, tcaso, tdiabetes, edad, sexo, hemoglic, glicemia,
#          establecimiento, eess, ano, hta:tbc, neuropatia:enfarterial, nefropatia, evaluado)

base_diabetes_hist <- list.files('data/raw/', full.names = TRUE, pattern = "^base_diabetes") %>% 
  map_df(import) %>% 
  select(fecha_cap = fecha_cap, diresas, ubigeo= ubigeo_res, tcaso, tdiabetes, edad, sexo, hemoglic, glicemia,
         establecimiento, eess, ano, hta:tbc, neuropatia:enfarterial, nefropatia, evaluado)

base_diabetes_actual <- import('data/raw/diabetes_actual.xlsx')%>% 
  clean_names() %>%  
  select(fecha_cap = fecha_cap, diresas, ubigeo= ubigeo_res, tcaso, tdiabetes, edad, sexo, hemoglic, glicemia,
         establecimiento, eess, ano, hta:tbc, neuropatia:enfarterial, nefropatia, evaluado) %>% 
  mutate(ubigeo = as.character(ubigeo),
         ubigeo = case_when(
           nchar(ubigeo) == 5 ~ paste0(strrep("0", 1), ubigeo),
           nchar(ubigeo) == 4 ~ paste0(strrep("0", 2), ubigeo),
           nchar(ubigeo) == 3 ~ paste0(strrep("0", 3), ubigeo),
           nchar(ubigeo) == 2 ~ paste0(strrep("0", 4), ubigeo),
           nchar(ubigeo) == 1 ~ paste0(strrep("0", 5), ubigeo),
           TRUE ~ ubigeo),
         hemoglic = as.numeric(hemoglic)
  )

base_diabetes <- bind_rows(base_diabetes_hist, base_diabetes_actual) %>% 
  mutate(tipo_eess = str_sub(eess, 8, 8)) %>% 
  mutate(tcaso = if_else(tcaso == 1, 'Nuevo', 'Prevalente'),
         tdiabetes = case_when(
           tdiabetes == 1 ~ 'DM Tipo 1',
           tdiabetes == 2 ~ 'DM Tipo 2',
           tdiabetes == 3 ~ 'D Gestacional',
           #tdiabetes == 4 ~ 'D Secundaria',
           #tdiabetes == 5 ~ 'Pre diabetes',
           T ~ 'Otros'
         ),
         sector = case_when(
           str_detect(eess, 'A') ~ 'Minsa',
           str_detect(eess, 'C') ~ 'EsSalud',
           str_detect(eess, 'D') ~ 'Fuerzas armadas/PNP',
           str_detect(eess, 'X') ~ 'Privados'
         ),
         sexo = if_else(sexo == 1, 'Masculino', 'Femenino'),
         control_gli = if_else(hemoglic < 7, 'Compensado (<7.0)', 'Descompensado (7.0 a más)'),
         glicemia_ran = case_when(
           glicemia < 70 ~ 'Bajo (<70)',
           glicemia >= 70 & glicemia <= 129 ~ 'Normal (70 a 129)',
           glicemia > 129 ~ 'Alto (130 a más)'
         )) %>% 
  mutate(edad_q = case_when(
    between(edad, 0, 4) ~ '0-4',
    between(edad, 5, 9) ~ '5-9',
    between(edad, 10, 14) ~ '10-14',
    between(edad, 15, 19) ~ '15-19',
    between(edad, 20, 24) ~ '20-24',
    between(edad, 25, 29) ~ '25-29',
    between(edad, 30, 34) ~ '30-34',
    between(edad, 35, 39) ~ '35-39',
    between(edad, 40, 44) ~ '40-44',
    between(edad, 45, 49) ~ '45-49',
    between(edad, 50, 54) ~ '50-54',
    between(edad, 55, 59) ~ '55-59',
    between(edad, 60, 64) ~ '60-64',
    between(edad, 65, 69) ~ '65-69',
    between(edad, 70, 74) ~ '70-74',
    between(edad, 75, 79) ~ '75-79',
    between(edad, 80, 130) ~ '80 a más'
  )) %>% 
  mutate(id2 = case_when(
    between(edad, 0, 4) ~ 1,
    between(edad, 5, 9) ~ 2,
    between(edad, 10, 14) ~ 3,
    between(edad, 15, 19) ~ 4,
    between(edad, 20, 24) ~ 5,
    between(edad, 25, 29) ~ 6,
    between(edad, 30, 34) ~ 7,
    between(edad, 35, 39) ~ 8,
    between(edad, 40, 44) ~ 9,
    between(edad, 45, 49) ~ 10,
    between(edad, 50, 54) ~ 11,
    between(edad, 55, 59) ~ 12,
    between(edad, 60, 64) ~ 13,
    between(edad, 65, 69) ~ 14,
    between(edad, 70, 74) ~ 15,
    between(edad, 75, 79) ~ 16,
    between(edad, 80, 130) ~ 17
  )) %>%
  mutate(ev = case_when(
    between(edad, 0, 11) ~ 'Niño',
    between(edad, 12, 17) ~ 'Adolescente',
    between(edad, 18, 29) ~ 'Joven',
    between(edad, 30, 59) ~ 'Adulto',
    between(edad, 60, 24000) ~ 'Adulto mayor'
  )) %>% 
  left_join(unidades_not, by = 'diresas') %>% 
  mutate(departamento2 = case_when(
    str_detect('DIRIS', diresas) ~ 'LIMA METROPOLITANA',
    diresas == 'LIMA PROVINCIAS' ~ 'LIMA',
    T ~ departamento
  )) %>% 
  mutate(region = case_when(
    departamento2 %in% c('LIMA', 'LIMA METROPOLITANA', 'AREQUIPA', 'ANCASH', 'MOQUEGUA', 'PIURA', 'CALLAO', 'LAMBAYEQUE', 'LA LIBERTAD', 'TUMBES', 'ICA','Lima', 'TACNA') ~ 'Costa',
    departamento2 %in% c('PASCO', 'AYACUCHO', 'HUANCAVELICA', 'CAJAMARCA', 'CUSCO', 'HUANUCO', 'APURIMAC', 'PUNO', 'JUNIN') ~ 'Sierra',
    departamento2 %in% c('UCAYALI', 'LORETO', 'AMAZONAS', 'SAN MARTIN', 'MADRE DE DIOS') ~ 'Selva'
  )) %>% 
  left_join(es_cat) %>% 
  mutate(tipo_hos = case_when(
    tipo_eess == 1  ~ 'Hospitales',
    tipo_eess != 1 ~ 'Primer nivel'
  )) %>% 
  mutate(mes = month(fecha_cap))

base_diabetes_tend_of <- base_diabetes_tend %>% 
  group_by(departamento, ano, sexo) %>% 
  summarise(casos = sum(casos)) %>% 
  ungroup() %>%
  bind_rows(base_diabetes %>% 
              filter(ano >= 2022) %>% 
              count(departamento, ano, sexo, name = 'casos'))

base_vraem <- import('data/raw/distritos_vraem2022.xlsx')

bases_list_diabetes <- list(shp_departamento,
                            shp_provincia,
                            shp_distrito,
                            base_diabetes_tend_of,
                            base_diabetes,
                            base_vraem)

bases_list_diabetes %>% rio::export('shiny_diabetes_ut/processed/data_diabetes_insumo.rds')
bases_list_diabetes %>% rio::export('shiny_diabetes_web/processed/data_diabetes_insumo.rds')

# Fechas
saveRDS(
  list(
    adate = adate,
    cdate = cdate,
    cmnth = cmnth,
    cweek = cweek,
    cyear = cyear
  ),
  "./shiny_diabetes_ut/processed/shiny_dates.rds"
)

saveRDS(
  list(
    adate = adate,
    cdate = cdate,
    cmnth = cmnth,
    cweek = cweek,
    cyear = cyear
  ),
  "./shiny_diabetes_web/processed/shiny_dates.rds"
)
