package Device

import (
	"Cold_Data/conf"
	"Cold_Data/lib"
	"Cold_Data/logs"
	"github.com/beego/beego/v2/adapter/orm"
	orm2 "github.com/beego/beego/v2/client/orm"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

// 模板
type DeviceTask struct {
	Id         int       `orm:"column(ID);size(11);auto;pk"`
	T_sn       string    `orm:"size(256);null"`        // 设备序列号 KF开头，环境监测主机。 YD开头，温途监测主机
	T_Ut_start time.Time `orm:"type(timestamp);null;"` // 开始时间
	T_Ut_end   time.Time `orm:"type(timestamp);null;"` // 结束时间

	T_Ut    time.Time `orm:"type(timestamp);null;"` // 采集时间
	T_State int       `orm:"size(2);default(1)"`
	//  1   start:开始监测任务，
	//  2   stop：结束监测任务，
	//  3   print：中途打印任务
}

// 模板
type DeviceTask_R struct {
	T_Ut_start string // 开始时间
	T_Ut_end   string // 结束时间
	T_State    int
	//  1   start:开始监测任务，
	//  2   stop：结束监测任务，
	//  3   print：中途打印任务
}

func (t *DeviceTask) TableName() string {
	return "device_task" // 数据库名称   // ************** 替换 FormulaList **************
}

func init() {
	//注册模型
	orm.RegisterModel(new(DeviceTask))
}

// 获取全部
func Read_DeviceTask_List(T_sn string) (r_l []DeviceTask) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(DeviceTask))

	cond := orm.NewCondition()
	cond1 := cond.And("T_sn", T_sn)

	_, err := qs.Limit(10).SetCond((*orm2.Condition)(cond1)).OrderBy("-Id").All(&r_l)
	if err != nil {
		logs.PrintlnError(lib.FuncName(), err)
		return
	}

	return
}

func Read_Task_任务总数(t_pid int, Wtime string) int {

	o := orm.NewOrm()
	var maps []orm2.Params
	sql := "SELECT COUNT(1) FROM device_task WHERE " + Wtime + " AND t_sn IN (SELECT DISTINCT t_sn FROM device_sensor WHERE t_pid = ? AND t_type IN " + conf.YD + ")"
	o.Raw(sql, t_pid).Values(&maps)

	return lib.To_int(maps[0]["COUNT(1)"])
}

func Read_Task_任务设备数(t_pid int, Wtime string) int {

	o := orm.NewOrm()
	var maps []orm2.Params
	sql := "SELECT COUNT(DISTINCT t_sn) AS COUNT FROM device_task WHERE " + Wtime + " AND t_sn IN (SELECT DISTINCT t_sn FROM device_sensor WHERE t_pid = ? AND t_type IN " + conf.YD + ")"
	o.Raw(sql, t_pid).Values(&maps)

	return lib.To_int(maps[0]["COUNT"])
}
