package main

import (
	"fmt"
	log "github.com/donnie4w/go-logger/logger"
	"github.com/tealeg/xlsx"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"os"
	qu "qfw/util"
	"regexp"
	"strings"
	"time"
	"unicode/utf8"
)

var (
	f_1 = xlsx.NewFile()
	f_2 = xlsx.NewFile()
 	f_3 = xlsx.NewFile()
 	f_4 = xlsx.NewFile()
 	f_5 = xlsx.NewFile()
	sheet_1 ,sheet_2,sheet_3,sheet_4,sheet_5 	*xlsx.Sheet
	x_name_1,x_name_2,x_name_3,x_name_4,x_name_5	string
	x_tag_1,x_tag_2,x_tag_3,x_tag_4,x_tag_5	string
)


func initBidata()  {

	x_name_1 = "招标信息"
	x_name_2 = "中标信息"
	x_name_3 = "招标项目"
	x_name_4 = "开标公示"
	x_name_5 = "评标公示"
	x_tag_1 = ""
	x_tag_2 = ""
	x_tag_3 = ""
	x_tag_4 = ""
	x_tag_5 = ""


	os.Remove("招标信息.xlsx")
	os.Remove("中标信息.xlsx")
	os.Remove("招标项目.xlsx")
	os.Remove("开标公示.xlsx")
	os.Remove("评标公示.xlsx")

	sheet_1, _= f_1.AddSheet("招标信息")
	sheet_2, _= f_2.AddSheet("中标信息")
	sheet_3, _= f_3.AddSheet("招标项目")
	sheet_4, _= f_4.AddSheet("开标公示")
	sheet_5, _= f_5.AddSheet("评标公示")

	row_1:= sheet_1.AddRow()
	row_2:= sheet_2.AddRow()
	row_3:= sheet_3.AddRow()
	row_4:= sheet_4.AddRow()
	row_5:= sheet_5.AddRow()

	for _,v := range bid_tagText[0]{
		row_1.AddCell().Value = v
	}
	for _,v := range bid_tagText[1]{
		row_2.AddCell().Value = v
	}
	for _,v := range bid_tagText[2]{
		row_3.AddCell().Value = v
	}
	for _,v := range bid_tagText[3]{
		row_4.AddCell().Value = v
	}
	for _,v := range bid_tagText[4]{
		row_5.AddCell().Value = v
	}
}

