package plant

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

	"gorm.io/gorm"
)

type WikiClassService struct{}

var WikiClassServiceApp = new(WikiClassService)

// AddClass 添加分类
func (s *WikiClassService) AddClass(req plantReq.CreateWikiClass) error {
	//1.查询name是否存在 2.查询oss是否存在
	if !errors.Is(global.DB.Where("name = ?", req.Name).First(&plant.Class{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在重复分类名称，请修改名称")
	}
	if req.OssId != "" {
		if errors.Is(global.DB.Where("id = ?", req.OssId).First(&system.Oss{}).Error, gorm.ErrRecordNotFound) {
			return errors.New("不存在此图片")
		}
	}
	return global.DB.Create(&plant.Class{
		Name:  req.Name,
		OssId: req.OssId,
	}).Error
}

// UpdateClass 修改分类
func (s *WikiClassService) UpdateClass(req plantReq.UpdateWikiClass) error {
	updateMap := map[string]interface{}{
		"name": req.Name,
		"oss":  req.OssId,
	}
	return global.DB.Model(&plant.Class{}).Where("id = ?", req.Id).Updates(updateMap).Error
}

func (s *WikiClassService) ClassPage(req common.PageInfo) (list interface{}, total int64, err error) {
	limit := req.PageSize
	offset := req.PageSize * (req.Current - 1)
	db := global.DB.Model(&plant.Class{})
	var classes []plant.Class
	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(limit).Offset(offset).Order("created_at desc").Find(&classes).Error
	return classes, total, err
}

// DeleteClass 删除分类
func (s *WikiClassService) DeleteClass(req common.IdsReq) error {
	var classes []plant.Class
	if err := global.DB.Where("id in ?", req.Ids).Find(&classes).Error; err != nil {
		return err
	}
	// todo 删除关联?
	return global.DB.Unscoped().Delete(&classes).Error
}

// ClassList 列表
func (s *WikiClassService) ClassList() (list interface{}, err error) {
	var classes []plant.Class
	err = global.DB.Preload("Oss").Order("created_at desc").Find(&classes).Error
	if err != nil {
		return
	}
	return classes, err
}

// Detail 详情
func (s *WikiClassService) Detail(id string) (c plant.Class, err error) {
	var class plant.Class
	err = global.DB.Where("id = ?", id).Preload("Oss").First(&class).Error
	//不存在的时候不要返回错误，而是返回nil
	if err != nil {
		return
	}
	return class, nil
}
