package Distributor

import (
	"ColdVerify_server/lib"
	"ColdVerify_server/logs"
	"ColdVerify_server/models/VerifyTemplate"
	"github.com/beego/beego/v2/adapter/orm"
	orm2 "github.com/beego/beego/v2/client/orm"
	_ "github.com/go-sql-driver/mysql"
	"strconv"
	"strings"
	"time"
)

// 分销商验证模版
type DistributorVerifyTemplate struct {
	Id                       int       `orm:"column(ID);size(11);auto;pk"`
	T_Distributor_id         string    `orm:"size(200);default(1)"`                                  // 分销商 int id
	T_VerifyTemplate_id      string    `orm:"size(200);default(1)"`                                  // 验证模版 int id
	T_VerifyTemplateClass_id int       `orm:"size(200);default(1)"`                                  // 验证模版分类 int id
	CreateTime               time.Time `orm:"column(create_time);type(timestamp);null;auto_now_add"` //auto_now 每次 model 保存时都会对时间自动更新
	UpdateTime               time.Time `orm:"column(update_time);type(timestamp);null;auto_now"`     //auto_now_add 第一次保存时才设置时间
}

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

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

// 添加
func Add_DistributorVerifyTemplate(r []DistributorVerifyTemplate) (id int64, is bool) {
	o := orm.NewOrm()
	id, err := o.InsertMulti(len(r), r)
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return 0, false
	}

	return id, true
}

// 删除
func Delete_DistributorVerifyTemplate(T_Distributor_id string) bool {
	o := orm.NewOrm()

	qs := o.QueryTable(new(DistributorVerifyTemplate))
	if num, err := qs.Filter("T_Distributor_id", T_Distributor_id).Delete(); err == nil {
		logs.Println("Number of records deleted in database:", num)
	} else {
		return false
	}

	return true
}

// 获取列表
func Read_DistributorVerifyTemplateClass_List(T_Distributor_id string) (r []VerifyTemplate.VerifyTemplateClass) {

	o := orm.NewOrm()
	var map_r []VerifyTemplate.VerifyTemplateClass
	// 也可以直接使用 Model 结构体作为表名
	sql := "SELECT vtc.* FROM verify_template_class vtc LEFT JOIN distributor_verify_template dvt ON vtc.id = dvt.t__verify_template_class_id" +
		" WHERE vtc.t__state = 1 and t__distributor_id = '" + T_Distributor_id + "' group by vtc.id order by vtc.id"

	logs.Println(sql)

	_, err := o.Raw(sql).QueryRows(&map_r)
	if err != nil {
		logs.Println(lib.FuncName(), err)
		return r
	}

	uniqueMap := make(map[int]struct{})
	var result []int

	for _, v := range map_r {
		parents := GetParentIDsByPath(v.T_path)
		for _, id := range parents {
			if id == 0 {
				continue
			}
			if _, exists := uniqueMap[id]; !exists {
				uniqueMap[id] = struct{}{}
				result = append(result, id)
			}
		}
	}
	var map_r2 []VerifyTemplate.VerifyTemplateClass
	qs := o.QueryTable(new(VerifyTemplate.VerifyTemplateClass))
	qs.Filter("Id__in", result).All(&map_r2)

	r = VerifyTemplate.VerifyTemplateClass_Call(map_r2, 0)

	return r

}

func GetParentIDsByPath(path string) []int {
	cleaned := strings.Trim(path, "/")
	if cleaned == "" {
		return nil
	}
	segments := strings.Split(cleaned, "/")
	parents := make([]int, 0, len(segments))
	for _, seg := range segments {
		id, _ := strconv.Atoi(seg)
		parents = append(parents, id)
	}
	return parents
}

func Read_DistributorVerifyTemplate_List(T_Distributor_id string, T_class int, T_name string, page int, page_z int) ([]VerifyTemplate.VerifyTemplate_R, int64) {

	o := orm.NewOrm()
	// 也可以直接使用 Model 结构体作为表名
	var r []VerifyTemplate.VerifyTemplate
	var VerifyTemplate_r []VerifyTemplate.VerifyTemplate_R
	var offset int
	pagez := page_z
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_z
	}
	sqlWhere := "vt.t_class = " + strconv.Itoa(T_class) + " AND t__distributor_id = '" + T_Distributor_id + "'"
	if len(T_name) > 1 {
		sqlWhere += " AND vt.t_name like \"%" + T_name + "%\""
	}
	sql := "SELECT COUNT(vt.id) FROM verify_template vt LEFT JOIN distributor_verify_template dvt ON vt.t__verify_template_id = dvt.t__verify_template_id COLLATE utf8mb4_general_ci " +
		"WHERE " + sqlWhere
	logs.Println(sql)
	var maps_z []orm2.ParamsList
	_, err := o.Raw(sql).ValuesList(&maps_z)
	if err != nil {
		return VerifyTemplate_r, 0
	}
	if len(maps_z) == 0 {
		return VerifyTemplate_r, 0
	}

	if page_z != 9999 {
		sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
	}

	sql = "SELECT vt.* FROM verify_template vt LEFT JOIN distributor_verify_template dvt ON vt.t__verify_template_id = dvt.t__verify_template_id COLLATE utf8mb4_general_ci " +
		"WHERE " + sqlWhere + " order by vt.t_name"
	if page_z != 9999 {
		sql = sql + " LIMIT " + strconv.Itoa(offset) + "," + strconv.Itoa(pagez)
	}

	logs.Println(sql)
	_, err = o.Raw(sql).QueryRows(&r)
	if err != nil {
		logs.Println(lib.FuncName(), err)
		return VerifyTemplate_r, 0
	}

	key, _ := strconv.Atoi(maps_z[0][0].(string))

	for _, v := range r {
		VerifyTemplate_r = append(VerifyTemplate_r, VerifyTemplate.VerifyTemplateToVerifyTemplate_R(v))
	}

	return VerifyTemplate_r, int64(key)
}
