package service

import (
	"fmt"
	"log"
	"time"
	"useEquipmentTimeEarlyWARNING/config"
	"useEquipmentTimeEarlyWARNING/databases"
	"useEquipmentTimeEarlyWARNING/util"
)

var serialNumber string

func init() {
	serialNumber = config.Config.GetString("serialNumber")
}

// VerifyEquipmentUseTime 验证设备使用时间
func VerifyEquipmentUseTime() {
	db := databases.Db

	//获取设备信息 sn 和 创建时间
	rows, err := db.Query("SELECT t_sn,t_dev_name,create_time,t__verify_time,t__calibration_time FROM Device WHERE t__state = 1 ")
	if err != nil {
		log.Panicln(err.Error())
	}
	fmt.Println("======================",time.Now())
	var (
		tSn,
		tDevName,
		createTime,
		t__verify_time, // 验证时间
		t__calibration_time string// 校准时间
	)
	for rows.Next() {
		nowTime := time.Now()


		rows.Scan(&tSn, &tDevName, &createTime, &t__verify_time, &t__calibration_time)
		fmt.Print(tSn)

		// 设备使用时间超过
		if createTime != "" {
			time, _ := time.Parse("2006-01-02 15:04:05", createTime)
			sub := nowTime.Sub(time)
			day := int(sub.Hours() / 24) // / 365
			fmt.Print("   设备使用时间：", day,"天")
			if day == 1 * 365 {
				util.SendWarning(tSn, -1,  1014, tDevName, "", fmt.Sprintf("%s设备使用时间超过1年", tSn))  // 运维预警通知
			}else if day == 2 * 365 {
				util.SendWarning(tSn, -1,  1014, tDevName, "", fmt.Sprintf("%s设备使用时间超过2年", tSn))  // 运维预警通知
			}else if day == 3 * 365 {
				util.SendWarning(tSn, -1,  1014, tDevName, "", fmt.Sprintf("%s设备使用时间超过3年", tSn))  // 运维预警通知
			}
		}

		// 设备验证时间还剩
		if t__verify_time != "" {
			time, _ := time.Parse("2006-01-02 15:04:05", t__verify_time)
			sub := time.Sub(nowTime)
			day := int(sub.Hours() / 24) // / 365
			fmt.Print("   设备验证时间还剩：", day,"天")
			if day == 1 * 60 {
				util.SendWarning(tSn, -1,  1003, tDevName, "", fmt.Sprintf("%s设备验证时间还剩%d天", tSn, int(day)))  // 运维预警通知
			}else if day == 2 * 60 {
				util.SendWarning(tSn, -1,  1003, tDevName, "", fmt.Sprintf("%s设备验证时间还剩%d天", tSn, int(day)))  // 运维预警通知
			}else if day == 3 * 60 {
				util.SendWarning(tSn, -1,  1003, tDevName, "", fmt.Sprintf("%s设备验证时间还剩%d天", tSn, int(day)))  // 运维预警通知
			}
		}

		// 设备校准时间还剩
		if t__calibration_time != "" {
			time, _ := time.Parse("2006-01-02 15:04:05", t__calibration_time)
			sub := time.Sub(nowTime)
			day := int(sub.Hours() / 24) // / 365
			fmt.Print("   设备校准时间还剩：", day,"天")
			if day == 1 * 60 {
				util.SendWarning(tSn, -1,  1003, tDevName, "", fmt.Sprintf("%s设备校准时间还剩%d天", tSn, int(day)))  // 运维预警通知
			}else if day == 2 * 60 {
				util.SendWarning(tSn, -1,  1003, tDevName, "", fmt.Sprintf("%s设备校准时间还剩%d天", tSn, int(day)))  // 运维预警通知
			}else if day == 3 * 60 {
				util.SendWarning(tSn, -1,  1003, tDevName, "", fmt.Sprintf("%s设备校准时间还剩%d天", tSn, int(day)))  // 运维预警通知
			}
		}

		fmt.Print("\n")




	}
}