func isToLongNewFile(num int) (bool,string)  {
	//暂定500000 -间隔
	index := 100000
	if num/index > 0 {
		return true,fmt.Sprintf("_%d",num/index)
	}
	return false,""
}
//导出-招标相关-信息
func exportBidata() {
	log.Debug("导出~标讯信息表...")
	sess := bid_mgo.GetMgoConn()
	defer bid_mgo.DestoryMongoConn(sess)
	q,total := map[string]interface{}{
		"publishtime": map[string]interface{}{
			"$gte": 1640966400,
			"$lt": 1646064000,
		},
	},0
	num_1,num_2,num_4:=0,0,0
	it := sess.DB(bid_mgo.DbName).C(bid_coll).Find(&q).Iter()
	for tmp := make(map[string]interface{}); it.Next(&tmp);total++{
		if total%10000==0 {
			log.Debug("curent index ",total,num_1,num_2,num_4)
			f_1.Save(x_name_1+x_tag_1+".xlsx")
			f_2.Save(x_name_2+x_tag_2+".xlsx")
			f_4.Save(x_name_4+x_tag_4+".xlsx")

			b_1,tag_1 := isToLongNewFile(num_1)
			if b_1 && !strings.Contains(x_tag_1,tag_1) {
				x_tag_1 = tag_1
				f_1 = xlsx.NewFile()
				sheet_1, _= f_1.AddSheet("招标信息")
				row_1:= sheet_1.AddRow()
				for _,v := range bid_tagText[0]{
					row_1.AddCell().Value = v
				}
			}

			b_2,tag_2 := isToLongNewFile(num_2)
			if b_2 && !strings.Contains(x_tag_2,tag_2) {
				x_tag_2 = tag_2
				f_2 = xlsx.NewFile()
				sheet_2, _= f_2.AddSheet("中标信息")
				row_2:= sheet_2.AddRow()
				for _,v := range bid_tagText[1]{
					row_2.AddCell().Value = v
				}
			}

			b_4,tag_4 := isToLongNewFile(num_4)
			if b_4 && !strings.Contains(x_tag_4,tag_4) {
				x_tag_4 = tag_4
				f_4 = xlsx.NewFile()
				sheet_4, _= f_4.AddSheet("评标公示")
				row_4:= sheet_4.AddRow()
				for _,v := range bid_tagText[3]{
					row_4.AddCell().Value = v
				}
			}
		}
		spidercode := qu.ObjToString(tmp["spidercode"])
		extracttype := qu.IntAll(tmp["extracttype"])
		subtype := qu.ObjToString(tmp["subtype"])
		toptype := qu.ObjToString(tmp["toptype"])
		site := qu.ObjToString(tmp["site"])
		if extracttype==-1&&site!="中国政府采购网"&&site!="中国招标投标公共服务平台"{
			tmp = make(map[string]interface{})
			continue
		}
		if kb_spicode[spidercode]=="" && xm_spicode[spidercode]=="" {
			tmp = make(map[string]interface{})
			continue
		}

		topscopeclass := []string{}
		if t_class, ok := tmp["topscopeclass"].(primitive.A); ok {
			topscopeclass = qu.ObjArrToStringArr(t_class)
		}else {
			if t_class, ok := tmp["topscopeclass"].([]interface{}); ok {
				topscopeclass = qu.ObjArrToStringArr(t_class)
			}
		}
		topscope := ""
		for k,v := range topscopeclass{
			length := utf8.RuneCountInString(v)
			new_v := string([]rune(v)[0:length-1])
			if k==0 {
				topscope = new_v
			}else {
				if! strings.Contains(topscope,new_v) {
					topscope = topscope+","+new_v
				}
			}
		}




		if toptype=="招标" {
			num_1++
			data_1 := dealWithZhaoBiao(tmp,num_1,topscope)
			row_1:= sheet_1.AddRow()
			for _,v := range data_1{
				row_1.AddCell().Value = v
			}
		}
		if subtype == "中标" || subtype == "成交" || subtype == "合同" {
			num_2++
			data_2 := dealWithZhongBiao(tmp,num_2,topscope)
			row_2:= sheet_2.AddRow()
			for _,v := range data_2{
				row_2.AddCell().Value = v
			}
		}
		if kb_spicode[spidercode]!=""{
			num_4++
			data_4 := dealWithKaiBiao(tmp,num_4,topscope)
			row_4:= sheet_4.AddRow()
			for _,v := range data_4{
				row_4.AddCell().Value = v
			}
		}
		tmp = make(map[string]interface{})
	}


	log.Debug("is over bidding ",total,num_1,num_2,num_4)

	if total>0 {
		f_1.Save(x_name_1+x_tag_1+".xlsx")
		f_2.Save(x_name_2+x_tag_2+".xlsx")
		f_4.Save(x_name_4+x_tag_4+".xlsx")
	}
}
//导出-项目相关-信息
func exportProjectSetData() {
	log.Debug("导出~标讯信息表...")
	sess := ext_mgo.GetMgoConn()
	defer ext_mgo.DestoryMongoConn(sess)
	q,total := map[string]interface{}{
		"_id": map[string]interface{}{
			"$gte": StringTOBsonId("61cf29000000000000000000"),
			"$lte": StringTOBsonId("621cf1800000000000000000"),
		},
	},0
	//1640966400    1646064000
	num_3 := 0
	it := sess.DB(ext_mgo.DbName).C("projectset_20200918").Find(&q).Iter()
	for tmp := make(map[string]interface{}); it.Next(&tmp);total++{
		if total%10000==0 {
			log.Debug("curent index ",total,num_3)
			f_3.Save(x_name_3+x_tag_3+".xlsx")
			b_3,tag_3 := isToLongNewFile(num_3)
			if b_3 && !strings.Contains(x_tag_3,tag_3) {
				x_tag_3 = tag_3
				f_3 = xlsx.NewFile()
				sheet_3, _= f_3.AddSheet("招标项目")
				row_3:= sheet_3.AddRow()
				for _,v := range bid_tagText[2]{
					row_3.AddCell().Value = v
				}
			}
		}
		zbtime := qu.IntAll(tmp["zbtime"])
		if zbtime<1640966400 || zbtime>=1646064000 {
			tmp = make(map[string]interface{})
			continue
		}
		topscopeclass := []string{}
		if t_class, ok := tmp["topscopeclass"].(primitive.A); ok {
			topscopeclass = qu.ObjArrToStringArr(t_class)
		}else {
			if t_class, ok := tmp["topscopeclass"].([]interface{}); ok {
				topscopeclass = qu.ObjArrToStringArr(t_class)
			}
		}

		list := []map[string]interface{}{}
		if l, ok := tmp["list"].(primitive.A); ok {
			list = qu.ObjArrToMapArr(l)
		}else {
			if l, ok := tmp["list"].([]interface{}); ok {
				list = qu.ObjArrToMapArr(l)
			}
		}

		site := ""
		if len(list)>0 {
			site = qu.ObjToString(list[0]["site"])
			if strings.Contains(site,"元博网") {
				site = "剑鱼发布"
			}
		}
		topscope := ""
		for k,v := range topscopeclass{
			length := utf8.RuneCountInString(v)
			new_v := string([]rune(v)[0:length-1])
			if k==0 {
				topscope = new_v
			}else {
				if! strings.Contains(topscope,new_v) {
					topscope = topscope+","+new_v
				}
			}
		}

		num_3++
		data_3 := dealWithXiangMu(tmp,num_3,topscope,site)
		row_3:= sheet_3.AddRow()
		for _,v := range data_3{
			row_3.AddCell().Value = v
		}
		tmp = make(map[string]interface{})
	}

	log.Debug("is over bidding ",total,num_3)
	if total>0 {
		f_3.Save(x_name_3+x_tag_3+".xlsx")
	}
}
//导出-评标相关-信息
func exportExtdata() {
	log.Debug("导出~评标信息表...")
	sess := ext_mgo.GetMgoConn()
	defer ext_mgo.DestoryMongoConn(sess)
	q,total := map[string]interface{}{
		"publishtime": map[string]interface{}{
			"$gte": 1640966400,
			"$lt": 1646064000,
		},
	},0
	num_5:=0
	it := sess.DB(ext_mgo.DbName).C(ext_coll).Find(&q).Iter()
	for tmp := make(map[string]interface{}); it.Next(&tmp);total++{
		if total%1000==0 {
			log.Debug("curent index ", total, num_5)
			f_5.Save(x_name_5 + x_tag_5 + ".xlsx")

			b_5, tag_5 := isToLongNewFile(num_5)
			if b_5 && !strings.Contains(x_tag_5, tag_5) {
				x_tag_5 = tag_5
				f_5 = xlsx.NewFile()
				sheet_5, _ = f_5.AddSheet("招标信息")
				row_5 := sheet_5.AddRow()
				for _, v := range bid_tagText[4] {
					row_5.AddCell().Value = v
				}
			}
		}
		extracttype := qu.IntAll(tmp["extracttype"])
		if extracttype==-1 {
			tmp = make(map[string]interface{})
			continue
		}
		spidercode := qu.ObjToString(tmp["spidercode"])
		winnerorder := []map[string]interface{}{}
		if w_order, ok := tmp["winnerorder"].(primitive.A); ok {
			winnerorder = qu.ObjArrToMapArr(w_order)
		}else {
			if w_order, ok := tmp["winnerorder"].([]interface{}); ok {
				winnerorder = qu.ObjArrToMapArr(w_order)
			}
		}

		topscopeclass := []string{}
		if t_class, ok := tmp["topscopeclass"].(primitive.A); ok {
			topscopeclass = qu.ObjArrToStringArr(t_class)
		}else {
			if t_class, ok := tmp["topscopeclass"].([]interface{}); ok {
				topscopeclass = qu.ObjArrToStringArr(t_class)
			}
		}
		topscope := ""
		for k,v := range topscopeclass{
			length := utf8.RuneCountInString(v)
			new_v := string([]rune(v)[0:length-1])
			if k==0 {
				topscope = new_v
			}else {
				if! strings.Contains(topscope,new_v) {
					topscope = topscope+","+new_v
				}
			}
		}


		if pb_spicode[spidercode]!=""||len(winnerorder)>0{
			num_5++
			winners:=""
			if len(winnerorder)>0 {
				for _,v := range winnerorder {
					entname := qu.ObjToString(v["entname"])
					if entname!=""{
						if winners=="" {
							winners = entname
						}else {
							winners = winners+","+entname
						}
					}
				}
			}
			if winners=="" {
				winners = qu.ObjToString(tmp["s_winner"])
			}
			data_5 := dealWithPingBiao(tmp,num_5,winners,topscope)
			row_5:= sheet_5.AddRow()
			for _,v := range data_5{
				row_5.AddCell().Value = v
			}
		}

		tmp = make(map[string]interface{})
	}


	log.Debug("is over ext ~",total,num_5)

	if total>0 {
		f_5.Save(x_name_5 + x_tag_5 + ".xlsx")
	}
}





