package service

import (
	"errors"
	"time"

	"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 OrgMsg struct {
	service.Service
}

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

	err = e.Orm.Model(&data).
		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("OrgMsgService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取OrgMsg对象
func (e *OrgMsg) Get(d *dto.OrgMsgGetReq) error {
	var data models.OrgMsg

	reply := new(models.OrgMsg)
	now := time.Now()
	negativeM, _ := time.ParseDuration("-5m")
	nowBefore5Minute := now.Add(negativeM)

	err := e.Orm.Model(&data).
		Scopes(cDto.PassDel("org_msg")).
		Where("code=?", d.Code).
		Where("username=?", d.Username).
		Where("created_at>?", nowBefore5Minute).
		Where("msg_type=?", d.MsgType).
		Order("id desc").
		First(&reply).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetOrgMsg error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建OrgMsg对象
func (e *OrgMsg) Insert(c *dto.OrgMsgInsertReq) error {
	var err error
	var data models.OrgMsg
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("OrgMsgService Insert error:%s \r\n", err)
		return err
	}
	return nil
}

// Update 修改OrgMsg对象
func (e *OrgMsg) Update(c *dto.OrgMsgUpdateReq, p *actions.DataPermission) error {
	var err error
	var data = models.OrgMsg{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).First(&data, c.GetId())
	c.Generate(&data)

	db := e.Orm.Save(&data)
	if db.Error != nil {
		e.Log.Errorf("OrgMsgService Save error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据")
	}
	return nil
}

// Remove 删除OrgMsg
func (e *OrgMsg) Remove(username string) error {
	var data models.OrgMsg

	db := e.Orm.Model(&data).Where("username=?", username).Delete(&data)
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveOrgMsg error:%s \r\n", err)
		return err
	}
	return nil
}
