library(shiny)
library(DT)
library(dplyr)
library(readr)
library(Cairo)
library(ggplot2)
library(plotly)
library(stringi)
library(stringr)
library(datetime)
library(dplyr)
library(ggthemes)
library(RMySQL)

csv_map <- list(
  "按月统计"       = "按月统计0.csv",
  "最后六周按日统计"   = "按日统计0.csv",
  "按小细胞统计"     = "按细胞统计0.csv",
  "按省统计"       = "按区域统计0.csv",
  "按仪器统计"     = "按仪器统计0.csv",
  "按样本类型统计" = "按样本统计0.csv",
  "按试剂批次统计" = "按批次统计0.csv",
  "按试剂项目统计" = "按项目统计0.csv"
)
page<-1
ui <- fluidPage(
  titlePanel("丹娜数据分析平台-和迈仪器"),
  sidebarLayout(
    sidebarPanel(
      width = 3,  # 设置侧边栏宽度为 2（更小）
      selectInput("stat_dim", "选择统计维度",
                  choices = names(csv_map)),
      uiOutput("metric_group"),
      uiOutput("stat_way"),
      br(),
      br(),
      br(),
      downloadButton("download_table", "下载表格数据")
    ),
    mainPanel(
      width = 9,
      tabsetPanel(
        tabPanel("图表展示", 
                 uiOutput("pagination_ui"),
                 plotlyOutput("main_plot")),
        tabPanel("数据表格", DTOutput("data_table"))

      )
    )
  )
  
)

# 定义服务器逻辑
server <- function(input, output) {
  current_page <- reactiveVal(page)
  output$download_table <- downloadHandler(
    filename = function() {
      paste0(input$stat_dim, "_", Sys.Date(), ".csv")
    },
    content = function(file) {
      data <- data_raw()
      write_excel_csv(data, file)
    }
  )
  output$pagination_ui <- renderUI({
    req(input$stat_dim, input$metric, input$stat_way_sel)
    
    max_pages <- switch(input$stat_dim,
                        "最后六周按日统计" = {
                          if (input$stat_way_sel == "按日分省统计") {
                            ceiling(length(dfBy区域$省编号) / 6)
                          } else if (input$stat_way_sel == "按日分小细胞统计") {
                            ceiling(length(细胞0$细胞) / 6)
                          } else if (input$stat_way_sel == "按日分仪器统计") {
                            ceiling(length(仪器号List$仪器序列号) / 6)
                          } else 1
                        },
                        "按月统计" = {
                          if (input$stat_way_sel == "按月分省统计") {
                            ceiling(length(dfBy区域$省编号) / 6)
                          } else if (input$stat_way_sel == "按月分小细胞统计") {
                            ceiling(length(细胞0$细胞) / 6)
                          } else if (input$stat_way_sel == "按月分仪器统计") {
                            ceiling(length(仪器号List$仪器序列号) / 6)
                          } else 1
                        },
                        "按仪器统计"     = max(仪器号List$GroupID),
                        "按试剂批次统计" = max(批次号List$GroupID),
                        "按试剂项目统计" = max(项目号List$GroupID),
                        "按小细胞统计" = 2,
                        1)
    
    if (max_pages > 1) {
      tagList(
        actionButton("prev_page", "上一页"),
        span(paste("第", current_page(), "页 / 共", max_pages, "页")),
        actionButton("next_page", "下一页")
      )
    }
  })
  
  observeEvent(input$prev_page, {
    if (current_page() > 1) current_page(current_page() - 1)
  })
  
  observeEvent(input$next_page, {
    max_pages <- switch(input$stat_dim,
                        "最后六周按日统计" = {
                          if (input$stat_way_sel == "按日分省统计") {
                            ceiling(length(dfBy区域$省编号) / 6)
                          } else if (input$stat_way_sel == "按日分细胞统计") {
                            ceiling(length(细胞0$细胞) / 6)
                          } else if (input$stat_way_sel == "按日分仪器统计") {
                            ceiling(length(仪器号List$仪器序列号) / 6)
                          } else 1
                        },
                        "按月统计" = {
                          if (input$stat_way_sel == "按月分省统计") {
                            ceiling(length(dfBy区域$省编号) / 6)
                          } else if (input$stat_way_sel == "按月分细胞统计") {
                            ceiling(length(细胞0$细胞) / 6)
                          } else if (input$stat_way_sel == "按月分仪器统计") {
                            ceiling(length(仪器号List$仪器序列号) / 6)
                          } else 1
                        },
                        "按仪器统计"     = max(仪器号List$GroupID),
                        "按试剂批次统计" = max(批次号List$GroupID),
                        "按试剂项目统计" = max(项目号List$GroupID),
                        "按小细胞统计" = 2,
                        1)
    if (current_page() < max_pages) current_page(current_page() + 1)
  })
  # 动态生成第二栏：指标分组
  output$metric_group <- renderUI({
    metric_choices <- switch(input$stat_dim,
                             "最后六周按日统计" = list("测试数、阳性数、有效数", 
                                               "阳性率、有效率", 
                                               "项目数、仪器数、批次数", 
                                               "省数、市数、小细胞数、样本数"),
                             "按月统计" = list("测试数、阳性数、有效数", 
                                           "阳性率、有效率", 
                                           "项目数、仪器数、批次数", 
                                           "省数、市数、小细胞数、样本数"),
                             "按小细胞统计"=list("测试数、阳性数、有效数", 
                                           "阳性率、有效率", 
                                           "项目数、仪器数、批次数", 
                                           "省数、市数、小细胞数、样本数", 
                                           "测试截止、测试开始"),
                             "按省统计" = list("测试数、阳性数、有效数", 
                                           "阳性率、有效率", 
                                           "项目数、仪器数、批次数", 
                                           "省数、市数、小细胞数、样本数", 
                                           "测试截止、测试开始"),
                             "按仪器统计" = list("测试数、阳性数、有效数", 
                                            "阳性率、有效率", 
                                            "项目数、仪器数、批次数", 
                                            "省数、市数、小细胞数、样本数", 
                                            "测试截止、测试开始"),
                             "按样本类型统计" = list("测试数、阳性数、有效数", 
                                              "阳性率、有效率", 
                                              "项目数、仪器数、批次数", 
                                              "省数、市数、小细胞数、样本数"),
                             "按试剂批次统计" = list("测试数、阳性数、有效数", 
                                              "阳性率、有效率", 
                                              "项目数、仪器数、批次数", 
                                              "省数、市数、小细胞数、样本数", 
                                              "测试截止、测试开始"),
                             "按试剂项目统计" = list("测试数、阳性数、有效数", 
                                              "阳性率、有效率", 
                                              "项目数、仪器数、批次数", 
                                              "省数、市数、小细胞数、样本数", 
                                              "测试截止、测试开始"))
    
    selectInput("metric", "选择指标分组", choices = metric_choices)
  })
  
  # 动态生成第三栏：统计方式
  output$stat_way <- renderUI({
    way_choices <- switch(input$stat_dim,
                          "按月统计" = c("全部统计","按月分省统计","按月分小细胞统计","按月分仪器统计"),
                          "最后六周按日统计" = c("全部统计","按日分省统计", "按日分小细胞统计","按日分仪器统计"),
                          "按小细胞统计" = "全部统计", 
                          "按省统计" = "全部统计",
                          "按仪器统计" = "全部统计",
                          "按样本类型统计" = "全部统计",
                          "按试剂批次统计" = "全部统计",
                          "按试剂项目统计"="全部统计")
    if (is.character(way_choices)) {
      selectInput("stat_way_sel", "选择统计方式", choices = way_choices)
    } else {
      NULL
    }
  })
  data_raw <- reactive({
    read_csv(csv_map[[input$stat_dim]])
  })
  # 生成数据表格
  output$data_table <- renderDT({
    datatable(data_raw(), options = list(pageLength = 10))
  })
  
  # 生成图表
  output$main_plot <- renderPlotly({
    req(input$stat_dim, input$metric, input$stat_way_sel)
    data <- generate_data_table(input$stat_dim, input$metric)
    # 把当前页码传进去
    generate_plot(data, input$stat_dim, input$metric, input$stat_way_sel, current_page())
  })
  
  
}


