package main

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


var (
	sysconfig    							map[string]interface{} //配置文件
	data_mgo						      	*MongodbSim     //mongodb操作对象
	save_other_name,data_coll_name			string
	xlsx_name,dynamic_coll_name				string
	infoSiteArr								[]string
)

func initMgo()  {

	dconf := sysconfig["data_mgodb"].(map[string]interface{})
	data_coll_name = qu.ObjToString(dconf["coll"])
	data_mgo = &MongodbSim{
		MongodbAddr: dconf["addr"].(string),
		DbName:      dconf["db"].(string),
		Size:        qu.IntAllDef(dconf["pool"], 5),
	}
	data_mgo.InitPool()



	//属性赋值
	save_other_name = qu.ObjToString(sysconfig["save_other_name"])
	dynamic_coll_name = qu.ObjToString(sysconfig["dynamic_coll_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()
	//企业变更-站点-mongo
	c.AddFunc("0 0 9 ? * *", func() { dealWithOtherData() })

	c.Start()

}

func dealWithOtherData()  {

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

	//先获取-待统计-动态站点
	tmp ,tmp_err := data_mgo.Find(dynamic_coll_name, 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())
	spider_data :=dealWithSiteSpiderData()//站点数据
	comeintime :=qu.Int64All(time.Now().Unix())

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

	//获取前两天数据
	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_st_data :=data_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().SetString(qu.ObjToString(spider_data["date"]))
	if len(before_st_data)>0 {
		row.AddCell().SetString(qu.ObjToString(before_st_data["date"]))
	}

	data_1 := *qu.ObjToMap(spider_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])))
		if len(before_st_data)>0 {
			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(spider_data["num"])))
	if len(before_st_data)>0 {
		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,"秒")
}