package service

import (
	"errors"

	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"

	"go-admin/app/mobile/service/dto"
	"go-admin/app/operate/models"
	"go-admin/common/actions"
	cDto "go-admin/common/dto"
)

type OrgNews struct {
	service.Service
}

// GetPage 获取OrgNews列表
func (e *OrgNews) GetPage(c *dto.OrgNewsGetPageReq, p *actions.DataPermission, list *[]dto.OrgNews, count *int64) error {
	var err error
	var data models.OrgNews

	err = e.Orm.Table("org_news as on1").
		Select("on1.id, on1.news_title, on1.news_img, on1.created_at, onc.comment_count").
		Joins("left join (select count(id) as comment_count,news_id from org_news_comment group by news_id)onc on on1.id=onc.news_id").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission(data.TableName(), p),
		).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("OrgNewsService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取OrgNews对象
func (e *OrgNews) Get(d *dto.OrgNewsGetReq, p *actions.DataPermission, model *models.OrgNews) error {
	var data models.OrgNews

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetOrgNews error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}
