package Certificate

import (
	"ColdVerify_local/conf"
	"ColdVerify_local/lib"
	"ColdVerify_local/logs"
	"fmt"
	orm2 "github.com/beego/beego/v2/client/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
)

type Certificate_ struct {
	Id          int    `orm:"column(ID)"`
	T_sn        string // 编号
	T_layout_no string // 布局编号
}

// 获取列表
func Read_Certificate_List(T_task_id, T_sn string, page, page_z int) ([]Certificate_, int64) {
	serverOrm := orm2.NewOrmUsingDB(conf.Server_AliasName)
	localOrm := orm2.NewOrmUsingDB(conf.Local_AliasName)

	pagez := page_z

	var offset int
	if page <= 1 {
		offset = 0
	} else {
		page -= 1
		offset = page * pagez
	}

	var maps []Certificate_
	idList := []string{}
	sql := "SELECT t_id FROM z_task_data_" + T_task_id + " GROUP BY t_id"
	fmt.Println(sql)
	_, err := localOrm.Raw(sql).QueryRows(&idList)

	if err != nil {
		logs.Error(lib.FuncName(), err)
		return maps, 0
	}

	idListStr := ""
	for _, id := range idList {
		if idListStr != "" {
			idListStr = idListStr + ","
		}
		idListStr = idListStr + "'" + id + "'"
	}

	sql_condition := " t__state=1"
	if len(idListStr) > 0 {
		sql_condition += " AND t_layout_no not in (" + idListStr + ")"
	}
	if len(T_sn) > 0 {
		sql_condition += " AND t_layout_no='" + T_sn + "'"
	}

	sql = "SELECT count(*) FROM certificate WHERE" + sql_condition

	fmt.Println(sql)
	var count int64
	err = serverOrm.Raw(sql).QueryRow(&count)
	if err != nil {
		return maps, 0
	}
	//sql = "SELECT * FROM certificate WHERE t__state=1 AND t_sn not in (" + strings.Join(snList, ",") + ") ORDER BY t_layout_no"

	// fixme 冷脸验证线上更新后再部署如下代码
	sql = "SELECT ID,t_layout_no FROM certificate WHERE" + sql_condition
	if page_z != 9999 {
		sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
	}

	fmt.Println(sql)
	_, err = serverOrm.Raw(sql).QueryRows(&maps)
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return maps, 0
	}
	return maps, count
}
