package StatisticsTask

import (
	"Cold_Data/lib"
	"Cold_Data/logs"
	"Cold_Data/models"
	"Cold_Data/models/Account"
	"Cold_Data/models/Device"
	"Cold_Data/models/Warning"
	"fmt"
	"time"
)

func init() {
	var err error
	// 从文件中加载map
	lib.Company_Map, err = lib.LoadMapFromFile("data.json")
	if err != nil {
		fmt.Println("Company_Map 文件不存在！，重新加载")
		lib.Company_Map = make(map[int]*models.Company_Project)
		lib.Company_Map[0] = &models.Company_Project{}

	} else {
		fmt.Println("Company_Map 加载成功")

	}

	// 定时循环 子公司归档
	go func() {
		time.Sleep(time.Second * 3)
		for true {
			// 间隔 全部统计一次
			StatisticsTask_GO()
			Company_Recursion(0)
			time.Sleep(time.Hour * 2)
		}
	}()

}

// 子公司归档
func Company_Recursion(T_mid int) {

	Company_A := Account.Read_Company_T_mid_All(T_mid)
	Company_Project_r, ok := lib.Company_Map[T_mid]
	if !ok {
		return
	}
	Company_Project_r.Children = []*models.Company_Project{} // 清空
	for _, A_r := range Company_A {
		Company_Project_Br, ok := lib.Company_Map[A_r.Id]
		if !ok {
			continue
		}
		Company_Recursion(A_r.Id)
		Company_Project_r.Children = append(Company_Project_r.Children, Company_Project_Br)
	}

	lib.Company_Map[T_mid] = Company_Project_r

}

