package dao

import (
	"time"

	"gorm.io/gorm"
)

type User struct {
	ID        int32          `gorm:"primarykey;type:int"`
	CreatedAt time.Time      `gorm:"type:datetime(0)"`
	UpdatedAt time.Time      `gorm:"type:datetime(0)"`
	DeletedAt gorm.DeletedAt `gorm:"index;type:datetime(0)"`
	Username  string         `gorm:"type:varchar(64);default null;comment:'用户名称'"`
	OpenId    string         `gorm:"type:varchar(255);default null;comment:'用户唯一标识'"`
	AvatarId  string         `gorm:"type:varchar(32);default null;comment:'头像图片uuid'"`
	Tags      string         `gorm:"type:json;default null;comment:'用户标签,json格式'"`
	Persona   string         `gorm:"type:json;default null;comment:'用户个性化数据,json格式'"`
}

func (User) TableName() string { return "user" }

func User_WX_Insert(data *User) (int32, error) {
	if err := s.db.Create(data).Error; err != nil {
		return 0, err
	}
	return data.ID, nil
}

func User_WX_Query(openId string) (*User, error) {
	var data User
	if err := s.db.Where("open_id = ?", openId).First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &data, nil
}

func User_Query(userId int32) (*User, error) {
	var data User
	if err := s.db.Where("id = ?", userId).First(&data).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		}
		return nil, err
	}
	return &data, nil
}

// 修改用户名称
func User_Change_Username(userId int32, username string) error {
	user := &User{ID: userId}
	return s.db.Model(&user).Update("username", username).Error
}

// 修改用户头像
func User_Change_AvatarId(userId int32, avatarId string) error {
	user := &User{ID: userId}
	return s.db.Model(&user).Update("avatar_id", avatarId).Error
}

// 查询用户信息列表，如果不存在，则设置为nil
func User_Query_List(userIds []int32) (map[int32]*User, error) {
	var list []*User
	if err := s.db.Where("id in (?)", userIds).Find(&list).Error; err != nil {
		return nil, err
	}

	reply := make(map[int32]*User)
	for _, data := range list {
		reply[data.ID] = data
	}
	return reply, nil
}

type UserBaseInfo struct {
	ID       int32  `gorm:"column:id"`
	Username string `gorm:"column:username"`
	AvatarId string `gorm:"column:avatar_id"`
}

// 批量查询用户的名称和头像信息
func User_Query_List_BaseInfo(userIds []int32) (map[int32]*UserBaseInfo, error) {
	var list []*UserBaseInfo
	if err := s.db.Model(&User{}).Where("id in (?)", userIds).Select("id, username, avatar_id").Find(&list).Error; err != nil && err != gorm.ErrRecordNotFound {
		return nil, err
	}

	m := make(map[int32]*UserBaseInfo)
	for _, info := range list {
		m[info.ID] = info
	}

	return m, nil
}