plotfunction<- function(dfData,independentVariableName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count, 
                              text = paste( round(Count, 2)) ,fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   linewidth = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionVector仪器序列号<- function(ik,independentVariableList,dfData,independentVariableName,dependentVariableNames,titleNames) {
  dfData<-dfData[(dfData$仪器序列号 %in% c(independentVariableList[independentVariableList[,2]==ik,][,1])),]
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionVector批次名称<- function(ik,independentVariableList,dfData,independentVariableName,dependentVariableNames,titleNames) {
  dfData<-dfData[(dfData$批次名称 %in% c(independentVariableList[independentVariableList[,2]==ik,][,1])),]
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionVector批次名称Log<- function(ik,independentVariableList,dfData,independentVariableName,dependentVariableNames,titleNames) {
  dfData<-dfData[(dfData$批次名称 %in% c(independentVariableList[independentVariableList[,2]==ik,][,1])),]
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionVector项目名称<- function(ik,independentVariableList,dfData,independentVariableName,dependentVariableNames,titleNames) {
  dfData<-dfData[(dfData$项目名称 %in% c(independentVariableList[independentVariableList[,2]==ik,][,1])),]
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionVector项目名称Log<- function(ik,independentVariableList,dfData,independentVariableName,dependentVariableNames,titleNames) {
  dfData<-dfData[(dfData$项目名称 %in% c(independentVariableList[independentVariableList[,2]==ik,][,1])),]
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionLog<- function(dfData,independentVariableName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionVector仪器序列号Log<- function(ik,independentVariableList,dfData,independentVariableName,dependentVariableNames,titleNames) {
  dfData<-dfData[(dfData$仪器序列号 %in% c(independentVariableList[independentVariableList[,2]==ik,][,1])),]
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = dfData00[,2], y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

panelPlotByDayAndLocation<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$省编号 %in% choosenList,]
  dfData00$省编号<-factor(dfData00$省编号,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testDay, y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 省编号,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

panelPlotByMonthAndLocation<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$省编号 %in% choosenList,]
  dfData00$省编号<-factor(dfData00$省编号,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testMonth, y = Count, text = paste( round(Count, 2)) ,fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 省编号,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
 # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

panelPlotByDayAnd细胞<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$小细胞 %in% choosenList,]
  dfData00$小细胞<-factor(dfData00$小细胞,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testDay, y = Count, text = paste( round(Count, 2)) ,fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 小细胞,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

panelPlotByMonthAnd细胞<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$小细胞 %in% choosenList,]
  dfData00$小细胞<-factor(dfData00$小细胞,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testMonth, y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 小细胞,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

pointPlotfunction批次<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1 <- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(批次名称)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
  #plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

pointPlotfunction批次Log<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1<- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(批次名称)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
 # plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

pointPlotfunction仪器<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1<- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(仪器序列号)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
  #plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

pointPlotfunction仪器Log<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1<- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(仪器序列号)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
 # plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

pointPlotfunction样本<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1<- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(样本类型)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
 # plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

pointPlotfunction样本Log<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1<- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(样本类型)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
 # plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

pointPlotfunction项目<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1<- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(项目名称)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
 # plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

pointPlotfunction项目Log<- function(dfData,independentVariableName,dependentVariableName,titleNames) {
  
  plot1<- ggplot(df20Ploted)+geom_point(aes(dfData[,independentVariableName], dfData[,dependentVariableName],
                                             text = paste( round(dfData[,dependentVariableName], 2)) ,color=as.character(项目名称)))+
    # geom_line(aes(testDay,浓度1移动均值),color="blue")+
    # geom_line(aes(testDay,浓度1累计均值),color="green",linewidth=1.)+
    # geom_line(aes(testDay,浓度1允许波动范围),color="red",linewidth=1.)+
    #  xlim(xmin, xmax) + ylim(ymin, ymax)+theme(legend.position ="right")+
    labs(
      title = titleNames[1],      # 主标题
      x = titleNames[2],        # X轴标签
      y = titleNames[3],              # Y轴标签
      color = titleNames[4]                  # 图例标题
    )+
    # scale_x_date(
    #   date_labels = "%Y-%m-%d",  # 格式符组合
    #   date_breaks = "1 month"         # 标签间隔（如 "2 weeks"）
    # )+
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 10,face = "bold"),
      axis.title.y = element_text(size = 10,face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90),
      legend.position = "right")+guides(color = "none") 
  
  # plot2
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  
}

plotfunctionByDay<- function(dfData,independentVariableName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = testDay, y = Count, text = paste( round(Count, 2)) ,fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
  # plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionBy区域<- function(dfData,independentVariableName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = 省编号, y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionBy仪器<- function(dfData,independentVariableName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = 仪器序列号, y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

plotfunctionBy仪器Log<- function(dfData,independentVariableName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  
  plot1<-ggplot(dfData00, aes(x = 仪器序列号, y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    scale_y_log10()+
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
  #return (list(plotdfDataNumber,b23,b33,b43,b53))
  
}

panelPlotByDayAnd仪器<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$仪器序列号 %in% choosenList,]
  dfData00$仪器序列号<-factor(dfData00$仪器序列号,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testDay, y = Count, text = paste( round(Count, 2)) ,fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 仪器序列号,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

panelPlotByMonthAnd仪器<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$仪器序列号 %in% choosenList,]
  dfData00$仪器序列号<-factor(dfData00$仪器序列号,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testMonth, y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 仪器序列号,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

panelPlotByDayAnd仪器<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$仪器序列号 %in% choosenList,]
  dfData00$仪器序列号<-factor(dfData00$仪器序列号,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testDay, y = Count, text = paste( round(Count, 2)) ,fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 仪器序列号,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

panelPlotByMonthAnd仪器<- function(dfData,choosenList,independentVariableName,panelName,dependentVariableNames,titleNames) {
  lth1<-length(dependentVariableNames)
  dfData00<-data.frame()
  for(i in 1:lth1){
    dfData0<-cbind(dependentVariableNames[i],dfData[,c(independentVariableName,panelName,dependentVariableNames[i])])
    colnames(dfData0)<-c("Group",c(independentVariableName,panelName,"Count"))
    dfData00<-rbind(dfData00,dfData0)
  }
  dfData00<-dfData00[dfData00$仪器序列号 %in% choosenList,]
  dfData00$仪器序列号<-factor(dfData00$仪器序列号,levels = choosenList)
  
  plot1<-ggplot(dfData00, aes(x = testMonth, y = Count,text = paste( round(Count, 2)) , fill = Group)) +
    geom_col(
      position = position_dodge(width = 0.4),  # 控制条间距
      width = 0.7  # 条宽度
    ) +
    geom_line(
      aes(group = Group, color = Group),
      position = position_dodge(width = 0.4),
      linewidth = 1,
      linetype="dashed",
      show.legend=FALSE,
      alpha = 1.0
    ) +  
    scale_color_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    # geom_text(
    #   aes(label = round(Count,2)),         # 标签内容
    #   position = position_dodge(width = 0.4),  # 与柱子位置一致
    #   vjust = -0.4,               # 垂直位置（负值向上）
    #   color = "black",            # 标签颜色
    #   size = 1.2                    # 字体大小
    # ) +
    facet_wrap( ~ 仪器序列号,ncol=2) +
    labs(
      title = titleNames[1],
      x = titleNames[2],
      y = titleNames[3],
      fill = titleNames[4]
    ) +
    scale_fill_manual(values = c("red", "blue","green","yellow")) +  # 自定义颜色
    theme_minimal() + theme(
      plot.title = element_text(size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(size = 12, face = "bold"),
      axis.title.y = element_text(size = 12, face = "bold"),
      axis.text.x = element_text(size = 8, face = "bold",angle=90) ,
      panel.border = element_rect(
        color = "black",   # 边框颜色
        linewidth = 1.,        # 边框粗细
        linetype = "solid", # 线型（solid/dashed/dotted）
        fill = NA          # 填充色（NA为透明）
      ),
      legend.position = "right")+guides(color = "none") 
  
  #plot1
  
  # Convert to interactive plot
  plot1<-ggplotly(plot1, tooltip = "text")
  return (plot1)
}

running_avg <- function(x, window = 3) {
  sapply(seq_along(x), function(i) {
    start <- max(1, i - window + 1)
    mean(x[start:i],na.rm=TRUE)
  })
}

lumping_avg<- function(x,window = 100) {
  sapply(seq_along(x), function(i) {
    start <- max(1, i - window + 1)
    mean(x[start:i],na.rm=TRUE)
  })
}

lumping_sd<- function(x,window = 100) {
  sapply(seq_along(x), function(i) {
    start <- max(1, i - window + 1)
    sd(x[start:i],na.rm=TRUE)
  })
}
rep6<-rep(1,6)
rep50<-rep(1,50)
rep0<-rep6
for(i in 1:1000) rep0<-c(rep0,rep6+i)
rep00<-rep50
for(i in 1:100) rep00<-c(rep00,rep50+i)

if(FALSE){
  csv_files <- list.files(pattern = "\\UTF.csv$")
  
  df00<-data.frame()
  
  for(i in 1:length(csv_files)) {
    #guess_encoding("historyRecord20.csv") # [[1]]$encoding 
    #df2 <- fread("historyRecord20250604175205UTF.csv",encoding = "UTF-8",fill = TRUE)
    # df22 <- read.csv(csv_files[i],encoding = "UTF-8",fill = TRUE)
    # colnames(df22)
    # summary(df22)
    df2 <- read.csv(csv_files[i],encoding = "UTF-8",fill = TRUE)
    df2$批次名称<-as.character(df2$批次名称)
    df2<-df2[!is.na(df2$批次名称),]
    
    df2$是否阳性<-df2$结论
    df2$是否阳性[df2$是否阳性=="阳性"]<-1.0
    df2$是否阳性[df2$是否阳性=="阴性"]<-0.0
    df2$是否阳性[df2$是否阳性=="无效"]<-0.5
    df2$是否阳性<-as.numeric(df2$是否阳性)
    df2$是否阳性[is.na(df2$是否阳性)]<-0.5
    
    df2$结论[df2$结论=="阳性"]<-1.0
    df2$结论[df2$结论=="阴性"]<-0.0
    df2$结论<-as.numeric(df2$结论)
    
    df2$是否有效<-1
    df2$是否有效[df2$是否阳性==0.5]<-0
    
    df00<-rbind(df00,df2)
  }
  write_excel_csv(df00,file="history06092025.csv")
  
  df2<-df00
  
} 
if(FALSE){
  series<-read.csv("荧光层析设备1.csv",encoding = "UTF-8",fill = TRUE)
  series1<-read.csv("FIC-Q100N.csv",encoding = "UTF-8",fill = TRUE)
  series0<-series$仪器序列号[series$仪器序列号 %in% 仪器号List$仪器序列号]
  series00<-series$仪器编号[series$仪器编号 %in% series1$仪器编号]
  colnames(series[,1:13])
  colnames(series1[,3:11])
  仪器编号和序列号<-merge(series[,1:13],series1[,3:11],by="仪器编号",all=FALSE)
  #仪器编号和序列号all<-merge(series[,1:13],series1[,3:11],by="仪器编号",all=TRUE)
  colnames(仪器编号和序列号)
  仪器编号和序列号$SIM卡号<- gsub("\t", " ", 仪器编号和序列号$SIM卡号)
  仪器编号和序列号$返利表序号<- gsub("\n", "_", 仪器编号和序列号$返利表序号)
  #仪器编号和序列号all$SIM卡号<- gsub("\t", " ", 仪器编号和序列号all$SIM卡号)
  #仪器编号和序列号all$返利表序号<- gsub("\n", "_", 仪器编号和序列号all$返利表序号)
  #仪器编号和序列号[仪器编号和序列号$仪器序列号=="781be43bb68f05bb",]
  
  cname0<-c("仪器编号"  ,       "仪器序列号"  ,    
            "SIM卡号"  ,        "发货时间"   ,      "仪器类型"   ,     
            "总测试量"   ,      "最后一次开机时间" ,"时间差"   ,       
            "开机地点"  ,       "网络类型" ,        "ip地址"    ,      
            "用户"  ,           "用户CRM"   ,       "返利表序号"  ,    
            "申请日期"  ,       "区域"     ,        "客户编码"  ,      
            "代理商名称" ,      "用户名称"   ,      "规格" ,           
            "状态")
  #write_excel_csv(仪器编号和序列号all[,cname0],file="仪器编号和序列号all.csv")
  write_excel_csv(仪器编号和序列号[,cname0],file="仪器编号和序列号.csv")
}
if(FALSE){
  series<-read.csv("荧光层析设备1.csv",encoding = "UTF-8",fill = TRUE)
  series1<-read.csv("FIC-Q100N20250710.csv",encoding = "UTF-8",fill = TRUE)
  series0<-series$仪器序列号[series$仪器序列号 %in% 仪器号List$仪器序列号]
  series00<-series$仪器编号[series$仪器编号 %in% series1$仪器编号]
  colnames(series)[1:13]
  colnames(series1)[3:11]
  仪器编号和序列号0<-merge(series[,1:13],series1[,3:11],by="仪器编号",all=FALSE)
  仪器编号和序列号1<-merge(series[,1:13],series1[,3:11],by="仪器编号",all=TRUE)
  仪器编号和序列号2<-merge(series[,1:13],series1[,3:11],by="仪器编号",all.y=TRUE,all.x=FALSE)
  unique编号1<-unique(仪器编号和序列号1$仪器编号)
  unique序列号1<-unique(仪器编号和序列号1$仪器序列号)
  unique编号2<-unique(仪器编号和序列号2$仪器编号)
  unique序列号2<-unique(仪器编号和序列号2$仪器序列号)
  #仪器编号和序列号all<-merge(series[,1:13],series1[,3:11],by="仪器编号",all=TRUE)
  colnames(仪器编号和序列号1)
  仪器编号和序列号0$SIM卡号<- gsub("\t", " ", 仪器编号和序列号0$SIM卡号)
  仪器编号和序列号0$返利表序号<- gsub("\n", "_", 仪器编号和序列号0$返利表序号)
  仪器编号和序列号1$SIM卡号<- gsub("\t", " ", 仪器编号和序列号1$SIM卡号)
  仪器编号和序列号1$返利表序号<- gsub("\n", "_", 仪器编号和序列号1$返利表序号)
  #仪器编号和序列号all$SIM卡号<- gsub("\t", " ", 仪器编号和序列号all$SIM卡号)
  #仪器编号和序列号all$返利表序号<- gsub("\n", "_", 仪器编号和序列号all$返利表序号)
  #仪器编号和序列号[仪器编号和序列号$仪器序列号=="781be43bb68f05bb",]
  仪器编号和序列号1e<-仪器编号和序列号1[complete.cases(仪器编号和序列号1$区域),]
  
  cname0<-c("仪器编号"  ,       "仪器序列号"  ,    
            "SIM卡号"  ,        "发货时间"   ,      "仪器类型"   ,     
            "总测试量"   ,      "最后一次开机时间" ,"时间差"   ,       
            "开机地点"  ,       "网络类型" ,        "ip地址"    ,      
            "用户"  ,           "用户CRM"   ,       "返利表序号"  ,    
            "申请日期"  ,       "区域"     ,        "客户编码"  ,      
            "代理商名称" ,      "用户名称"   ,      "规格" ,           
            "状态")
  #write_excel_csv(仪器编号和序列号all[,cname0],file="仪器编号和序列号all.csv")
  write_excel_csv(仪器编号和序列号1[,cname0],file="仪器编号和序列号1.csv")
  
  mydb = dbConnect(MySQL(), user='root', password='My9521$$', dbname='和迈', host='192.168.11.223')
  dbWriteTable(mydb, name='仪器编号和序列号1', value=仪器编号和序列号1)
  dbDisconnect(mydb)
  
  write_excel_csv(仪器编号和序列号1e[,cname0],file="仪器编号和序列号1e.csv")
  
  mydb = dbConnect(MySQL(), user='root', password='My9521$$', dbname='和迈', host='192.168.11.223')
  dbWriteTable(mydb, name='仪器编号和序列号1e', value=仪器编号和序列号1e)
  dbDisconnect(mydb)
  
  Numberof区域<-length(unique(仪器编号和序列号1e$区域))
  listOfUnique细胞<-""
  for(j in 1:Numberof区域) listOfUnique细胞<-paste(listOfUnique细胞,unique(仪器编号和序列号1e$区域)[j],sep="___")
  细胞<-data.frame(cbind(1:Numberof区域,unique(df2andInf$区域)))
  colnames(细胞)<-c("ID","细胞")
  
  write_excel_csv(细胞,file="细胞.csv")
  
  细胞1<-细胞[str_length(细胞$细胞)<=3,]
  
  similiar<-str_like(细胞$细胞,paste(paste("%",细胞1$细胞[3],sep=""),"%",sep=""), ignore_case = TRUE)
  细胞$细胞[30]
  细胞$细胞[43]
  细胞$细胞[30]<-细胞$细胞[43]
  similiar<-str_like(细胞$细胞,paste(paste("%",细胞1$细胞[4],sep=""),"%",sep=""), ignore_case = TRUE)
  细胞$细胞[9]
  细胞$细胞[45]
  细胞$细胞[45]<-细胞$细胞[9]
  similiar<-str_like(细胞$细胞,paste(paste("%",细胞1$细胞[5],sep=""),"%",sep=""), ignore_case = TRUE)
  细胞$细胞[17]
  细胞$细胞[46]
  细胞$细胞[46]<-细胞$细胞[17]
  similiar<-str_like(细胞$细胞,paste(paste("%",细胞1$细胞[6],sep=""),"%",sep=""), ignore_case = TRUE)
  细胞$细胞[11]
  细胞$细胞[47]
  细胞$细胞[47]<-细胞$细胞[11]
  similiar<-str_like(细胞$细胞,paste(paste("%",细胞1$细胞[7],sep=""),"%",sep=""), ignore_case = TRUE)
  细胞$细胞[14]
  细胞$细胞[54]
  细胞$细胞[54]<-细胞$细胞[14]
  similiar<-str_like(细胞$细胞,paste(paste("%",细胞1$细胞[8],sep=""),"%",sep=""), ignore_case = TRUE)
  细胞$细胞[63]
  细胞$细胞[34]
  细胞$细胞[63]<-细胞$细胞[34]
  
  unique(细胞$细胞)
  仪器编号和序列号1m<-仪器编号和序列号1e
  
  仪器编号和序列号1m$区域[ str_like(仪器编号和序列号1m$区域,paste(paste("%",细胞1$细胞[3],sep=""),"%",sep=""), ignore_case = TRUE)]<-细胞$细胞[43]
  仪器编号和序列号1m$区域[ str_like(仪器编号和序列号1m$区域,paste(paste("%",细胞1$细胞[4],sep=""),"%",sep=""), ignore_case = TRUE)]<-细胞$细胞[9]
  仪器编号和序列号1m$区域[ str_like(仪器编号和序列号1m$区域,paste(paste("%",细胞1$细胞[5],sep=""),"%",sep=""), ignore_case = TRUE)]<-细胞$细胞[17]
  仪器编号和序列号1m$区域[ str_like(仪器编号和序列号1m$区域,paste(paste("%",细胞1$细胞[6],sep=""),"%",sep=""), ignore_case = TRUE)]<-细胞$细胞[11]
  仪器编号和序列号1m$区域[ str_like(仪器编号和序列号1m$区域,paste(paste("%",细胞1$细胞[7],sep=""),"%",sep=""), ignore_case = TRUE)]<-细胞$细胞[14]
  仪器编号和序列号1m$区域[ str_like(仪器编号和序列号1m$区域,paste(paste("%",细胞1$细胞[8],sep=""),"%",sep=""), ignore_case = TRUE)]<-细胞$细胞[34]
  
  仪器编号和序列号$小细胞[str_like(仪器编号和序列号$小细胞,paste(paste("%","陈凯 华中",sep=""),"%",sep=""), ignore_case = TRUE)]<-"华中 陈凯"
  
  unique(仪器编号和序列号$小细胞)
  
  write_excel_csv(仪器编号和序列号1m[,cname0],file="仪器编号和序列号1m.csv")
  
  mydb = dbConnect(MySQL(), user='root', password='My9521$$', dbname='和迈', host='192.168.11.223')
  dbWriteTable(mydb, name='仪器编号和序列号1m', value=仪器编号和序列号[,2:22])
  dbDisconnect(mydb)
  
  Numberof区域<-length(unique(仪器编号和序列号1m$小细胞))
  listOfUnique细胞<-""
  for(j in 1:Numberof区域) listOfUnique细胞<-paste(listOfUnique细胞,unique(仪器编号和序列号1m$小细胞)[j],sep="___")
  细胞m<-data.frame(cbind(1:Numberof区域,unique(df2andInf$小细胞)))
  colnames(细胞m)<-c("ID","细胞")
  
  write_excel_csv(细胞m,file="细胞m.csv")
}

mydb = dbConnect(MySQL(), user='root', password='My9521$$', dbname='和迈', host='192.168.11.223')
dbListTables(mydb)
#dbListFields(mydb, '测试数据')

#仪器编号和序列号all<-read.csv("仪器编号和序列号all.csv",encoding = "UTF-8",fill = TRUE)

#仪器编号和序列号<-read.csv("仪器编号和序列号.csv",encoding = "UTF-8",fill = TRUE)
rs = dbSendQuery(mydb, "select * from  和迈.仪器编号和序列号1m ")
仪器编号和序列号 = fetch(rs, n=-1)
仪器编号和序列号<-仪器编号和序列号[!duplicated(仪器编号和序列号[,c("仪器编号","仪器序列号" )]),]
colnames(仪器编号和序列号)
#仪器编号和序列号<-distinct(仪器编号和序列号[,2:22])
#仪器编号和序列号<-read.csv("仪器编号和序列号.csv",encoding = "UTF-8",fill = TRUE)

rs = dbSendQuery(mydb, "select * from  和迈.和迈测试数据 ")
df2 = fetch(rs, n=-1)
dbDisconnect(mydb)

#df2 = fetch(rs, n=-1)
#df2 <- read.csv("history06092025.csv",encoding = "UTF-8",fill = TRUE)
colnames(df2)
cname00<-c( "序号" ,        "项目号"   ,    "批次号" ,      "样品编号" ,  
            "项目名称" ,    "批次名称" ,    "测试时间" ,    "浓度1"  ,     
            "结论"  ,       "C值"   ,       "T值"  ,        "浓度2" ,      
            "浓度3" ,       "结论2"  ,      "结论3"  ,      "样本类型"  ,  
            "省市编号"  ,   "仪器序列号" ,  "T2值"  ,       "T3值"  ,      
            "仪器备注名称", "仪器投放区域", "详细地址")
df2<-distinct(df2[,cname00])
df2$批次名称<-as.character(df2$批次名称)
df2<-df2[!is.na(df2$批次名称),]

df2andInf<-merge(df2,仪器编号和序列号[,c("仪器编号","仪器序列号","发货时间" ,"申请日期" ,       
                                 "小细胞"   ,          "客户编码"   ,      "代理商名称" ,     
                                 "用户名称" ,        "规格"   ,          "状态")],by="仪器序列号",all.x=TRUE,all.y=FALSE)

df2andInf$省编号<-(df2andInf$省市编号 %/% 10000)*10000
df2andInf$省名<-str_sub(df2andInf$详细地址,1,3)
df2andInf$省名[str_length(df2andInf$省名)<3]<-NA

df2andInf$省名[str_like(df2andInf$省编号,paste(paste("%","120000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"天津市"
df2andInf$省名[str_like(df2andInf$省编号,paste(paste("%","230000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"黑龙江"
df2andInf$省名[str_like(df2andInf$省编号,paste(paste("%","320000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"江苏省"
df2andInf$省名[str_like(df2andInf$省编号,paste(paste("%","420000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"湖北省"
df2andInf$省名[str_like(df2andInf$省编号,paste(paste("%","510000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"四川省"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","重庆市",sep=""),"%",sep=""), ignore_case = TRUE)]<-"500000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","广西壮",sep=""),"%",sep=""), ignore_case = TRUE)]<-"450000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","江西省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"360000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","北京市",sep=""),"%",sep=""), ignore_case = TRUE)]<-"110000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","河北省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"130000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","上海市",sep=""),"%",sep=""), ignore_case = TRUE)]<-"310000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","浙江省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"330000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","四川省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"510000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","安徽省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"340000"
df2andInf$省编号[str_like(df2andInf$省名,paste(paste("%","贵州省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"520000"

df2andInf<-distinct(df2andInf)

#df2andInf0<-df2andInf[str_c(df2andInf$仪器编号, df2andInf$仪器序列号)!=NA,]



df2andInf$是否阳性<-df2andInf$结论
df2andInf$是否阳性[df2andInf$是否阳性=="阳性"]<-1.0
df2andInf$是否阳性[df2andInf$是否阳性=="阴性"]<-0.0
df2andInf$是否阳性[df2andInf$是否阳性=="无效"]<-0.5
df2andInf$是否阳性<-as.numeric(df2andInf$是否阳性)
df2andInf$是否阳性[is.na(df2andInf$是否阳性)]<-0.5

df2andInf$结论[df2andInf$结论=="阳性"]<-1.0
df2andInf$结论[df2andInf$结论=="阴性"]<-0.0
df2andInf$结论<-as.numeric(df2andInf$结论)

df2andInf$是否有效<-1
df2andInf$是否有效[df2andInf$是否阳性==0.5]<-0

Numberof项目号<-length(unique(df2andInf$项目号))
Numberof批次号<-length(unique(df2andInf$批次号))
Numberof样品编号<-length(unique(df2andInf$样品编号))
Numberof项目名称<-length(unique(df2andInf$项目名称))
Numberof批次名称<-length(unique(df2andInf$批次名称))
Numberof省编号<-length(unique(df2andInf$省编号))
Numberof省名<-length(unique(df2andInf$省名))
Numberof省市编号<-length(unique(df2andInf$省市编号))
Numberof仪器序列号<-length(unique(df2andInf$仪器序列号))
Numberof详细地址<-length(unique(df2andInf$详细地址))
Numberof小细胞<-length(unique(df2andInf$小细胞))
Numberof仪器备注名称<-length(unique(df2andInf$仪器备注名称))
Numberof仪器投放区域<-length(unique(df2andInf$仪器投放区域))
Numberof样本类型<-length(unique(df2andInf$样本类型))


if(FALSE){
  省编号and省名<-data.frame(cbind(df2andInf$省编号,df2andInf$省名))
  colnames(省编号and省名)<-c("省编号","省名")
  省编号and省名<-省编号and省名[!duplicated(省编号and省名),]
  省编号and省名<-省编号and省名[order(省编号and省名$省编号),]
  省编号and省名$省名[str_like(省编号and省名$省编号,paste(paste("%","120000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"天津市"
  省编号and省名$省名[str_like(省编号and省名$省编号,paste(paste("%","230000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"黑龙江"
  省编号and省名$省名[str_like(省编号and省名$省编号,paste(paste("%","320000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"江苏省"
  省编号and省名$省名[str_like(省编号and省名$省编号,paste(paste("%","420000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"湖北省"
  省编号and省名$省名[str_like(省编号and省名$省编号,paste(paste("%","510000",sep=""),"%",sep=""), ignore_case = TRUE)]<-"四川省"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","重庆市",sep=""),"%",sep=""), ignore_case = TRUE)]<-"500000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","广西壮",sep=""),"%",sep=""), ignore_case = TRUE)]<-"450000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","江西省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"360000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","北京市",sep=""),"%",sep=""), ignore_case = TRUE)]<-"110000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","河北省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"130000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","上海市",sep=""),"%",sep=""), ignore_case = TRUE)]<-"310000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","浙江省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"330000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","四川省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"510000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","安徽省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"340000"
  省编号and省名$省编号[str_like(省编号and省名$省名,paste(paste("%","贵州省",sep=""),"%",sep=""), ignore_case = TRUE)]<-"520000"
  省编号and省名<-省编号and省名[!duplicated(省编号and省名),]
}

summaryTable<-stri_join("Numberof测试: ",as.character(nrow(df2andInf)),
                        "\nNumberof项目名称: ", as.character(Numberof项目名称),
                        "\nNumberof批次号:  ",as.character(Numberof批次号), "  \n",
                        "Numberof样品编号：  ",as.character(Numberof样品编号),"  \n",
                        "Numberof批次名称:   ",as.character(Numberof批次名称),"  \n",
                        "Numberof省编号:   ",as.character(Numberof省编号),"  \n",
                        "Numberof省市编号:   ",as.character(Numberof省市编号),"  \n",
                        "Numberof仪器序列号:   ",as.character(Numberof仪器序列号),"  \n",
                        "Numberof详细地址:   ",as.character(Numberof详细地址),"  \n",
                        "Numberof小细胞:   ",as.character(Numberof小细胞),"  \n",
                        "Numberof样本类型:   ",as.character(Numberof样本类型),"  \n",sep="")
小细胞<-unique(df2andInf$小细胞)
Numberof小细胞<-length(小细胞)
细胞<-data.frame(cbind(1:Numberof小细胞,小细胞))
colnames(细胞)<-c("ID","细胞")
细胞0<-细胞[!(str_like(细胞$细胞,paste(paste("%","内部",sep=""),"%",sep=""), ignore_case = TRUE) |
            str_like(细胞$细胞,paste(paste("%","客服",sep=""),"%",sep=""), ignore_case = TRUE) |
            str_like(细胞$细胞,paste(paste("%","医学",sep=""),"%",sep=""), ignore_case = TRUE)  ),]
细胞0<-细胞0[!is.na(细胞0$细胞),]
细胞0$ID<-1:nrow(细胞0)
write_excel_csv(细胞0,file="细胞0.csv")

summary(df2andInf$结论)
summary(df2andInf$是否阳性)
summary(df2andInf$是否有效)

#df2andInf$仪器序列号_批次名称<-str_c(df2andInf$仪器序列号,'_',df2andInf$批次名称)


colnames(df2andInf)
#colnames(df00)
#df2andInf00<-df2andInf0
summary(df2andInf$仪器序列号)
summary(df2andInf$批次名称)


df20<-df2andInf #[,c(1:11,16,17,20)]
df20$省编号<-str_c("省编号: ",df20$省编号)
df20<-df20[complete.cases(df20$测试时间), ]
df20<-df20[str_length(df20$测试时间)>10, ]


colnames(df20)

df20$浓度1<-as.numeric(df20$浓度1)
df20$C值<-as.numeric(df20$C值)
df20$T值<-as.numeric(df20$T值)
df20$ToverC值<-df20$T值/df20$C值
df20$ToverC值[df20$是否有效==0]<-NA

summary(as.numeric(df20$结论))
summary(df20$浓度1)
summary(df20$ToverC值)

summary(df20$testTimeFromeBegining)
colnames(df20)


df20$testMonth<-str_sub(df20$测试时间,1,7)

#df20$testMonthinNumber<-as.numeric(str_c(str_sub(df20$测试时间,1,4),str_sub(df20$测试时间,6,7)))

df20$testDay<-as.Date(str_sub(df20$测试时间,1,10))
df20<-df20[df20$testDay<="2025-06-05", ]
#df20<-df20[df20$testDay<=Sys.Date(), ]

df20<-df20[complete.cases(df20$testDay), ]

summary(df20$testDay)

df20$testTime<-as.datetime(str_sub(df20$测试时间,1,19),format='%Y-%m-%d %H:%M:%S')

duration<-(max(df20$testTime,na.rm = TRUE)-min(df20$testTime,na.rm = TRUE))/(60.*60.*24.)

df20$testTimeFromeToday<-(max(df20$testTime,na.rm = TRUE)-df20$testTime)/(60.*60.*24.)+1.
#max0<-max(df20$testTime,na.rm=TRUE)
#min0<-min(df20$testTime,na.rm=TRUE)

#unique(dfBy样本$样本类型)
#max0-min0

#max(df20$testDay,na.rm=TRUE)
#min(df20$testDay,na.rm=TRUE)

#clean_df <- df20[complete.cases(df20[,c("小细胞")]), ]
#summary(clean_df)


summary(df20$testTimeFromeToday)
dayMax<-max(df20$testTimeFromeToday,na.rm = TRUE)


df2000<-df20
df20<-df20[df20$testTimeFromeToday<=730,]
#df20<-df20[complete.cases(df20$测试时间), ]
lastDay<-max(df20$testDay,na.rm = TRUE)
df20dayLast21<-df20[lastDay-df20$testDay<21,]


dfByDay <- df2000 %>%  group_by(testMonth,testDay) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByDay$阳性率<-round(dfByDay$阳性数/dfByDay$有效数,3)
dfByDay$有效率<-round(dfByDay$有效数/dfByDay$测试数,3)
dfByDay$阳性数<-as.integer(dfByDay$阳性数)
dfByDay$测试数<-as.integer(dfByDay$测试数)
dfByDay$有效数<-as.integer(dfByDay$有效数)
dfByDay$省数<-as.integer(dfByDay$省数)
dfByDay <- dfByDay[order(lastDay-dfByDay$testDay),]
#dfByDay <- dfByDay[lastDay-dfByDay$testDay<42,]
#dfByDay<-dfByDay[lastDay-dfByDay$testDay<=21,]

write_excel_csv(dfByDay,file="按日统计0.csv")

dfByMonth <- df2000 %>%  group_by(testMonth) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByMonth$阳性率<-round(dfByMonth$阳性数/dfByMonth$有效数,3)
dfByMonth$有效率<-round(dfByMonth$有效数/dfByMonth$测试数,3)
dfByMonth$阳性数<-as.integer(dfByMonth$阳性数)
dfByMonth$测试数<-as.integer(dfByMonth$测试数)
dfByMonth$有效数<-as.integer(dfByMonth$有效数)
dfByMonth$省数<-as.integer(dfByMonth$省数)
dfByMonth <- dfByMonth[order(dfByMonth$testMonth),]
dfByMonth <- dfByMonth[nrow(dfByMonth):1,]

write_excel_csv(dfByMonth,file="按月统计0.csv")

dfBy项目 <- df2000 %>%  group_by(项目名称) %>%  summarise(
  
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号)),
  
  测试开始 = round(max(testTimeFromeToday,na.rm = TRUE),2),
  测试截止 = round(min(testTimeFromeToday,na.rm = TRUE),2)
)
dfBy项目$阳性率<-round(dfBy项目$阳性数/dfBy项目$有效数,3)
dfBy项目$有效率<-round(dfBy项目$有效数/dfBy项目$测试数,3)
dfBy项目$阳性数<-as.integer(dfBy项目$阳性数)
dfBy项目$测试数<-as.integer(dfBy项目$测试数)
dfBy项目$有效数<-as.integer(dfBy项目$有效数)
dfBy项目 <- dfBy项目[order(-dfBy项目$测试数),]
write_excel_csv(dfBy项目,file="按项目统计0.csv")

dfBy样本 <- df2000 %>%  group_by(样本类型) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号)),
  测试开始 = round(max(testTimeFromeToday,na.rm = TRUE),2),
  测试截止 = round(min(testTimeFromeToday,na.rm = TRUE),2)
)
dfBy样本$阳性率<-round(dfBy样本$阳性数/dfBy样本$有效数,3)
dfBy样本$有效率<-round(dfBy样本$有效数/dfBy样本$测试数,3)
dfBy样本$阳性数<-as.integer(dfBy样本$阳性数)
dfBy样本$测试数<-as.integer(dfBy样本$测试数)
dfBy样本$有效数<-as.integer(dfBy样本$有效数)
dfBy样本 <- dfBy样本[order(-dfBy样本$测试数),]
write_excel_csv(dfBy样本,file="按样本统计0.csv")

dfBy细胞 <- df2000 %>%  group_by(小细胞) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号)),
  测试开始 = round(max(testTimeFromeToday,na.rm = TRUE),2),
  测试截止 = round(min(testTimeFromeToday,na.rm = TRUE),2)
)
dfBy细胞$阳性率<-round(dfBy细胞$阳性数/dfBy细胞$有效数,3)
dfBy细胞$有效率<-round(dfBy细胞$有效数/dfBy细胞$测试数,3)
dfBy细胞$阳性数<-as.integer(dfBy细胞$阳性数)
dfBy细胞$测试数<-as.integer(dfBy细胞$测试数)
dfBy细胞$有效数<-as.integer(dfBy细胞$有效数)
dfBy细胞 <- dfBy细胞[order(-dfBy细胞$测试数),]
write_excel_csv(dfBy细胞,file="按细胞统计0.csv")

dfBy区域 <- df2000 %>%  group_by(省编号) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号)),
  测试开始 = round(max(testTimeFromeToday,na.rm = TRUE),2),
  测试截止 = round(min(testTimeFromeToday,na.rm = TRUE),2)
)
dfBy区域$阳性率<-round(dfBy区域$阳性数/dfBy区域$有效数,3)
dfBy区域$有效率<-round(dfBy区域$有效数/dfBy区域$测试数,3)
dfBy区域$阳性数<-as.integer(dfBy区域$阳性数)
dfBy区域$测试数<-as.integer(dfBy区域$测试数)
dfBy区域$有效数<-as.integer(dfBy区域$有效数)
dfBy区域 <- dfBy区域[order(-dfBy区域$测试数),]
write_excel_csv(dfBy区域,file="按区域统计0.csv")

省编号<-dfBy区域$省编号
省编号0<-省编号[str_length(省编号)>8]
dfBy区域<-dfBy区域[dfBy区域$省编号  %in% 省编号0,]

dfBy批次 <- df2000 %>%  group_by(批次名称) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号)),
  最早测试=min(testDay,na.rm = TRUE),
  最近测试=max(testDay,na.rm = TRUE),
  测试开始 = round(max(testTimeFromeToday,na.rm = TRUE),2),
  测试截止 = round(min(testTimeFromeToday,na.rm = TRUE),2)
)
dfBy批次$阳性率<-round(dfBy批次$阳性数/dfBy批次$有效数,3)
dfBy批次$有效率<-round(dfBy批次$有效数/dfBy批次$测试数,3)
dfBy批次$阳性数<-as.integer(dfBy批次$阳性数)
dfBy批次$测试数<-as.integer(dfBy批次$测试数)
dfBy批次$有效数<-as.integer(dfBy批次$有效数)
dfBy批次$省数<-as.integer(dfBy批次$省数)
dfBy批次 <- dfBy批次[order(-dfBy批次$测试数),]
write_excel_csv(dfBy批次,file="按批次统计0.csv")

df20001<-cbind(df2000,IDIndex=1:nrow(df2000))
dfBy仪器 <- df20001 %>%  group_by(仪器序列号) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号)),
  earliestIndex=min(IDIndex),
  medianIndex=median(IDIndex),
  latestIndex=max(IDIndex),
  最早测试=min(testDay,na.rm = TRUE),
  最近测试=max(testDay,na.rm = TRUE),
  测试开始 = round(max(testTimeFromeToday,na.rm = TRUE),2),
  测试截止 = round(min(testTimeFromeToday,na.rm = TRUE),2)
)
dfBy仪器$阳性率<-round(dfBy仪器$阳性数/dfBy仪器$有效数,3)
dfBy仪器$有效率<-round(dfBy仪器$有效数/dfBy仪器$测试数,3)
dfBy仪器$阳性数<-as.integer(dfBy仪器$阳性数)
dfBy仪器$测试数<-as.integer(dfBy仪器$测试数)
dfBy仪器$有效数<-as.integer(dfBy仪器$有效数)

dfBy仪器$最早测试地点<-df2000$详细地址[dfBy仪器$earliestIndex]
dfBy仪器$中期测试地点<-df2000$详细地址[dfBy仪器$medianIndex]
dfBy仪器$最后测试地点<-df2000$详细地址[dfBy仪器$latestIndex]
dfBy仪器 <- dfBy仪器[order(-dfBy仪器$测试数),]
cname0<-c( "仪器序列号"  ,"最早测试地点","中期测试地点", "最后测试地点",      
           "批次数"  ,   "测试数"  ,   "样本数"  ,   "项目数" ,   
           "阳性数",     "有效数"  ,   "最早测试" ,  "最近测试" ,  "测试开始" , 
           "测试截止",   "阳性率" ,    "有效率") 

write_excel_csv(dfBy仪器[,cname0],file="按仪器统计0.csv")

cname0<-c( "仪器序列号"  ,"仪器编号"  ,"最早测试地点","中期测试地点", "最后测试地点",      
           "开机地点"  ,  "批次数"  ,   "测试数"  ,   "样本数"  ,   "项目数" ,   
           "阳性数",     "有效数"  ,   "最早测试" ,  "最近测试" ,  "测试开始" , 
           "测试截止",   "阳性率" ,    "有效率",  
           "SIM卡号"  ,        "发货时间"   ,      "仪器类型"   ,     
           "总测试量"   ,      "最后一次开机时间" ,"时间差"   ,       
           "网络类型" ,        "ip地址"    ,      
           "用户"  ,           "用户CRM"   ,       "返利表序号"  ,    
           "申请日期"  ,       "小细胞"     ,        "客户编码"  ,      
           "代理商名称" ,      "用户名称"   ,      "规格" ,           
           "状态")
colnames(dfBy仪器)
dfBy仪器andInf<-merge(dfBy仪器,仪器编号和序列号,by="仪器序列号",all.x=TRUE,all.y=FALSE)
colnames(dfBy仪器andInf)
dfBy仪器andInf <- dfBy仪器andInf[order(-dfBy仪器andInf$测试截止),][,cname0]
#dfBy仪器andInf0<-distinct(dfBy仪器andInf)
write_excel_csv(dfBy仪器andInf,file="仪器统计andInf.csv")
dfBy仪器andInfall<-merge(dfBy仪器,仪器编号和序列号,by="仪器序列号",all.x=TRUE,all.y=TRUE)
dfBy仪器andInfall <- dfBy仪器andInfall[order(-dfBy仪器andInfall$测试截止),][,cname0]
#dfBy仪器andInfall0<-distinct(dfBy仪器andInfall)
write_excel_csv(dfBy仪器andInfall,file="仪器统计andInfall.csv")
colnames(仪器编号和序列号)
notFound<-仪器编号和序列号[!(仪器编号和序列号$仪器序列号 %in% dfBy仪器$仪器序列号),]

colnames(notFound)

cname1<-c( "仪器序列号"  ,"仪器编号"  ,     
           "开机地点"  ,  
           "SIM卡号"  ,        "发货时间"   ,      "仪器类型"   ,     
           "总测试量"   ,      "最后一次开机时间" ,"时间差"   ,       
           "网络类型" ,        "ip地址"    ,      
           "用户"  ,           "用户CRM"   ,       "返利表序号"  ,    
           "申请日期"  ,       "小细胞"     ,        "客户编码"  ,      
           "代理商名称" ,      "用户名称"   ,      "规格" ,           
           "状态")
#notFound[,cname1]
#notFound0<-distinct(notFound)
write_excel_csv(notFound[,cname1],file="仪器统计Notfound.csv")

if(FALSE) {
  CRMNotFound <- read.csv("CRMNotFound.csv",encoding = "UTF-8",fill = TRUE)
  NoTestSince05012025 <- read.csv("NoTestSince05012025.csv",encoding = "UTF-8",fill = TRUE)
  colnames(CRMNotFound)[c(3,4,5)]<-c("销售申请时间NoCRM","销售申请区域NoCRM","销售申请时代理商名称NoCRM")
  colnames(NoTestSince05012025) [9]<-"备注NoTest"
  
  feedbackData<-merge(CRMNotFound,NoTestSince05012025,by="仪器编号",all.x=TRUE,all.y=TRUE)
  colnames(feedbackData)
  colnames(feedbackData)[10]<-"用户onCRM"
  
  write_excel_csv(feedbackData,file="feedbackData07042025.csv")
  仪器编号和序列号feedbackData<-merge(仪器编号和序列号,feedbackData,by="仪器编号",all.x=TRUE,all.y=TRUE)
  colnames(仪器编号和序列号feedbackData)
  
  dfBy仪器feedbackDataandInf<-merge(dfBy仪器,仪器编号和序列号feedbackData,by="仪器序列号",all.x=TRUE,all.y=FALSE)
  colnames(dfBy仪器feedbackDataandInf)
  cname0<-c( "仪器序列号"  ,"仪器编号"  ,"最早测试地点","中期测试地点", "最后测试地点",      
             "开机地点"  ,  "批次数"  ,   "测试数"  ,   "样本数"  ,   "项目数" ,   
             "阳性数",     "有效数"  ,   "最早测试" ,  "最近测试" ,  "测试开始" , 
             "测试截止",   "阳性率" ,    "有效率",  
             "SIM卡号"  ,        "发货时间"   ,      "仪器类型"   ,     
             "总测试量"   ,      "最后一次开机时间" ,"时间差"   ,       
             "网络类型" ,        "ip地址"    ,      
             "用户"  ,           "用户CRM"   ,       "返利表序号"  ,    
             "申请日期"  ,       "小细胞"     ,        "客户编码"  ,      
             "代理商名称" ,      "用户名称"   ,      "规格" ,           
             "状态","销售申请时间" ,             "销售申请时间NoCRM"   ,     
             "销售申请区域NoCRM"   ,      "销售申请时代理商名称NoCRM",
             "是否装机" ,                 "未装机原因"  ,             
             "备注"   ,                   "最后测试时间"  ,           
             "用户onCRM"     ,            "销售申请日期"   ,          
             "销售申请区域"   ,           "销售申请时代理商名称"  ,   
             "销售申请时用户名称"    ,    "无测试原因"  ,             
             "备注NoTest"   )
  dfBy仪器feedbackDataandInf <- dfBy仪器feedbackDataandInf[order(-dfBy仪器feedbackDataandInf$测试截止),][,cname0]
  write_excel_csv(dfBy仪器feedbackDataandInf,file="仪器统计feedbackandInf.csv")
  dfBy仪器feedbackDataandInfall<-merge(dfBy仪器,仪器编号和序列号feedbackData,by="仪器序列号",all.x=TRUE,all.y=TRUE)
  dfBy仪器feedbackDataandInfall <- dfBy仪器feedbackDataandInfall[order(-dfBy仪器feedbackDataandInfall$测试截止),][,cname0]
  write_excel_csv(dfBy仪器feedbackDataandInfall,file="仪器统计feedbackandInfall.csv")
  colnames(仪器编号和序列号feedbackData)
  notFoundfeedBack<-仪器编号和序列号feedbackData[!(仪器编号和序列号feedbackData$仪器序列号 %in% dfBy仪器$仪器序列号),]
  
  cname1<-c( "仪器序列号"  ,"仪器编号"  ,     
             "开机地点"  ,  
             "SIM卡号"  ,        "发货时间"   ,      "仪器类型"   ,     
             "总测试量"   ,      "最后一次开机时间" ,"时间差"   ,       
             "网络类型" ,        "ip地址"    ,      
             "用户"  ,           "用户CRM"   ,       "返利表序号"  ,    
             "申请日期"  ,       "小细胞"     ,        "客户编码"  ,      
             "代理商名称" ,      "用户名称"   ,      "规格" ,           
             "状态","销售申请时间" ,             "销售申请时间NoCRM"   ,     
             "销售申请区域NoCRM"   ,      "销售申请时代理商名称NoCRM",
             "是否装机" ,                 "未装机原因"  ,             
             "备注"   ,                   "最后测试时间"  ,           
             "用户onCRM"     ,            "销售申请日期"   ,          
             "销售申请区域"   ,           "销售申请时代理商名称"  ,   
             "销售申请时用户名称"    ,    "无测试原因"  ,             
             "备注NoTest" )
  
  colnames(notFoundfeedBack)
  
  write_excel_csv(notFoundfeedBack[,cname1],file="仪器统计NotfoundfeedBack.csv")
}

dfByDayAndLocation <- df2000 %>%  group_by(testDay,testMonth,省编号) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByDayAndLocation$阳性率<-round(dfByDayAndLocation$阳性数/dfByDayAndLocation$有效数,3)
dfByDayAndLocation$有效率<-round(dfByDayAndLocation$有效数/dfByDayAndLocation$测试数,3)
dfByDayAndLocation$阳性数<-as.integer(dfByDayAndLocation$阳性数)
dfByDayAndLocation$测试数<-as.integer(dfByDayAndLocation$测试数)
dfByDayAndLocation$有效数<-as.integer(dfByDayAndLocation$有效数)
dfByDayAndLocation <- dfByDayAndLocation[order(dfByDayAndLocation$testDay),]
dfByDayAndLocation<-dfByDayAndLocation[dfByDayAndLocation$省编号  %in% 省编号0,]

dfByMonthAndLocation <- df20 %>%  group_by(testMonth,省编号) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByMonthAndLocation$阳性率<-round(dfByMonthAndLocation$阳性数/dfByMonthAndLocation$有效数,3)
dfByMonthAndLocation$有效率<-round(dfByMonthAndLocation$有效数/dfByMonthAndLocation$测试数,3)
dfByMonthAndLocation$阳性数<-as.integer(dfByMonthAndLocation$阳性数)
dfByMonthAndLocation$测试数<-as.integer(dfByMonthAndLocation$测试数)
dfByMonthAndLocation$有效数<-as.integer(dfByMonthAndLocation$有效数)
dfByMonthAndLocation <- dfByMonthAndLocation[order(dfByMonthAndLocation$testMonth),]
dfByMonthAndLocation<-dfByMonthAndLocation[dfByMonthAndLocation$省编号  %in% 省编号0,]

dfByDayAnd细胞 <- df2000 %>%  group_by(testDay,testMonth,小细胞) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByDayAnd细胞$阳性率<-round(dfByDayAnd细胞$阳性数/dfByDayAnd细胞$有效数,3)
dfByDayAnd细胞$有效率<-round(dfByDayAnd细胞$有效数/dfByDayAnd细胞$测试数,3)
dfByDayAnd细胞$阳性数<-as.integer(dfByDayAnd细胞$阳性数)
dfByDayAnd细胞$测试数<-as.integer(dfByDayAnd细胞$测试数)
dfByDayAnd细胞$有效数<-as.integer(dfByDayAnd细胞$有效数)
dfByDayAnd细胞 <- dfByDayAnd细胞[order(dfByDayAnd细胞$testDay),]

dfByMonthAnd细胞 <- df20 %>%  group_by(testMonth,小细胞) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByMonthAnd细胞$阳性率<-round(dfByMonthAnd细胞$阳性数/dfByMonthAnd细胞$有效数,3)
dfByMonthAnd细胞$有效率<-round(dfByMonthAnd细胞$有效数/dfByMonthAnd细胞$测试数,3)
dfByMonthAnd细胞$阳性数<-as.integer(dfByMonthAnd细胞$阳性数)
dfByMonthAnd细胞$测试数<-as.integer(dfByMonthAnd细胞$测试数)
dfByMonthAnd细胞$有效数<-as.integer(dfByMonthAnd细胞$有效数)
dfByMonthAnd细胞 <- dfByMonthAnd细胞[order(dfByMonthAnd细胞$testMonth),]

dfByDayAnd仪器 <- df2000 %>%  group_by(testDay,testMonth,仪器序列号) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByDayAnd仪器$阳性率<-round(dfByDayAnd仪器$阳性数/dfByDayAnd仪器$有效数,3)
dfByDayAnd仪器$有效率<-round(dfByDayAnd仪器$有效数/dfByDayAnd仪器$测试数,3)
dfByDayAnd仪器$阳性数<-as.integer(dfByDayAnd仪器$阳性数)
dfByDayAnd仪器$测试数<-as.integer(dfByDayAnd仪器$测试数)
dfByDayAnd仪器$有效数<-as.integer(dfByDayAnd仪器$有效数)
dfByDayAnd仪器 <- dfByDayAnd仪器[order(dfByDayAnd仪器$testDay),]

dfByMonthAnd仪器 <- df20 %>%  group_by(testMonth,仪器序列号) %>%  summarise(
  测试数 = n(),
  阳性数=sum(结论,na.rm = TRUE),
  有效数=sum(是否有效,na.rm = TRUE),
  样本数=length(unique(样本类型)),
  项目数=length(unique(项目名称)),
  仪器数=length(unique(仪器序列号)),
  批次数=length(unique(批次名称)),
  小细胞数=length(unique(小细胞)),
  市数=length(unique(省市编号)),
  省数=length(unique(省编号))
)
dfByMonthAnd仪器$阳性率<-round(dfByMonthAnd仪器$阳性数/dfByMonthAnd仪器$有效数,3)
dfByMonthAnd仪器$有效率<-round(dfByMonthAnd仪器$有效数/dfByMonthAnd仪器$测试数,3)
dfByMonthAnd仪器$阳性数<-as.integer(dfByMonthAnd仪器$阳性数)
dfByMonthAnd仪器$测试数<-as.integer(dfByMonthAnd仪器$测试数)
dfByMonthAnd仪器$有效数<-as.integer(dfByMonthAnd仪器$有效数)
dfByMonthAnd仪器 <- dfByMonthAnd仪器[order(dfByMonthAnd仪器$testMonth),]

仪器号List0<-cbind(dfBy仪器,GroupID=rep00[1:length(dfBy仪器$仪器序列号)])
仪器号List<-仪器号List0[,c(1,ncol(仪器号List0))]
仪器号ikmax<-max(仪器号List$GroupID)
dfBy仪器$仪器序列号<-factor(dfBy仪器$仪器序列号,levels = 仪器号List[,1])
批次号List0<-cbind(dfBy批次,GroupID=rep00[1:length(dfBy批次$批次名称)])
批次号List<-批次号List0[,c(1,ncol(批次号List0))]
批次号ikmax<-max(批次号List$GroupID)
dfBy批次$批次名称<-factor(dfBy批次$批次名称,levels = 批次号List[,1])
项目号List0<-cbind(dfBy项目,GroupID=rep00[1:length(dfBy项目$项目名称)])
项目号List<-项目号List0[,c(1,ncol(项目号List0))]
项目号ikmax<-max(项目号List$GroupID)
dfBy项目$项目名称<-factor(dfBy项目$项目名称,levels = 项目号List[,1])

# 图表生成函数
dfByDay1<-dfByDay[lastDay-dfByDay$testDay<42,]
dfByDayAndLocation1<-dfByDayAndLocation[lastDay-dfByDayAndLocation$testDay<42,]
dfByMonth1<-dfByMonth[1:30,]

dfByDayAnd细胞1<-dfByDayAnd细胞[lastDay-dfByDayAnd细胞$testDay<42,]

lenhalf<-length(dfBy细胞$小细胞)/2
dfBy细胞1<-dfBy细胞[dfBy细胞$小细胞 %in% dfBy细胞$小细胞[1:lenhalf],]
dfBy细胞2<-dfBy细胞[dfBy细胞$小细胞 %in% dfBy细胞$小细胞[(1+lenhalf):length(dfBy细胞$小细胞)],]


generate_data_table <- function(dim, metric) {
  data <- switch(dim,
                 "按月统计" = read_csv("按月统计0.csv"),
                 "最后六周按日统计" = read_csv("按日统计0.csv"),
                 "按小细胞统计"=read_csv("按细胞统计0.csv"),
                 "按省统计" = read_csv("按区域统计0.csv"),
                 "按仪器统计" = read_csv("按仪器统计0.csv"),
                 "按样本类型统计" = read_csv("按样本统计0.csv"),
                 "按试剂批次统计" = read_csv("按批次统计0.csv"),
                 "按试剂项目统计" = read_csv("按项目统计0.csv"))

 
  metrics <- switch(metric,
                    "测试数、阳性数、有效数" = c("测试数", "阳性数", "有效数"),
                    "阳性率、有效率" = c("阳性率", "有效率"),
                    "项目数、仪器数、批次数" = c("批次数", "项目数", "仪器数"),
                    "省数、市数、小细胞数、样本数" = c("省数", "市数", "小细胞数","样本数"),
                    "测试截止、测试开始" = c("测试截止", "测试开始"))
  
  
  data %>% select(all_of(metrics))
}

generate_plot <- function(data, dim, metric, way, page = 1) {
  
#  cat(page)
  per    <- 6    # 每页子图数量
  if(!is.numeric(page)) offset<-6 else offset <- (page - 1) * per        # 起始下标
 # offset<-6

  # ---- 函数内部的小工具：切片 ----
  slice_vec <- function(vec, offset, per) {
    vec[ (offset + 1) : min(offset + per, length(vec)) ]
  }
  
 # cat("1,", page)
  # ---- 开始分发 ----
  p <- switch(dim,
              
              # ---------- 1. 最后六周按日统计 ----------
              "最后六周按日统计" = {
                switch(way,
                       "按日分省统计" = {
                         choosenList <- slice_vec(dfBy区域$省编号, offset, per)
                         if(length(choosenList) == 0) return(NULL)
                         switch(metric,
                                "测试数、阳性数、有效数" = {
                                  panelPlotByDayAndLocation(dfByDayAndLocation1, choosenList,
                                                            "testDay", "省编号",
                                                            c("测试数","有效数","阳性数"),
                                                            c("最后六周按日分省统计","测试时间","统计数值",""))
                                },
                                "阳性率、有效率" = {
                                  panelPlotByDayAndLocation(dfByDayAndLocation1, choosenList,
                                                            "testDay", "省编号",
                                                            c("有效率","阳性率"),
                                                            c("最后六周按日分省统计","测试时间","统计数值",""))
                                },
                                "项目数、仪器数、批次数" = {
                                  panelPlotByDayAndLocation(dfByDayAndLocation1, choosenList,
                                                            "testDay", "省编号",
                                                            c("项目数","仪器数","批次数"),
                                                            c("最后六周按日分省统计","测试时间","统计数值",""))
                                },
                                "省数、市数、小细胞数、样本数" = {
                                  panelPlotByDayAndLocation(dfByDayAndLocation1, choosenList,
                                                            "testDay", "省编号",
                                                            c("样本数","市数","小细胞数"),
                                                            c("最后六周按日分省统计","测试时间","统计数值",""))
                                }
                         )
                       },
                       "按日分小细胞统计" = {
                         choosenList <- slice_vec(细胞0$细胞, offset, per)
                         if(length(choosenList) == 0) return(NULL)
                         switch(metric,
                                "测试数、阳性数、有效数" = {
                                  panelPlotByDayAnd细胞(dfByDayAnd细胞1, choosenList,
                                                      "testDay", "小细胞",
                                                      c("测试数","有效数","阳性数"),
                                                      c("最后六周按日分小细胞统计","测试时间","统计数值",""))
                                },
                                "阳性率、有效率" = {
                                  panelPlotByDayAnd细胞(dfByDayAnd细胞1, choosenList,
                                                      "testDay", "小细胞",
                                                      c("有效率","阳性率"),
                                                      c("最后六周按日分小细胞统计","测试时间","统计数值",""))
                                },
                                "项目数、仪器数、批次数" = {
                                  panelPlotByDayAnd细胞(dfData=dfByDayAnd细胞1,choosenList,independentVariableName="testDay",panelName="小细胞",
                                                      dependentVariableNames=c("项目数","仪器数","批次数"),titleNames=c("最后六周按日分小细胞统计","测试时间","统计数值",""))
                                },
                                "省数、市数、小细胞数、样本数" = {
                                  panelPlotByDayAnd细胞(dfData=dfByDayAnd细胞1,choosenList,independentVariableName="testDay",panelName="小细胞",
                                                      dependentVariableNames=c("样本数","市数","省数"),titleNames=c("最后六周按日分小细胞统计","测试时间","统计数值",""))
                                }                            
                                
                         )
                       },
                       "按日分仪器统计" = {
                         choosenList <- slice_vec(仪器号List$仪器序列号, offset, per)
                         if(length(choosenList) == 0) return(NULL)
                         switch(metric,
                                "测试数、阳性数、有效数" = {
                                  panelPlotByDayAnd仪器(dfData=dfByDayAnd仪器1,choosenList,independentVariableName="testDay",panelName="仪器序列号",
                                                      dependentVariableNames=c("测试数","有效数","阳性数"),titleNames=c("最后六周按日分仪器统计","测试时间","统计数值",""))
                                },
                                "阳性率、有效率" = {
                                  panelPlotByDayAnd仪器(dfData=dfByDayAnd仪器1,choosenList,independentVariableName="testDay",panelName="仪器序列号",
                                                      dependentVariableNames=c("有效率","阳性率"),titleNames=c("最后六周按日分仪器统计","测试时间","统计数值",""))
 
                                },
                                "项目数、仪器数、批次数" = {
                                  panelPlotByDayAnd仪器(dfData=dfByDayAnd仪器1,choosenList,independentVariableName="testDay",panelName="仪器序列号",
                                                      dependentVariableNames=c("项目数","批次数"),titleNames=c("最后六周按日分仪器统计","测试时间","统计数值",""))
                                },
                                "省数、市数、小细胞数、样本数" = {
                                  panelPlotByDayAnd仪器(dfData=dfByDayAnd仪器1,choosenList,independentVariableName="testDay",panelName="仪器序列号",
                                                      dependentVariableNames=c("样本数","市数","省数","小细胞数"),titleNames=c("最后六周按日分仪器统计","测试时间","统计数值",""))
                               }
                                
                                
                         )
                       },
                       "全部统计" = {
                         switch(metric,
                                "测试数、阳性数、有效数" =
                                  plotfunction(dfByDay1, "testDay", c("测试数","有效数","阳性数"),
                                               c("最后六周按日统计","测试时间","统计数值","")),
                                "阳性率、有效率" =
                                  plotfunction(dfByDay1, "testDay", c("有效率","阳性率"),
                                               c("最后六周按日统计","测试时间","统计数值","")),
                                "项目数、仪器数、批次数" =
                                  plotfunction(dfByDay1, "testDay", c("项目数","仪器数","批次数"),
                                               c("最后六周按日统计","测试时间","统计数值","")),
                                "省数、市数、小细胞数、样本数" =
                                  plotfunction(dfByDay1, "testDay", c("样本数","市数","省数","小细胞数"),
                                               c("最后六周按日统计","测试时间","统计数值",""))
                         )
                       }
                )
              },
              
              # ---------- 2. 按月统计 ----------
              "按月统计" = {
                switch(way,
                       "按月分省统计" = {
                         choosenList <- slice_vec(dfBy区域$省编号, offset, per)
                         if(length(choosenList) == 0) return(NULL)
                       switch(metric,
                              "测试数、阳性数、有效数" = {
                                panelPlotByMonthAndLocation(dfByMonthAndLocation, choosenList,
                                                            "testMonth", "省编号",
                                                            c("测试数","有效数","阳性数"),
                                                            c("按月分省统计","测试时间","统计数值",""))
                              },
                              "阳性率、有效率" = {
                                panelPlotByMonthAndLocation(dfByMonthAndLocation, choosenList,
                                                            "testMonth", "省编号",
                                                            c("有效率","阳性率"),
                                                            c("按月分省统计","测试时间","统计数值",""))
                              },
                              "项目数、仪器数、批次数" = {
                                panelPlotByMonthAndLocation(dfByMonthAndLocation, choosenList,
                                                            "testMonth", "省编号",
                                                            c("项目数","仪器数","批次数"),
                                                            c("按月分省统计","测试时间","统计数值",""))
                              },
                              "省数、市数、小细胞数、样本数" = {
                                panelPlotByMonthAndLocation(dfByMonthAndLocation, choosenList,
                                                            "testMonth", "省编号",
                                                            c("样本数","市数","小细胞数"),
                                                            c("按月分省统计","测试时间","统计数值",""))
                              }
                       )
                       },
  "按月分小细胞统计" = {
    choosenList <- slice_vec(细胞0$细胞, offset, per)
    if(length(choosenList) == 0) return(NULL)
    switch(metric,
           "测试数、阳性数、有效数" = {
             panelPlotByMonthAnd细胞(dfByMonthAnd细胞, choosenList,
                                   "testMonth", "小细胞",
                                   c("测试数","有效数","阳性数"),
                                   c("按月分小细胞统计","测试时间","统计数值",""))
           },
           "阳性率、有效率" = {
             panelPlotByMonthAnd细胞(dfByMonthAnd细胞, choosenList,
                                   "testMonth", "小细胞",
                                   c("有效率","阳性率"),
                                   c("按月分小细胞统计","测试时间","统计数值",""))
           },
           "项目数、仪器数、批次数" = {
             panelPlotByMonthAnd细胞(dfData=dfByMonthAnd细胞,choosenList,independentVariableName="testMonth",panelName="小细胞",
                                   dependentVariableNames=c("项目数","仪器数","批次数"),titleNames=c("按月分小细胞统计","测试时间","统计数值",""))
           },
           "省数、市数、小细胞数、样本数" = {
             panelPlotByMonthAnd细胞(dfData=dfByMonthAnd细胞,choosenList,independentVariableName="testMonth",panelName="小细胞",
                                   dependentVariableNames=c("样本数","市数","省数","小细胞数"),titleNames=c("按月分小细胞统计","测试时间","统计数值",""))
           }
    )
  },
  "按月分仪器统计" = {
    choosenList <- slice_vec(仪器号List$仪器序列号, offset, per)
    if(length(choosenList) == 0) return(NULL)
    switch(metric,
           "测试数、阳性数、有效数" = {
             
             panelPlotByMonthAnd仪器(dfData=dfByMonthAnd仪器,choosenList,independentVariableName="testMonth",panelName="仪器序列号",
                                   dependentVariableNames=c("测试数","有效数","阳性数"),titleNames=c("按月分仪器统计","测试时间","统计数值",""))
           },
           "阳性率、有效率" = {
             panelPlotByMonthAnd仪器(dfData=dfByMonthAnd仪器,choosenList,independentVariableName="testMonth",panelName="仪器序列号",
                                   dependentVariableNames=c("有效率","阳性率"),titleNames=c("按月分仪器统计","测试时间","统计数值",""))
           },
           "项目数、仪器数、批次数" = {
             panelPlotByMonthAnd仪器(dfData=dfByMonthAnd仪器,choosenList,independentVariableName="testMonth",panelName="仪器序列号",
                                   dependentVariableNames=c("项目数","批次数"),titleNames=c("按月分仪器统计","测试时间","统计数值",""))
           },
           "省数、市数、小细胞数、样本数" = {
             panelPlotByMonthAnd仪器(dfData=dfByMonthAnd仪器,choosenList,independentVariableName="testMonth",panelName="仪器序列号",
                                   dependentVariableNames=c("样本数","市数","省数"),titleNames=c("按月分仪器统计","测试时间","统计数值",""))
           }    
 
           
    )
  },
  "全部统计" = {
    switch(metric,
           "测试数、阳性数、有效数" =
             plotfunction(dfByMonth1, "testMonth", c("测试数","有效数","阳性数"),
                          c("按月统计","测试时间","统计数值","")),
           "阳性率、有效率" =
             plotfunction(dfByMonth1, "testMonth", c("有效率","阳性率"),
                          c("按月统计","测试时间","统计数值","")),
           "项目数、仪器数、批次数" =
             plotfunction(dfByMonth1, "testMonth", c("项目数","仪器数","批次数"),
                          c("按月统计","测试时间","统计数值","")),
           "省数、市数、小细胞数、样本数" =
             plotfunction(dfByMonth1, "testMonth", c("样本数","市数","省数","小细胞数"),
                          c("按月统计","测试时间","统计数值",""))
    )                      
                       }
                )
              },
              
              "按小细胞统计" = {
                if (page == 1) {
                  switch(metric,
                         "测试数、阳性数、有效数"   = plotfunction(dfBy细胞1,"小细胞",c("测试数","有效数","阳性数"),c("按小细胞统计","细胞","统计数值","")),
                         "阳性率、有效率"           = plotfunction(dfBy细胞1, "小细胞", c("有效率","阳性率"), c("按小细胞统计","细胞","统计数值","")),
                         "项目数、仪器数、批次数"   = plotfunction(dfBy细胞1, "小细胞", c("项目数","仪器数","批次数"), c("按小细胞统计","细胞","统计数值","")),
                         "省数、市数、小细胞数、样本数"             = plotfunction(dfBy细胞1, "小细胞", c("样本数","市数","省数"), c("按小细胞统计","细胞","统计数值","")),
                         "测试截止、测试开始"       = plotfunctionLog(dfBy细胞1, "小细胞", c("测试开始","测试截止"), c("按小细胞统计","细胞","多少天之前",""))
                  )
                } else if (page == 2) {
                  switch(metric,
                         "测试数、阳性数、有效数"   = plotfunction(dfBy细胞2,"小细胞",c("测试数","有效数","阳性数"),c("按小细胞统计","细胞","统计数值","")),
                         "阳性率、有效率"           = plotfunction(dfBy细胞2, "小细胞", c("有效率","阳性率"), c("按小细胞统计","细胞","统计数值","")),
                         "批次数、项目数、仪器数"   = plotfunction(dfBy细胞2, "小细胞", c("项目数","仪器数","批次数"), c("按小细胞统计","细胞","统计数值","")),
                         "省数、市数、小细胞数、样本数"             = plotfunction(dfBy细胞2, "小细胞", c("样本数","市数","省数"), c("按小细胞统计","细胞","统计数值","")),
                         "测试截止、测试开始"       = plotfunctionLog(dfBy细胞2, "小细胞", c("测试开始","测试截止"), c("按小细胞统计","细胞","多少天之前",""))
                  )
                }
              },
                # ---------- 3. 其它维度（不需要分页） ----------
              "按省统计" = {
                switch(metric,
                       "测试数、阳性数、有效数"   = plotfunction(dfBy区域, "省编号", c("测试数","有效数","阳性数"), c("按省统计","省编号","统计数值","")),
                       "阳性率、有效率"           = plotfunction(dfBy区域, "省编号", c("有效率","阳性率"), c("按省统计","省编号","统计数值","")),
                       "批次数、项目数、仪器数"   = plotfunction(dfBy区域, "省编号", c("项目数","仪器数","批次数"), c("按省统计","省编号","统计数值","")),
                       "省数、市数、小细胞数、样本数"   = plotfunction(dfBy区域, "省编号", c("样本数","市数","小细胞数"), c("按省统计","省编号","统计数值","")),
                       "测试截止、测试开始"       = plotfunctionLog(dfBy区域, "省编号", c("测试开始","测试截止"), c("按省统计","省编号","多少天之前",""))
                )
              },
              
  "按仪器统计" = {
    if(!is.numeric(page)) return(NULL)
    if(page<1 | page>max(仪器号List$GroupID) | is.na(page))  return(NULL)
                switch(metric,
                       "测试数、阳性数、有效数"   = plotfunctionVector仪器序列号(page, 仪器号List, dfBy仪器, "仪器序列号", c("测试数","有效数","阳性数"), c("按仪器统计","仪器序列号","统计数值","")),
                       "阳性率、有效率"           = plotfunctionVector仪器序列号(page, 仪器号List, dfBy仪器, "仪器序列号", c("有效率","阳性率"), c("按仪器统计","仪器序列号","统计数值","")),
                       "批次数、项目数、样本数"   = plotfunctionVector仪器序列号(page, 仪器号List, dfBy仪器, "仪器序列号", c("项目数","批次数"), c("按仪器统计","仪器序列号","统计数值","")),
                       "省数、项目数、小细胞数、样本数"   = plotfunctionVector仪器序列号(page, 仪器号List, dfBy仪器, "仪器序列号", c("样本数","省数", "市数","小细胞数"), c("按仪器统计","仪器序列号","统计数值","")),
                       "测试截止、测试开始"       = plotfunctionVector仪器序列号Log(page, 仪器号List, dfBy仪器, "仪器序列号", c("测试开始","测试截止"), c("按仪器统计","仪器序列号","多少天之前",""))
                )
              },
              "按样本类型统计" = {
                switch(metric,
                       "测试数、阳性数、有效数"   = plotfunction(dfBy样本, "样本类型", c("测试数","有效数","阳性数"), c("按样本类型统计","样本类型","统计数值","")),
                       "阳性率、有效率"           = plotfunction(dfBy样本, "样本类型", c("有效率","阳性率"), c("按样本类型统计","样本类型","统计数值","")),
                       "批次数、省数、项目数、小细胞数" = plotfunction(dfBy样本, "样本类型", c("项目数","仪器数","批次数"), c("按样本类型统计","样本类型","统计数值","")),
                       "批次数、省数、项目数、小细胞数" = plotfunction(dfBy样本, "样本类型", c("省数", "市数","小细胞数"), c("按样本类型统计","样本类型","统计数值","")),
                        "测试截止、测试开始"       = plotfunctionLog(dfBy样本, "样本类型", c("测试开始","测试截止"), c("按样本类型统计","样本类型","多少天之前",""))
                )
              },
              "按试剂批次统计" = {
                if(!is.numeric(page)) return(NULL)
                if(page<1 | page>max(批次号List$GroupID) | is.na(page))  return(NULL)
                switch(metric,
                       "测试数、阳性数、有效数"   = plotfunctionVector批次名称(page, 批次号List, dfBy批次, "批次名称", c("测试数","有效数","阳性数"), c("按批次统计","批次名称","统计数值","")),
                       "阳性率、有效率"           = plotfunctionVector批次名称(page, 批次号List, dfBy批次, "批次名称", c("有效率","阳性率"), c("按试剂批次统计","批次名称","统计数值","")),
                       "省数、项目数、小细胞数、样本数" = plotfunctionVector批次名称(page, 批次号List, dfBy批次, "批次名称", c("项目数","仪器数"), c("按试剂批次统计","批次名称","统计数值","")),
                       "省数、项目数、小细胞数、样本数" = plotfunctionVector批次名称(page, 批次号List, dfBy批次, "批次名称", c("样本数","省数", "市数","小细胞数"), c("按试剂批次统计","批次名称","统计数值","")),
                       "测试截止、测试开始"       = plotfunctionVector批次名称Log(page, 批次号List, dfBy批次, "批次名称", c("测试开始","测试截止"), c("按试剂批次统计","批次名称","多少天之前",""))
                )
              },
              "按试剂项目统计" = {
                if(!is.numeric(page)) return(NULL)
                if(page<1 | page>max(项目号List$GroupID) | is.na(page))  return(NULL)
                switch(metric,
                       "测试数、阳性数、有效数"   = plotfunctionVector项目名称(page, 项目号List, dfBy项目, "项目名称", c("测试数","有效数","阳性数"), c("按项目统计","项目名称","统计数值","")),
                       "阳性率、有效率"           = plotfunctionVector项目名称(page, 项目号List, dfBy项目, "项目名称", c("有效率","阳性率"), c("按试剂项目统计","项目名称","统计数值","")),
                       "批次数、省数、小细胞数、样本数" = plotfunctionVector项目名称(page, 项目号List, dfBy项目, "项目名称", c("仪器数","批次数"), c("按试剂项目统计","项目名称","统计数值","")),
                       "省数、项目数、小细胞数、样本数" = plotfunctionVector项目名称(page, 项目号List, dfBy项目, "项目名称", c("样本数","省数", "市数","小细胞数"), c("按试剂项目统计","项目名称","统计数值","")),
                        "测试截止、测试开始"       = plotfunctionVector项目名称Log(page, 项目号List, dfBy项目, "项目名称", c("测试开始","测试截止"), c("按试剂项目统计","项目名称","多少天之前",""))
                )
              }
  )
  return(p)
}

shinyApp(ui = ui, server = server)