package message

import (
	"spaceofcheng/services/models/message"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service"
	"spaceofcheng/services/utils"

	"github.com/astaxie/beego"
)

// MessageServ 系统处理
type MessageServ struct {
	ctx *utils.Context
	dao *message.MessageDAO
}

// NewMessageServ 初始化
func NewMessageServ(ctx *utils.Context) *MessageServ {
	return &MessageServ{
		ctx: ctx,
		dao: message.NewMessageDAO(ctx),
	}
}

// GetCmsInfoList 获取消息管理列表
func (s *MessageServ) GetCmsInfoList(title, orgid string, page int, pageSize int) (map[string]interface{}, error) {
	if pageSize == 0 {
		pageSize = service.PAGENUM
	}
	if page == 0 {
		page = 1
	}
	infos, err := s.dao.GetCmsInfoList(title, orgid, page, pageSize)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	total, err := s.dao.GetCmsInfoListCount(title, orgid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

	return map[string]interface{}{
		"list":     infos,
		"pagesize": pageSize,
		"pagenum":  total,
		"page":     page,
	}, err
}

// GetCmsInfoByLocation 根据位置ID获取消息列表
func (s *MessageServ) GetCmsInfoByLocation(locationid, orgid string) ([]model.TaCmsInfo, error) {
	infos, err := s.dao.GetCmsInfoByLocation(locationid, orgid)
	return infos, err
}

// GetCmsInfoByID 获取单条消息信息
func (s *MessageServ) GetCmsInfoByID(id string) (*model.TaCmsInfo, error) {
	info, err := s.dao.GetCmsInfoByID(id)
	return info, err
}

// SaveCmsInfo 保存消息信息
func (s *MessageServ) SaveCmsInfo(cmsinfo model.TaCmsInfo) (*model.TaCmsInfo, error) {
	if cmsinfo.InfoId == "" {
		newcmsinfo, err := s.dao.AddCmsInfo(cmsinfo)
		return newcmsinfo, err
	}
	err := s.dao.UpdateCmsInfo(cmsinfo)
	return &cmsinfo, err
}

// DelCmsInfo 删除消息信息
func (s *MessageServ) DelCmsInfo(infoid string) error {
	err := s.dao.DelCmsInfo(infoid)
	return err
}