// 处理公司 h 处理类型  0 全部  1 记录数据
func Company_Handle(C_r Account.Company) {
	_, ok := lib.GO_Handle[C_r.Id]
	if ok {
		return
	}

	lib.GO_Handle[C_r.Id] = true // 标记开始
	start := time.Now()
	logs.Println("开始处理公司：", C_r.T_name)
	Company_Project_r, ok := lib.Company_Map[C_r.Id]
	if !ok {
		Company_Project_r = &models.Company_Project{}
	}

	Company_Project_r.Company_name = C_r.T_name
	Company_Project_r.Company_key = C_r.T_key
	Company_Project_r.Company_plan = C_r.T_plan
	Company_Project_r.Company_data = C_r.T_data
	Company_Project_r.Company_v3d = C_r.T_v3d
	Company_Project_r.Company_Address = C_r.T_Address
	Company_Project_r.Company_coordinate = C_r.T_coordinate
	//Company_Project_r.Device.DeviceList = Device_Data(C_r)
	// 设备类
	Company_Project_r.Device.T_库房总数 = Device.Read_Device_库房总数(C_r.Id)
	Company_Project_r.Device.T_移动总数 = Device.Read_Device_移动总数(C_r.Id)
	if Company_Project_r.Device.T_库房总数+Company_Project_r.Device.T_移动总数 == 0 {
		// 没有设备，跳过数据整理
		lib.Company_Map[C_r.Id] = Company_Project_r
		return
	}
	Company_Project_r.Device.T_移动离线总数 = Device.Read_Device_设备离线总数(C_r.Id)
	Company_Project_r.Device.T_移动监控总数 = Device.Read_Device_设备监控总数(C_r.Id)

	// 报警类
	//Company_Project_r.Warning.T_库房报警总数 = Warning.Read_Warning_库房报警总数(C_r.Id)
	Company_Project_r.Warning.T_库房未处理总数 = Warning.Read_Warning_库房未处理总数(C_r.Id)

	Company_Project_r.Warning.T_库房设备报警数_今天 = Warning.Read_Warning_库房设备报警数(C_r.Id, "DATE (create_time) = DATE (NOW())")
	//Company_Project_r.Warning.T_库房设备报警数_昨天  = Warning.Read_Warning_库房设备报警数(C_r.Id,"TO_DAYS(NOW()) - TO_DAYS( create_time) <= 1")
	//Company_Project_r.Warning.T_库房设备报警数_近7天 = Warning.Read_Warning_库房设备报警数(C_r.Id,"DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(create_time)")
	//Company_Project_r.Warning.T_库房设备报警数_本月  = Warning.Read_Warning_库房设备报警数(C_r.Id,"DATE_FORMAT(create_time,'%Y%m') = DATE_FORMAT( CURDATE( ), '%Y%m' )")
	//Company_Project_r.Warning.T_库房设备报警数_上一月 = Warning.Read_Warning_库房设备报警数(C_r.Id,"PERIOD_DIFF(date_format(now(), '%Y%m' ), date_format( create_time,'%Y%m')) =1")
	Company_Project_r.Warning.T_库房报警设备数_今天 = Warning.Read_Warning_库房报警设备数(C_r.Id, "DATE (create_time) = DATE (NOW())")

	//Company_Project_r.Warning.T_移动警数总数 = Warning.Read_Warning_移动警数总数(C_r.Id)
	Company_Project_r.Warning.T_移动未处理总数 = Warning.Read_Warning_移动未处理总数(C_r.Id)
	Company_Project_r.Warning.T_移动设备报警数_今天 = Warning.Read_Warning_移动设备报警数(C_r.Id, "DATE (create_time) = DATE (NOW())")
	//Company_Project_r.Warning.T_移动设备报警数_昨天  = Warning.Read_Warning_移动设备报警数(C_r.Id,"TO_DAYS(NOW()) - TO_DAYS( create_time) <= 1")
	//Company_Project_r.Warning.T_移动设备报警数_近7天 = Warning.Read_Warning_移动设备报警数(C_r.Id,"DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(create_time)")
	//Company_Project_r.Warning.T_移动设备报警数_本月  = Warning.Read_Warning_移动设备报警数(C_r.Id,"DATE_FORMAT(create_time,'%Y%m') = DATE_FORMAT( CURDATE( ), '%Y%m' )")
	//Company_Project_r.Warning.T_移动设备报警数_上一月 = Warning.Read_Warning_移动设备报警数(C_r.Id,"PERIOD_DIFF(date_format(now(), '%Y%m' ), date_format( create_time,'%Y%m')) =1")
	Company_Project_r.Warning.T_移动报警设备数_今天 = Warning.Read_Warning_移动报警设备数(C_r.Id, "DATE (create_time) = DATE (NOW())")

	Company_Project_r.Warning.T_库房报警类型统计 = make(map[string]int)
	for _, v := range Warning.Read_Warning_库房报警类型统计(C_r.Id) {
		//x := models.WarningClassList_Project{T_name: Warning.Read_WarningType_Get(lib.To_int(v["t_tp"])),T_value: lib.To_int(v["COUNT(*)"])}
		Company_Project_r.Warning.T_库房报警类型统计[Warning.Read_WarningType_Get(lib.To_int(v["t_tp"]))] = lib.To_int(v["COUNT(*)"])
	}
	Company_Project_r.Warning.T_移动报警类型统计 = make(map[string]int)
	for _, v := range Warning.Read_Warning_移动端报警类型统计(C_r.Id) {
		Company_Project_r.Warning.T_移动报警类型统计[Warning.Read_WarningType_Get(lib.To_int(v["t_tp"]))] = lib.To_int(v["COUNT(*)"])
	}
	Company_Project_r.Warning.T_探头报警类型统计 = make(map[string]int)
	for _, v := range Warning.Read_Warning_探头报警统计(C_r.Id) {
		Company_Project_r.Warning.T_探头报警类型统计[v["t__d_s_name"].(string)] = lib.To_int(v["COUNT(*)"])
	}
	Company_Project_r.Warning.T_探头报警类型统计_30天 = make(map[string]int)
	sprintf30 := fmt.Sprintf("t__ut >= CURDATE() - INTERVAL %v DAY", 30)
	for _, v := range Warning.Read_Warning_日期探头报警统计(C_r.Id, sprintf30) {
		Company_Project_r.Warning.T_探头报警类型统计_30天[v["t__d_s_name"].(string)] = lib.To_int(v["COUNT(*)"])
	}

	Company_Project_r.Warning.T_探头报警类型统计_90天 = make(map[string]int)
	sprintf90 := fmt.Sprintf("t__ut >= CURDATE() - INTERVAL %v DAY", 90)
	for _, v := range Warning.Read_Warning_日期探头报警统计(C_r.Id, sprintf90) {
		Company_Project_r.Warning.T_探头报警类型统计_90天[v["t__d_s_name"].(string)] = lib.To_int(v["COUNT(*)"])
	}

	currentDate := time.Now().Local()

	//Company_Project_r.Warning.T_库房报警设备数_近7天[date.Format("01-02")] = Warning.Read_Warning_库房报警设备数(C_r.Id,"date_format(create_time,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
	//Company_Project_r.Warning.T_移动报警设备数_近7天[date.Format("01-02")] = Warning.Read_Warning_移动报警设备数(C_r.Id,"date_format(create_time,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
	//Company_Project_r.Warning.T_库房报警设备数_近7天 = make(map[string]int)
	//Company_Project_r.Warning.T_移动报警设备数_近7天 = make(map[string]int)
	Company_Project_r.Warning.T_报警设备数_近7天 = make(map[string]int)
	// 获取当前日期
	// 生成最近7天的日期
	for i := 0; i < 7; i++ {
		date := currentDate.AddDate(0, 0, -i)
		//Company_Project_r.Warning.T_库房报警设备数_近7天[date.Format("01-02")] = Warning.Read_Warning_库房报警设备数(C_r.Id,"date_format(create_time,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
		//Company_Project_r.Warning.T_移动报警设备数_近7天[date.Format("01-02")] = Warning.Read_Warning_移动报警设备数(C_r.Id,"date_format(create_time,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
		Company_Project_r.Warning.T_报警设备数_近7天[date.Format("01-02")] = Warning.Read_Warning_报警设备数(C_r.Id, "date_format(create_time,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
	}
	Company_Project_r.Warning.T_报警设备数_近30天 = make(map[string]int)
	// 生成最近30天的日期
	for i := 0; i < 30; i++ {
		date := currentDate.AddDate(0, 0, -i)
		Company_Project_r.Warning.T_报警设备数_近30天[date.Format("01-02")] = Warning.Read_Warning_报警设备数(C_r.Id, "date_format(create_time,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
	}
	Company_Project_r.Warning.T_报警设备数_近90天 = make(map[string]int)
	// 生成最近120天的日期
	for i := 0; i < 90; i++ {
		date := currentDate.AddDate(0, 0, -i)
		Company_Project_r.Warning.T_报警设备数_近90天[date.Format("01-02")] = Warning.Read_Warning_报警设备数(C_r.Id, "date_format(create_time,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
	}

	// 任务类
	Company_Project_r.Task.T_任务总数_今天 = Device.Read_Task_任务总数(C_r.Id, "DATE (t__ut_start) = DATE (NOW())")
	//Company_Project_r.Task.T_任务总数_昨天  = Device.Read_Task_任务总数(C_r.Id,"TO_DAYS(NOW()) - TO_DAYS( t__ut_start) <= 1")
	//Company_Project_r.Task.T_任务总数_近7天 = Device.Read_Task_任务总数(C_r.Id,"DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(t__ut_start)")

	Company_Project_r.Task.T_任务设备数_今天 = Device.Read_Task_任务设备数(C_r.Id, "DATE (t__ut_start) = DATE (NOW())")
	//Company_Project_r.Task.T_任务设备数_昨天  = Device.Read_Task_任务设备数(C_r.Id,"TO_DAYS(NOW()) - TO_DAYS( t__ut_start) <= 1")
	//Company_Project_r.Task.T_任务设备数_近7天 = Device.Read_Task_任务设备数(C_r.Id,"DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(t__ut_start)")

	//currentMonth := time.Now().Month()
	//currentYear := time.Now().Year()
	//Company_Project_r.Task.T_任务总数_近一年 = make(map[string]int)
	//for i := 0; i < 12; i++ {
	//	month := currentMonth - time.Month(i)
	//	year := currentYear
	//
	//	if month <= 0 {
	//		month += 12
	//		year--
	//	}
	//	Company_Project_r.Task.T_任务总数_近一年[fmt.Sprintf("%d-%d",year,month)] = Device.Read_Task_任务总数(C_r.Id,"date_format(t__ut_start,'%Y-%m') = '"+fmt.Sprintf("%d-%02d",year, int(month))+"'")
	//}

	Company_Project_r.Task.T_任务总数_近7天 = make(map[string]int)
	// 获取当前日期
	//currentDate := time.Now().Local()
	// 生成最近7天的日期
	for i := 0; i < 7; i++ {
		date := currentDate.AddDate(0, 0, -i)
		Company_Project_r.Task.T_任务总数_近7天[date.Format("01-02")] = Device.Read_Task_任务总数(C_r.Id, "date_format(t__ut_start,'%Y-%m-%d') = '"+date.Format("2006-01-02")+"'")
	}

	lib.Company_Map[C_r.Id] = Company_Project_r

	//str, _ := json.Marshal(Company_Project_r)
	//fmt.Println(string(str))
	logs.Println("处理公司完成：", C_r.T_name)
	logs.PrintlnData("[" + C_r.T_name + "] 耗时:" + time.Since(start).String())
	go func() {
		time.Sleep(time.Minute * 10)
		delete(lib.GO_Handle, C_r.Id)
	}()
}

func StatisticsTask_GO() {

	fmt.Println("----开始统计-----")
	Company_All := Account.Read_Company_All()
	for _, C_r := range Company_All {
		//内部测试
		if C_r.T_path[:5] == "/0/1/" {
			continue
		}
		_, ok := lib.GO_Handle[C_r.Id]
		if ok {
			continue
		}
		Company_Handle(C_r)
	}

	fmt.Println("----保存成功-----")
	// 将map保存到文件
	err := lib.SaveMapToFile(lib.Company_Map, "data.json")
	if err != nil {
		fmt.Println("保存失败:", err)
		return
	}

}

//func Device_Data(C_r Account.Company) []models.DeviceList_Project {
//	logs.Println("开始处理公司数据：", C_r.T_name)
//
//	DeviceList := []models.DeviceList_Project{}
//	for _, ds := range Device.Read_DeviceSensor_ByT_pid(C_r.Id) {
//		ds_ := models.DeviceList_Project{}
//
//		ds_.T_sn = ds.T_sn
//		ds_.T_id = ds.T_id
//		ds_.T_name = ds.T_name
//		ds_.T_sort = ds.T_sort
//		ds_.T_3dview = ds.T_3dview
//		ds_.T_type = ds.T_type
//		ds_.T_link = ds.T_link
//
//		dd := Device.Read_DeviceData(ds.T_sn, ds.T_id)
//		ds_.T_t = dd.T_t
//		ds_.T_rh = dd.T_rh
//		ds_.T_time = dd.T_time.Format("2006-01-02 15:04:05")
//		if dsp, is := Device.Read_DeviceSensorParameter(ds.T_sn, ds.T_id); is {
//			ds_.T_Tlower = dsp.T_Tlower
//			ds_.T_Tupper = dsp.T_Tupper
//			ds_.T_RHlower = dsp.T_RHlower
//			ds_.T_RHupper = dsp.T_RHupper
//		}
//
//		ds_.T_Dattery = ds.T_Dattery
//		ds_.T_Site = ds.T_Site
//		ds_.T_monitor = ds.T_monitor
//		ds_.T_online = ds.T_online
//		ds_.T_online_s = ds.T_online_s
//		DeviceList = append(DeviceList, ds_)
//
//	}
//
//	return DeviceList
//
//}
