package plant

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

	"gorm.io/gorm"
)

type TopicService struct{}

var TopicServiceApp = new(TopicService)

// AddTopic 发布话题
func (s *TopicService) AddTopic(req plantReq.CreateTopic) error {
	// 查询是否存在
	if !errors.Is(global.DB.Where("title = ?", req.Title).First(&plant.Topic{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在重复话题")
	}
	start, _ := time.Parse("2006-01-02 15:04:05", req.StartTime)
	end, _ := time.Parse("2006-01-02 15:04:05", req.EndTime)
	return global.DB.Create(&plant.Topic{
		Title:     req.Title,
		StartTime: start,
		EndTime:   end,
		Remark:    req.Remark,
	}).Error
}

// UpdateTopic 修改话题
func (s *TopicService) UpdateTopic(req plantReq.UpdateTopic) error {
	start, _ := time.Parse("2006-01-02 15:04:05", req.StartTime)
	end, _ := time.Parse("2006-01-02 15:04:05", req.EndTime)
	updateMap := map[string]interface{}{
		"title":      req.Title,
		"start_time": start,
		"end_time":   end,
		"remark":     req.Remark,
	}
	err := global.DB.Model(&plant.Topic{}).Where("id = ?", req.Id).Updates(updateMap).Error
	return err
}

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

// TopicList 话题列表
func (s *TopicService) TopicList() (list interface{}, err error) {
	var topics []plant.Topic
	err = global.DB.Order("created_at desc").Find(&topics).Error
	return topics, err
}

// Detail 话题详情
func (s *TopicService) Detail(id string) (t plant.Topic, err error) {
	var res plant.Topic
	err = global.DB.Where("id = ?", id).First(&res).Error
	if err != nil {
		return res, err
	}
	return res, nil
}

// DeleteTopics 删除话题
func (s *TopicService) DeleteTopics(req common.IdsReq) error {
	var topics []plant.Topic
	err := global.DB.Where("id in ?", req.Ids).Find(&topics).Error
	if err != nil {
		return err
	}
	err = global.DB.Unscoped().Delete(&topics).Error
	if err != nil {
		return err
	}
	return nil
}
