package Task

import (
	"ColdVerify_local/conf"
	"ColdVerify_local/lib"
	"ColdVerify_local/logs"
	"github.com/beego/beego/v2/adapter/orm"
	orm2 "github.com/beego/beego/v2/client/orm"
	"time"
)

// 创建数据库  Device.CREATE_TaskData("")
func CREATE_TaskDataCopy(alias_name, T_copy_id string) bool {
	o := orm2.NewOrmUsingDB(alias_name)

	sql := "DROP TABLE IF EXISTS `z_task_data_copy_" + T_copy_id + "`"
	o.Raw(sql).Exec()

	sql = "CREATE TABLE IF NOT EXISTS `z_task_data_copy_" + T_copy_id + "` ( " +
		"  `ID` int(11) NOT NULL AUTO_INCREMENT," +
		"	`t_sn` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL," +
		"	`t_id` varchar(256) DEFAULT NULL," +
		"	`t_t` float(6, 1) NULL DEFAULT NULL," +
		"	`t_rh` float(6, 1) NULL DEFAULT NULL," +
		"	`t_time` datetime(0) NULL DEFAULT NULL," +
		"	PRIMARY KEY (`ID`) USING BTREE," +
		"   KEY `t_sn` (`t_sn`)," +
		"   KEY `t_id` (`t_id`)," +
		"   KEY `t_time` (`t_time`)" +
		") ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;"

	_, err := o.Raw(sql).Exec()
	if err != nil {
		return false
	}

	//sqlIndex := "ALTER TABLE `z_task_data_" + T_task_id + "` add unique index(`t_sn`,`t_id`,`t_time`);"
	//logs.Debug(sqlIndex)
	//o.Raw(sqlIndex).Exec()
	return true
}

type TaskCopy struct {
	Id         int       `orm:"column(ID);size(11);auto;pk"`
	T_task_id  string    `orm:"size(256);null"`                                        // 任务ID
	T_copy_id  string    `orm:"size(256);null"`                                        // 复制id
	T_time     string    `orm:"size(256);null"`                                        // 存档时间
	T_State    int       `orm:"size(2);default(1)"`                                    // 0 删除   1 正常 2 报告生成
	CreateTime time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now_add 第一次保存时才设置时间
	UpdateTime time.Time `orm:"column(update_time);type(timestamp);null;auto_now"`     //auto_now 每次 model 保存时都会对时间自动更新
}

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

func init() {

	//注册模型
	orm.RegisterModel(new(TaskCopy))
}

// 获取 By
func Read_TaskCopy(T_copy_id string) (r TaskCopy, err error) {

	o := orm.NewOrm()
	qs := o.QueryTable(new(TaskCopy))
	err = qs.Filter("T_copy_id", T_copy_id).Filter("T_State__gt", 0).One(&r)
	if err != nil {
		return r, err
	}
	return r, nil
}

// 修改
func Update_TaskCopy(r TaskCopy, cols ...string) bool {
	o := orm.NewOrm()
	if num, err := o.Update(&r, cols...); err == nil {
		logs.Println("Number of records updated in database:", num)
		return true
	}
	return false
}

// 添加
func Add_TaskCopy(r TaskCopy) (string, bool) {
	o := orm.NewOrm()
	// 生成编号
	rand_x := 0
	for true {
		r.T_copy_id = lib.GetRandstring(12, "abcdefghijklmnopqrstuvwxyz0123456789", int64(rand_x)) // 1,336,336
		err := o.Read(&r, "T_copy_id")                                                             // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
		if err != nil {
			break
		}
		rand_x += 1
	}

	_, err := o.Insert(&r)
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return "", false
	}

	return r.T_copy_id, true
}

// 删除
func Delete_TaskCopy(v TaskCopy) bool {
	o := orm.NewOrm()

	v.T_State = 0
	num, err := o.Update(&v, "T_State")
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return false
	}

	sql := "DROP TABLE IF EXISTS `z_task_data_copy_" + v.T_copy_id + "`"
	o.Raw(sql).Exec()

	logs.Println("Number of records deleted in database:", num)
	return true
}
func Read_TaskCopy_List(T_task_id string, page int, page_z int) ([]TaskCopy, int64) {
	o := orm.NewOrm()

	qs := o.QueryTable(new(TaskCopy))
	var r []TaskCopy
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = int64((page - 1) * page_z)
	}
	cond := orm.NewCondition()
	cond1 := cond.And("T_task_id", T_task_id).And("T_State__gt", 0)

	qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-T_time").All(&r)
	cnt, _ := qs.SetCond((*orm2.Condition)(cond1)).Count()

	return r, cnt
}

// 数据存档
func TaskData_Arhiving(T_task_id, T_copy_id string) bool {

	o := orm.NewOrm()

	sql := "INSERT INTO `z_task_data_copy_" + T_copy_id + "`(`t_sn`, `t_id`, `t_t`, `t_rh`, `t_time`)" +
		" SELECT `t_sn`, `t_id`, `t_t`, `t_rh`, `t_time` FROM `z_task_data_" + T_task_id + "`"
	_, err := o.Raw(sql).Exec()
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return false
	}
	return true
}

// 数据恢复
func TaskData_Recover(T_task_id, T_copy_id string) bool {

	o := orm.NewOrm()
	Truncate_TaskData(conf.Local_AliasName, T_task_id)

	sql := "INSERT INTO `z_task_data_" + T_task_id + "`(`t_sn`, `t_id`, `t_t`, `t_rh`, `t_time`)" +
		" SELECT `t_sn`, `t_id`, `t_t`, `t_rh`, `t_time` FROM z_task_data_copy_" + T_copy_id
	_, err := o.Raw(sql).Exec()
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return false
	}
	return true
}
