package message

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

	"github.com/astaxie/beego"
)

// GetNewsList 获取咨询列表
func (s *MessageServ) GetNewsList(locationid, 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.GetNewsList(locationid, orgid, page, pageSize)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	total, err := s.dao.GetNewsListCount(locationid, orgid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}

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

// GetNewsByLocation 根据位置id获取咨询信息
func (s *MessageServ) GetNewsByLocation(locationid, orgid string) ([]model.TaCmsNews, error) {
	news, err := s.dao.GetNewsByLocation(locationid, orgid)
	return news, err
}

// GetNewsByID 获取咨询详情
func (s *MessageServ) GetNewsByID(newsid string) (*message.CmsNews, error) {
	info, err := s.dao.GetNewsByID(newsid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	newslocation, err := s.dao.GetNewsLocationByID(newsid)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	info.NewsLocations = newslocation
	return info, nil
}

// SaveNews 保存咨询信息
func (s *MessageServ) SaveNews(news model.TaCmsNews, locationids string) (*model.TaCmsNews, error) {
	var newInfo *model.TaCmsNews
	var err error
	if news.Title == "" {
		return nil, errors.New("咨询标题不允许为空！")
	}

	if news.ImageUrl == "" {
		return nil, errors.New("图片不允许为空！")
	}

	if news.ForwardType == "" {
		return nil, errors.New("跳转类型不允许为空！")
	}
	if news.ForwardType == ForwardTypeUrl && news.ForwardUrl == "" {
		return nil, errors.New("跳转地址不允许为空！")
	}

	if news.ForwardType == ForwardTypeCourse && news.CaseId == "" {
		return nil, errors.New("跳转资源不允许为空！")
	}

	if news.NewsId == "" {
		newInfo, err = s.dao.AddNews(news)
	} else {
		err = s.dao.UpdateNews(news)
		newInfo = &news
	}
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	err = s.dao.DelNewsLocation(newInfo.NewsId)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	err = s.dao.SaveNewsLocation(newInfo.NewsId, locationids)
	if err != nil {
		beego.Error(err)
		return nil, err
	}
	return newInfo, err
}

// DelNews 刪除咨询信息
func (s *MessageServ) DelNews(newsid string) error {
	err := s.dao.DelNews(newsid)
	return err
}
