package models

import (
	"bsm/full/module/ec/mall/internal/impl"
	"git.apinb.com/bsm-sdk/core/types"
	"git.apinb.com/bsm-sdk/core/utils"
	"gorm.io/gorm"
)

type ContentType int32

const (
	CONTENT_TYPE_TEXT       ContentType = iota + 1 // 1.文本
	CONTENT_TYPE_IMAGE                             // 2.图片
	CONTENT_TYPE_VIDEO                             // 3.视频
	CONTENT_TYPE_AUDIO                             // 4.音频
	CONTENT_TYPE_LINK                              // 5.连接
	CONTENT_TYPE_ATTACHMENT                        // 6.附件
)

const (
	// NormalStatus .
	NormalStatus = 1
	// DisabledStatus .
	DisabledStatus = -1
)

type Std_Store struct {
	Store_ID       uint   `gorm:"primarykey;"  json:"store_id"`                                         // 店铺ID
	Store_Identity string `gorm:"column:store_identity;type:varchar(36);index;"  json:"store_identity"` // 店铺唯一标识，24位NanoID,36位为ULID
}

// 初始化数据
func InitData() {
	CreateStore("to b", "localhost")
}

func CreateStore(title, domain string) {
	var cnt int64 = 0

	// 创建默认目录
	var store MallStore
	err := impl.DBService.Model(&MallStore{}).Where("subdomain=?", domain).First(&store).Error
	if err == gorm.ErrRecordNotFound {
		store = MallStore{
			Title:      title,
			Subdomain:  domain,
			Std_IICUDS: types.Std_IICUDS{Identity: utils.UUID(), Status: NormalStatus},
		}
		impl.DBService.Create(&store)
	}

	// 创建默认目录
	err = impl.DBService.Model(&MallStaff{}).Where("store_identity=? and account=?", store.Identity, "root").Count(&cnt).Error
	if cnt == 0 || err != nil {
		salt := utils.RandomString(8)
		root := &MallStaff{
			Std_Store:  Std_Store{Store_ID: store.ID, Store_Identity: store.Identity},
			Account:    "root",
			Password:   utils.Md5("123456" + salt),
			Salt:       salt,
			Role:       "Mall_Admin",
			Std_IICUDS: types.Std_IICUDS{Identity: utils.UUID(), Status: 1},
		}
		impl.DBService.Create(root)
	}
}

// GetCategoryList 获取分类列表
func GetCategoryList(keyword, identity string, id int64) ([]*MallCategory, error) {
	tx := impl.DBService.Preload("Categories").Where("store_identity = ? ", identity).Where("parent_id = 0")
	if id != 0 {
		tx = tx.Where("id = ?", id)
	}
	if keyword != "" {
		tx = tx.Where("title like ?", "%"+keyword+"%")
	}

	data := make([]*MallCategory, 0)
	tx.Order("created_at desc").Find(&data)
	err := tx.Error
	return data, err
}
