l_ai_category/ai_test.go

89 lines
2.0 KiB
Go

package l_ai_category
import (
"context"
"encoding/json"
"fmt"
"gitea.cdlsxd.cn/self-tools/l_ai_category/utils_gorm"
"testing"
)
const (
dns = "root:lansexiongdi6,@tcp(47.97.27.195:3306)/report?parseTime=True&loc=Local"
driver = "mysql"
table = "goods_category"
)
func TestCategory(t *testing.T) {
catString := string(CategoryToJsonByte())
res, err := GetCategory(context.Background(), "金龙鱼御品珍珠米", "03320e58-6a0b-4061-a22b-902039f2190d", "deepseek-v3-250324", catString)
t.Log(res, err)
}
type Category struct {
Id int `json:"id"`
Name string `json:"name"`
Level int `json:"level"`
Pid int `json:"pid"`
}
type CategoryDic struct {
Category
Children []*CategoryDic `json:"children"`
}
func TestGetCateGoryJson(t *testing.T) {
cateJsonByte := CategoryToJsonByte()
t.Log(string(cateJsonByte))
}
func CategoryToJsonByte() (cateJsonByte []byte) {
cates := cateAll()
var (
cateLevelPath = make([]map[int][]*CategoryDic, 3)
)
for _, v := range cates {
if cateLevelPath[v.Level-1] == nil {
cateLevelPath[v.Level-1] = make(map[int][]*CategoryDic)
}
if _, ex := cateLevelPath[v.Level-1][v.Pid]; !ex {
cateLevelPath[v.Level-1][v.Pid] = make([]*CategoryDic, 0)
}
cateLevelPath[v.Level-1][v.Pid] = append(cateLevelPath[v.Level-1][v.Pid], &CategoryDic{Category: v})
}
cate := cateIteration(cateLevelPath[0], cateIteration(cateLevelPath[1], cateLevelPath[2]))[0]
cateJsonByte, _ = json.Marshal(cate)
return
}
func cateIteration(parent map[int][]*CategoryDic, child map[int][]*CategoryDic) map[int][]*CategoryDic {
for _, v := range parent {
for _, vv := range v {
vv.Children = child[vv.Id]
}
}
return parent
}
func cateAll() (data []Category) {
var (
row Category
)
db, err, clean := utils_gorm.DB(driver, dns)
defer clean()
if err != nil {
panic(err)
}
rows, _ := db.Raw(fmt.Sprintf("SELECT id,name,level,pid FROM `%s` where `type`=2", table)).Rows()
defer rows.Close()
for rows.Next() {
err = db.ScanRows(rows, &row)
if err != nil {
panic(err)
}
data = append(data, row)
}
return
}