//招标信息
func dealWithZhaoBiao(tmp map[string]interface{},index int,topscope string)[]string {
	dataArr := []string{}
	dataArr = append(dataArr,fmt.Sprintf("%d",index))
	site := qu.ObjToString(tmp["site"])
	if strings.Contains(site,"元博网") {
		site = "剑鱼发布"
	}
	dataArr = append(dataArr,site)
	dataArr = append(dataArr,qu.ObjToString(tmp["projectname"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["area"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["city"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["district"]))
	dataArr = append(dataArr,"")

	dataArr = append(dataArr,topscope)



	publishtime := qu.Int64All(tmp["publishtime"])
	if publishtime>0 {
		dataArr = append(dataArr,time.Unix(publishtime, 0).Format(timeLayout))
	}else {
		dataArr = append(dataArr,"")
	}

	dataArr = append(dataArr,"")//公告结束日期
	buyer := qu.ObjToString(tmp["buyer"])
	dataArr = append(dataArr,buyer)
	price := qu.Float64All(tmp["budget"])
	price_str,price_unit := "",""
	if price>0.0 {
		price_str = fmt.Sprintf("%.2f",price)
		price_unit = "元"
	}
	dataArr = append(dataArr,price_str)
	dataArr = append(dataArr,price_unit)

	dataArr = append(dataArr,qu.ObjToString(tmp["buyeraddr"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["buyerperson"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["buyertel"]))


	if buyer!="" {
		qy_data := qy_mgo.FindOne(qy_coll, map[string]interface{}{
			"company_name":buyer,
		})
		dataArr = append(dataArr,qu.ObjToString(qy_data["company_email"]))//邮箱
	}else {
		dataArr = append(dataArr,"")//邮箱
	}

	dataArr = append(dataArr,qu.ObjToString(tmp["href"]))
	dataArr = append(dataArr,trimHtml(qu.ObjToString(tmp["detail"])))

	return dataArr
}
//中标信息
func dealWithZhongBiao(tmp map[string]interface{},index int,topscope string)[]string {
	dataArr := []string{}
	dataArr = append(dataArr,fmt.Sprintf("%d",index))
	site := qu.ObjToString(tmp["site"])
	if strings.Contains(site,"元博网") {
		site = "剑鱼发布"
	}
	dataArr = append(dataArr,site)
	dataArr = append(dataArr,qu.ObjToString(tmp["projectname"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["area"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["city"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["district"]))
	dataArr = append(dataArr,"")
	dataArr = append(dataArr,topscope)

	publishtime := qu.Int64All(tmp["publishtime"])
	if publishtime>0 {
		dataArr = append(dataArr,time.Unix(publishtime, 0).Format(timeLayout))
	}else {
		dataArr = append(dataArr,"")
	}
	dataArr = append(dataArr,"")//招标公告发布日期
	bidopentime := qu.Int64All(tmp["bidopentime"])
	if bidopentime>0 {
		dataArr = append(dataArr,time.Unix(bidopentime, 0).Format(timeLayout))
	}else {
		dataArr = append(dataArr,"")
	}

	dataArr = append(dataArr,qu.ObjToString(tmp["s_winner"]))
	price := qu.Float64All(tmp["bidamount"])
	price_str,price_unit := "",""
	if price>0.0 {
		price_str = fmt.Sprintf("%.2f",price)
		price_unit = "元"
	}
	dataArr = append(dataArr,price_str)
	dataArr = append(dataArr,price_unit)

	dataArr = append(dataArr,"")//评标委员会名单
	dataArr = append(dataArr,qu.ObjToString(tmp["buyer"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["buyerperson"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["buyertel"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["href"]))
	dataArr = append(dataArr,trimHtml(qu.ObjToString(tmp["detail"])))

	return dataArr
}
//项目信息
func dealWithXiangMu(tmp map[string]interface{},index int,topscope string,site string)[]string {
	dataArr := []string{}
	dataArr = append(dataArr,fmt.Sprintf("%d",index))
	dataArr = append(dataArr,site)
	dataArr = append(dataArr,qu.ObjToString(tmp["projectname"]))
	dataArr = append(dataArr,topscope)
	dataArr = append(dataArr,qu.ObjToString(tmp["area"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["city"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["district"]))
	dataArr = append(dataArr,"")
	zbtime := qu.Int64All(tmp["zbtime"])
	if zbtime>0 { //招标项目建立时间
		dataArr = append(dataArr,time.Unix(zbtime, 0).Format(timeLayout))
	}else {
		dataArr = append(dataArr,"")
	}
	agency := qu.ObjToString(tmp["agency"])
	if agency!="" {
		qy_data := qy_mgo.FindOne(qy_coll, map[string]interface{}{
			"company_name":agency,
		})
		dataArr = append(dataArr,qu.ObjToString(qy_data["credit_no"]))//招标代理机构代码
	}else {
		dataArr = append(dataArr,"")//招标代理机构代码
	}
	dataArr = append(dataArr,agency)
	dataArr = append(dataArr,qu.ObjToString(tmp["buyer"]))
	//组织~~~部门名称
	dataArr = append(dataArr,"")
	dataArr = append(dataArr,"")
	dataArr = append(dataArr,"")
	dataArr = append(dataArr,"")
	dataArr = append(dataArr,"")
	dataArr = append(dataArr,qu.ObjToString(tmp["projectscope"]))

	return dataArr
}
//开标信息
func dealWithKaiBiao(tmp map[string]interface{},index int,topscope string)[]string {
	dataArr := []string{}
	dataArr = append(dataArr,fmt.Sprintf("%d",index))
	site := qu.ObjToString(tmp["site"])
	if strings.Contains(site,"元博网") {
		site = "剑鱼发布"
	}
	dataArr = append(dataArr,site)
	projectname := qu.ObjToString(tmp["projectname"])
	if projectname != "" {
		dataArr = append(dataArr,qu.ObjToString(tmp["projectname"]))
	}else {
		dataArr = append(dataArr,qu.ObjToString(tmp["title"]))
	}
	dataArr = append(dataArr,topscope)
	dataArr = append(dataArr,qu.ObjToString(tmp["area"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["city"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["district"]))
	dataArr = append(dataArr,"")
	bidopentime := qu.Int64All(tmp["bidopentime"])
	if bidopentime>0 {
		dataArr = append(dataArr,time.Unix(bidopentime, 0).Format(timeLayout))
	}else {
		dataArr = append(dataArr,"")
	}
	return dataArr
}
//评标信息
func dealWithPingBiao(tmp map[string]interface{},index int,winners string,topscope string)[]string {
	dataArr := []string{}
	dataArr = append(dataArr,fmt.Sprintf("%d",index))
	site := qu.ObjToString(tmp["site"])
	if strings.Contains(site,"元博网") {
		site = "剑鱼发布"
	}
	dataArr = append(dataArr,site)
	dataArr = append(dataArr,qu.ObjToString(tmp["projectname"]))
	dataArr = append(dataArr,topscope)
	dataArr = append(dataArr,qu.ObjToString(tmp["area"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["city"]))
	dataArr = append(dataArr,qu.ObjToString(tmp["district"]))
	dataArr = append(dataArr,"")
	publishtime := qu.Int64All(tmp["publishtime"])
	if publishtime>0 {
		dataArr = append(dataArr,time.Unix(publishtime, 0).Format(timeLayout))
	}else {
		dataArr = append(dataArr,"")
	}
	dataArr = append(dataArr,"")//公式结束时间
	dataArr = append(dataArr,winners)
	return dataArr
}



func trimHtml(src string) string {
	//将HTML标签全转换成小写
	re, _ := regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllStringFunc(src, strings.ToLower)
	//去除STYLE
	re, _ = regexp.Compile("\\<style[\\S\\s]+?\\</style\\>")
	src = re.ReplaceAllString(src, "")
	//去除SCRIPT
	re, _ = regexp.Compile("\\<script[\\S\\s]+?\\</script\\>")
	src = re.ReplaceAllString(src, "")
	//去除所有尖括号内的HTML代码，并换成换行符
	re, _ = regexp.Compile("\\<[\\S\\s]+?\\>")
	src = re.ReplaceAllString(src, "\n")
	//去除连续的换行符
	re, _ = regexp.Compile("\\s{2,}")
	src = re.ReplaceAllString(src, "\n")
	return strings.TrimSpace(src)
}