package Distributor

import (
	"ColdVerify_server/conf"
	"ColdVerify_server/lib"
	"ColdVerify_server/logs"
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/cache"
	"github.com/beego/beego/v2/adapter/orm"
	orm2 "github.com/beego/beego/v2/client/orm"
	_ "github.com/go-sql-driver/mysql"
	"time"
)

// 分销商
type Distributor struct {
	Id               int       `orm:"column(ID);size(11);auto;pk"`
	T_name           string    `orm:"size(256);null"`                                        // 名称
	T_Distributor_id string    `orm:"size(256);null"`                                        // 分销商id
	T_State          int       `orm:"size(200);default(1)"`                                  //  0删除  1 正常
	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 第一次保存时才设置时间
}

type Distributor_R struct {
	T_name           string
	T_Distributor_id string
}

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

var redisCache_Distributor cache.Cache

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

	config := fmt.Sprintf(`{"key":"%s","conn":"%s","dbNum":"%s","password":"%s"}`,
		"redis_"+"distributor", conf.Redis_address, conf.Redis_dbNum, conf.Redis_password)
	logs.Println(config)
	var err error
	redisCache_Distributor, err = cache.NewCache("redis", config)
	if err != nil || redisCache_Distributor == nil {
		errMsg := "failed to init redis"
		logs.Println(errMsg, err)

	}
}

// -------------------------------------------------------------
func DistributorToDistributor_R(T Distributor) (T_r Distributor_R) {
	T_r.T_name = T.T_name
	T_r.T_Distributor_id = T.T_Distributor_id

	//......
	return T_r
}

// ---------------- Redis -------------------
// Redis_Set(m.T_sn,m) // Redis 更新缓存
func Redis_Distributor_Set(key string, r Distributor) (err error) {
	//json序列化
	str, err := json.Marshal(r)
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return
	}
	err = redisCache_Distributor.Put(key, str, 24*time.Hour)
	if err != nil {
		logs.Println("set key:", key, ",value:", str, err)
	}
	return
}

// if r,is :=Redis_Get(T_sn);is{
// return r,nil
// }
func Redis_Distributor_Get(key string) (r Distributor, is bool) {
	if redisCache_Distributor.IsExist(key) {
		logs.Println("找到key:", key)
		v := redisCache_Distributor.Get(key)
		json.Unmarshal(v.([]byte), &r)
		return r, true
	}
	logs.Println("没有 找到key:", key)
	return Distributor{}, false
}
func Redis_Distributor_DelK(key string) (err error) {
	err = redisCache_Distributor.Delete(key)
	return
}

// ---------------- 特殊方法 -------------------

// 获取 ById
func Read_Distributor_ById(id int) (r Distributor, is bool) {
	o := orm.NewOrm()
	r = Distributor{Id: id}
	err := o.Read(&r) // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
	if err != nil {
		logs.Error(lib.FuncName(), err)
		return r, false
	}
	return r, true
}

// 获取 By
func Read_Distributor(T_Distributor_id string) (r Distributor, is bool) {

	o := orm.NewOrm()
	qs := o.QueryTable(new(Distributor))
	err := qs.Filter("T_Distributor_id", T_Distributor_id).One(&r)
	if err != nil {
		return r, false
	}

	return r, true
}

// 添加
func Add_Distributor(r Distributor) (id int64, is bool) {
	o := orm.NewOrm()

	// 生成编号
	rand_x := 0
	for true {
		r.T_Distributor_id = lib.GetRandstring(4, "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", int64(rand_x)) // 1,336,336
		err := o.Read(&r, "T_Distributor_id")                                                            // o.Read(&r,"Tokey") 如果不是 主键 就得指定字段名
		if err != nil {
			break
		}
		rand_x += 1
	}

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

	Redis_Distributor_Set(r.T_name, r)
	return id, true
}

// 删除
func Delete_Distributor(v Distributor) bool {
	o := orm.NewOrm()
	if num, err := o.Delete(&v); err == nil {
		logs.Println("Number of records deleted in database:", num)
	} else {
		return false
	}

	Redis_Distributor_DelK(v.T_name)
	return true
}

// 删除
func Delete_Distributor_(v Distributor) bool {
	o := orm.NewOrm()
	v.T_State = 0
	if num, err := o.Update(&v, "T_State"); err == nil {
		logs.Println("Number of records updated in database:", num)
	} else {
		return false
	}

	Redis_Distributor_DelK(v.T_name)
	return true
}

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

// 获取列表
func Read_Distributor_List(T_name string, page int, page_z int) ([]Distributor_R, int64) {

	o := orm.NewOrm()
	// 也可以直接使用 Model 结构体作为表名
	var r []Distributor
	qs := o.QueryTable(new(Distributor))
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = int64((page - 1) * page_z)
	}
	cond := orm.NewCondition()
	cond1 := cond.And("T_name__icontains", T_name).And("T_State", 1) // .AndNot("status__in", 1).Or("profile__age__gt", 2000)

	if page_z == 9999 {
		qs.SetCond((*orm2.Condition)(cond1)).OrderBy("-Id").All(&r)
	} else {
		qs.Limit(page_z, offset).SetCond((*orm2.Condition)(cond1)).OrderBy("-Id").All(&r)
	}
	cnt, _ := qs.SetCond((*orm2.Condition)(cond1)).Count()

	// 转换
	var Distributor_r []Distributor_R
	for _, v := range r {
		Distributor_r = append(Distributor_r, DistributorToDistributor_R(v))
	}

	return Distributor_r, cnt
}

// 获取列表
func Read_Distributor_List_ALL(T_name string) (maps []Distributor) {

	o := orm.NewOrm()
	qs := o.QueryTable(new(Distributor))
	if len(T_name) > 0 {
		qs = qs.Filter("T_name__icontains", T_name)
	}

	qs.Filter("T_State", 1).OrderBy("Id").All(&maps)

	return maps
}

func DistributorListToMap(T []Distributor) map[string]string {
	maps := make(map[string]string, len(T))
	for _, v := range T {
		maps[v.T_Distributor_id] = v.T_name
	}
	return maps
}
