package main

import (
	"fmt"
	"github.com/cron"
	"github.com/tealeg/xlsx"
	"log"
	"os"
	qu "qfw/util"
	"time"
)


var (
	sysconfig    							map[string]interface{} //配置文件
	save_mgo,qy_mgo,jp_mgo,st_mgo        	*MongodbSim            //mongodb操作对象
	qy_c_name,jp_c_name,st_c_name			string
	es_index_st,es_type_st					string
	save_other_name,save_site_name			string
	xlsx_name								string
	infoSiteArr								[]string
)

func initMgo()  {

	saveconf := sysconfig["save_mgodb"].(map[string]interface{})
	qy_c_name = qu.ObjToString(saveconf["coll"])
	save_mgo = &MongodbSim{
		MongodbAddr: saveconf["addr"].(string),
		DbName:      saveconf["db"].(string),
		Size:        qu.IntAllDef(saveconf["pool"], 5),
	}
	save_mgo.InitPool()

	qconf := sysconfig["qy_mgodb"].(map[string]interface{})
	qy_c_name = qu.ObjToString(qconf["coll"])
	qy_mgo = &MongodbSim{
		MongodbAddr: qconf["addr"].(string),
		DbName:      qconf["db"].(string),
		Size:        qu.IntAllDef(qconf["pool"], 5),
	}
	qy_mgo.InitPool()

	jconf := sysconfig["jp_mgodb"].(map[string]interface{})
	jp_c_name = qu.ObjToString(jconf["coll"])
	jp_mgo = &MongodbSim{
		MongodbAddr: jconf["addr"].(string),
		DbName:      jconf["db"].(string),
		Size:        qu.IntAllDef(jconf["pool"], 5),
	}
	jp_mgo.InitPool()

	sconf := sysconfig["st_mgodb"].(map[string]interface{})
	st_c_name = qu.ObjToString(sconf["coll"])
	st_mgo = &MongodbSim{
		MongodbAddr: sconf["addr"].(string),
		DbName:      sconf["db"].(string),
		Size:        qu.IntAllDef(sconf["pool"], 5),
	}
	st_mgo.InitPool()


	//属性赋值
	es_index_st = qu.ObjToString(sysconfig["es_index_st"])
	es_type_st = qu.ObjToString(sysconfig["es_type_st"])
	save_other_name = qu.ObjToString(sysconfig["save_other_name"])
	save_site_name = qu.ObjToString(sysconfig["save_site_name"])


	xlsx_name = qu.ObjToString(sysconfig["xlsx_name"])
}

func init() {
	//加载配置文件
	qu.ReadConfig(&sysconfig)
	initMgo()
}

func main() {
	go taskTime()

	time.Sleep(99999 * time.Hour)

}

func taskTime()  {

	log.Println("部署定时任务")
	c := cron.New()

	//站点相关全量-es-mongo
	c.AddFunc("0 30 8 ? * *", func() { dealWithSTData() })


	//企业变更-站点-mongo
	c.AddFunc("0 0 9 ? * *", func() { dealWithOtherData() })

	c.Start()

}

func dealWithOtherData()  {

	log.Println("开始统计相关数据...")

	//先获取-待统计-动态站点
	tmp ,tmp_err := save_mgo.Find("z_site_spider", map[string]interface{}{},nil,nil)
	if tmp_err==nil && tmp!=nil && len(tmp)>0 {
		infoSiteArr = make([]string,0)
		for _,v :=range tmp {
			infoSiteArr = append(infoSiteArr,qu.ObjToString(v["site"]))
		}
		log.Println("目标站点：",len(infoSiteArr))
	}

	start := int(time.Now().Unix())
	st_data :=dealWithJPData()//站点数据
	qy_date,qy_num := dealWithQYData()//企业数据
	comeintime :=qu.Int64All(time.Now().Unix())
	save_mgo.Save(save_other_name, map[string]interface{}{
		"name":"企业",
		"num":qu.IntAll(qy_num),
		"comeintime":comeintime,
		"date":qy_date,
	})

	save_mgo.Save(save_other_name, map[string]interface{}{
		"name":"站点",
		"num":qu.IntAll(st_data["num"]),
		"comeintime":comeintime,
		"date":qu.ObjToString(st_data["date"]),
		"data":st_data["data"],
	})



	//获取前两天数据
	qy_arr := make([]map[string]string,0)
	now:=time.Now() //当前天
	cur_time:= time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).Unix()
	before_time := cur_time-86400*2
	before_date :=qu.FormatDateByInt64(&before_time, qu.DATEFORMAT)
	//企业数据
	before_qy_data :=save_mgo.FindOne(save_other_name, map[string]interface{}{
		"name":"企业",
		"date":before_date,
	})
	qy_arr = append(qy_arr, map[string]string{
		"date":qy_date,
		"num":qy_num,
	})
	if before_qy_data!=nil && len(before_qy_data)>2 {
		qy_arr = append(qy_arr, map[string]string{
			"date":qu.ObjToString(before_qy_data["date"]),
			"num":fmt.Sprintf("%d",before_qy_data["num"]),
		})
	}


	//站点数据
	before_st_data :=save_mgo.FindOne(save_other_name, map[string]interface{}{
		"name":"站点",
		"date":before_date,
	})


	os.Remove("统计.xlsx")	//写excle
	f :=xlsx.NewFile()
	sheet, _ := f.AddSheet("统计")

	//企业数据
	row := sheet.AddRow()
	row.AddCell().Value = "企业分类/日期"
	row.AddCell().Value = "数量"
	for _,tmp := range qy_arr {
		row = sheet.AddRow()
		row.AddCell().SetString(tmp["date"])
		row.AddCell().SetString(tmp["num"])
	}


	//站点相关数据
	sheet.AddRow()
	row = sheet.AddRow()
	row.AddCell().Value = "站点分类/日期"
	row.AddCell().SetString(qu.ObjToString(st_data["date"]))
	row.AddCell().SetString(qu.ObjToString(before_st_data["date"]))


	data_1 := *qu.ObjToMap(st_data["data"])
	data_2 := *qu.ObjToMap(before_st_data["data"])

	for _,key := range infoSiteArr {
		row = sheet.AddRow()
		row.AddCell().SetString(key)
		row.AddCell().SetString(fmt.Sprintf("%d",qu.Int64All(data_1[key])))
		row.AddCell().SetString(fmt.Sprintf("%d",qu.Int64All(data_2[key])))
	}
	row = sheet.AddRow()
	row.AddCell().Value = "总计"
	row.AddCell().SetString(fmt.Sprintf("%d",qu.Int64All(st_data["num"])))
	row.AddCell().SetString(fmt.Sprintf("%d",qu.Int64All(before_st_data["num"])))

	err := f.Save(xlsx_name)
	if err != nil {
		log.Println("保存xlsx失败:", err)
	}else {
		log.Println("保存xlsx成功:", err)
	}


	sendErrMailSmtp("统计-站点-企业","附件")

	log.Println("定时处理完毕...",int(time.Now().Unix())-start,"秒")
}