suppressMessages({
  library("optparse")
  library(Seurat)
  library(dplyr)
  library(tibble)
  library(ggplot2)
  library(tiff)
  library(broom)
  library(grid)
  library(gridExtra)
  library(magick)
  library(purrr)
  library(cowplot)
  library(figpatch)
  library(pdftools)
  library(cluster)
  library(ggpubr)
  library(SingleR)
  library(celldex)
})

option_list <- list(
        make_option(c("-i", "--indir"), help="indir"),
        make_option(c("-o", "--outdir"), help="outdir", default="."),
        make_option(c("--he_png"), help="he png file"),
        make_option(c("--point_size"), help="point_size, default %default",type="double",default=1),
        make_option(c("--cluster"), help="cluster.csv"),
	make_option(c("--cell_type1"), help="cell type 1"),
	make_option(c("--cell_type2"), help="cell type 2")
)
opt <- parse_args(OptionParser(option_list=option_list))


Cluster=read.csv(opt$cluster,header=TRUE,sep=",")
outdir=opt$outdir
he_file=opt$he_png
point_size=opt$point_size


he_fig=png::readPNG(he_file)
width=ncol(he_fig)
hetght=nrow(he_fig)
cal_zoom_rate = function(width, height){
        std_width = 1000
        std_height = std_width / (46 * 31) * (46 * 36 * sqrt(3) / 2.0)
        if(std_width / std_height > width / height){
                scale = width / std_width
        }
        else{
                scale = height / std_height
        }
        return(scale)
}

zoom_scale = cal_zoom_rate(ncol(he_fig), nrow(he_fig))

FilePath=opt$indir

bc_pos_file = gzfile(paste(FilePath, "barcodes_pos.tsv.gz", sep  = "/"),'rt')
bc_pos = read.table(bc_pos_file, header = FALSE, sep = '\t', quote = '')
names(bc_pos)=c("Barcode","x","y")
bc_pos=merge(bc_pos,Cluster,by="Barcode",all=FALSE)
bc_pos$x=bc_pos$x * zoom_scale
bc_pos$y=bc_pos$y * zoom_scale

col =  c("#F56867","#FEB915","#C798EE","#59BE86","#7495D3","#D1D1D1","#6D1A9C","#15821E","#3A84E6","#997273","#787878","#DB4C6C","#9E7A7A","#554236","#AF5F3C","#93796C","#F9BD3F","#DAB370","#87
7F6C","#268785","#ed1299", "#09f9f5", "#246b93", "#cc8e12", "#d561dd", "#c93f00", "#ddd53e","#4aef7b", "#e86502", "#9ed84e", "#39ba30", "#6ad157", "#8249aa", "#99db27", "#e07233", "#ff523f","#c
e2523", "#f7aa5d", "#cebb10", "#03827f", "#931635", "#373bbf", "#a1ce4c", "#ef3bb6", "#d66551","#1a918f", "#ff66fc", "#2927c4", "#7149af" ,"#57e559" ,"#8e3af4" ,"#f9a270" ,"#22547f", "#db5e92",
"#edd05e", "#6f25e8", "#0dbc21", "#280f7a", "#6373ed", "#5b910f" ,"#7b34c1" ,"#0cf29a" ,"#d80fc1")

#计算相邻细胞距离
distance<-c()
m=1
for (i in 1:(nrow(bc_pos)-1)){
	j=i+1
	dis=sqrt((abs(bc_pos[i,]$x-bc_pos[j,]$x)^2)+(abs(bc_pos[i,]$y-bc_pos[j,]$y)^2))
	distance[m]=dis
	m=m+1
	if(m>1000){
		break
	}
}
min_dis=min(distance)
print(min_dis)
bc_pos$singleR=as.factor(bc_pos$singleR)
bc_pos <- bc_pos[which(bc_pos$singleR==opt$cell_type1 | bc_pos$singleR==opt$cell_type2),]

col_index<-c()
m=1
n=1
for(i in levels(bc_pos$singleR)){
	if(i %in% bc_pos$singleR){
		col_index[m]=n
		m=m+1
	}
	n=n+1
}
col<-col[col_index]

#默认保留宽度为4
bc_pos$bj="no"
for (i in 1:(nrow(bc_pos)-1)){
	for (j in (i+1):(nrow(bc_pos))){
        	dis=sqrt((abs(bc_pos[i,]$x-bc_pos[j,]$x)^2)+(abs(bc_pos[i,]$y-bc_pos[j,]$y)^2))
        	if(dis>min_dis*2.2){
			next
		}
		if(bc_pos[i,]$singleR != bc_pos[j,]$singleR){
			bc_pos[i,]$bj="yes"
			bc_pos[j,]$bj="yes"
		}
	}
}
bc_pos<-bc_pos[which(bc_pos$bj=="yes"),]

singleR_clstr_plot<-ggplot(data=bc_pos,aes(x ,dim(he_fig)[1]-y)) +
    background_image(he_fig)+
    geom_point(aes(colour = singleR),size=point_size) +
    scale_color_manual(values = col)+
    theme_bw() +
    theme(plot.title = element_text(face = 2,size = 50,hjust = 0.5)) +
    #geom_label(data = label.data, aes(label = singleR,x = x.center,y = dim(he_fig)[1]-y.center))+
    theme(axis.ticks = element_blank(), axis.text.y = element_blank(),panel.border = element_blank(), axis.text.x = element_blank()) +
    xlab('')+ylab('')+
    coord_cartesian(xlim = c(0, dim(he_fig)[2]), ylim = c(0, dim(he_fig)[1]),
                        expand = FALSE)+
    guides(colour = guide_legend(override.aes = list(size=3.5)))+
    theme(legend.position="right")

ggsave(filename = paste(outdir,"/",opt$cell_type1,"_",opt$cell_type2,"_bianjie.pdf",sep=""), plot = singleR_clstr_plot, width = 10, height = 8)
ggsave(filename = paste(outdir,"/",opt$cell_type1,"_",opt$cell_type2,"_bianjie.png",sep=""), plot = singleR_clstr_plot, width = 10, height = 8)
