package plant

import (
	"sundynix-go/global"
	"sundynix-go/model/plant"
	plantReq "sundynix-go/model/plant/request"
	"sundynix-go/model/system"

	"gorm.io/gorm"
)

type UserProfileService struct{}

// UpdateProfile 修改用户信息
func (s *UserProfileService) UpdateProfile(req plantReq.UpdateProfile, userId string) error {
	return global.DB.Transaction(func(tx *gorm.DB) error {
		//1.更新profile
		updateMap := map[string]interface{}{
			"nick_name": req.Nickname,
			"avatar_id": req.AvatarId,
		}
		err := tx.Model(&plant.UserProfile{}).Where("user_id = ?", userId).Updates(updateMap).Error
		if err != nil {
			return err
		}
		//2.更新user表
		updateMap = map[string]interface{}{
			"name":      req.Nickname,
			"avatar_id": req.AvatarId,
		}
		err = tx.Model(&system.User{}).Where("id = ?", userId).Updates(updateMap).Error
		if err != nil {
			return err
		}
		return nil
	})
}

// ProfileDetail 获取用户详情
func (s *UserProfileService) ProfileDetail(userId string) (plant.UserProfile, error) {
	var res plant.UserProfile
	err := global.DB.Where("user_id = ?", userId).
		Preload("Avatar").
		Preload("Level").
		First(&res).Error
	if err != nil {
		return res, err
	}
	return res, nil
}

// MyStars 我的收藏
func (s *UserProfileService) MyStars(req plantReq.StarsPageReq, userId string) (list interface{}, total int64, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.Current - 1)
	db := global.DB.Model(&plant.UserStar{}).Preload("Wiki", func(db *gorm.DB) *gorm.DB {
		return db.Preload("ImgList", func(db *gorm.DB) *gorm.DB {
			return db.Order("created_at desc")
		})
	}).Preload("Post", func(db *gorm.DB) *gorm.DB {
		return db.Preload("ImgList", func(db *gorm.DB) *gorm.DB {
			return db.Order("created_at desc")
		})
	})
	var stars []*plant.UserStar
	db = db.Where("user_id = ?", userId)
	if req.Class != 0 {
		db = db.Where("type = ?", req.Class) //1.百科 //2.社交动态
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("created_at desc").Find(&stars).Error
	return stars, total, err
}

// MyBadges 我的徽章
func (s *UserProfileService) MyBadges(userId string) ([]plant.UserBadge, error) {
	var badges []plant.UserBadge
	err := global.DB.Where("user_id = ?", userId).
		Preload("Badge", func(db *gorm.DB) *gorm.DB {
			return db.Preload("Icon")
		}).
		Find(&badges).Error
	return badges, err
}
