# ==========================================================
#                Corrected Code
# ==========================================================

# 1. Load the faersR package.
library(faersR)

dic_drug('Velaglucerase|Vpriv|维拉苷酶')
# 2. Clear all previous filters to ensure a clean start.
filt_clear()


# 3. Set the drug role filter to include only reports where the drug is the primary suspect.
filt_drug.role(primary.suspect = TRUE)

# 4. Define the time frame for data extraction by creating a sequence of all quarters from 1994 to 2023.
#    Note: This sets the broadest possible time frame; the final analysis period is determined by data availability.
years_to_filter <- 1994:2023
all_quarters <- paste0(rep(years_to_filter, each = 4), "Q", 1:4)
do.call(filt_yearQ, list(all_quarters))

# 5. Display the current filter settings for verification.
filt_show()

# 6. Define the query terms for the specific drug in this comparative analysis: Velaglucerase (brand name: Vpriv).
#    Note: The variable name 'Imiglucerase' is retained from a template but holds the 'Velaglucerase' query.
Imiglucerase <- dic_drug('Velaglucerase|Vpriv|维拉苷酶', file = 'cidian')

# 7. Execute the screening process for Velaglucerase.
sc <- screen(Imiglucerase)

# 8. Display a summary of the screening results.
sc

# 9. Generate and save Table 1, containing the baseline characteristics of the Adverse Event Reports (AERs) for Velaglucerase.
AER_tab1(sc, file = '01 表格1')

# 10. Calculate and save signal detection scores at the System Organ Class (SOC) level for Velaglucerase.
sig_soc(sc = sc,
        ROR = TRUE, PRR = TRUE, chisq = TRUE, IC = TRUE, EBGM = TRUE,
        ROR.3 = 1, PRR.2 = 1,
        top = 100,
        by = NULL,
        rank.n = FALSE, rank.ROR = TRUE, rank.PRR = FALSE,
        rank.chisq = FALSE, rank.IC = FALSE, rank.EBGM = FALSE,
        file = '02 soc的结果'
)

# 11. Generate a preliminary signal analysis at the Preferred Term (PT) level (top 5 shown in console).
sig_pt(sc, rank.ROR = TRUE, sort.soc = TRUE, top = 5)

# 12. Save the complete list of significant PT signals for Velaglucerase to a file.
sig_pt(sc, rank.ROR = TRUE, sort.soc = TRUE, file = '03 具体不良反应')

# 13. Save the top 30 PT signals (ranked by ROR) for Velaglucerase to a separate file.
sig_pt(sc, rank.ROR = TRUE, sort.soc = TRUE, file = '03 具体不良反应前30', TOP = 30)

# 14. Retrieve the top 10,000 PT signals and store them in a data frame for further visualization or analysis.
pt <- sig_pt(sc, rank.ROR = TRUE, top = 10000)

# 15. Generate a waterfall plot based on the Information Component (IC) lower bound (IC025).
waterfall.IC025(pt)

# 16. Generate a flowchart illustrating the data screening process for the Velaglucerase analysis.
flowchart(sc)
