package message

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

	"github.com/astaxie/beego"
)

const (
	ForwardTypeUrl    = "url"
	ForwardTypeCourse = "course"
)

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

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

// GetImgByLocation 根据位置获取图片
func (s *MessageServ) GetImgByLocation(locationid, orgid string) ([]model.TaCmsImages, error) {
	imgs, err := s.dao.GetImgByLocation(locationid, orgid)
	return imgs, err
}

// GetImgByID 获取单条图片信息
func (s *MessageServ) GetImgByID(imgid string) (*model.TaCmsImages, error) {
	img, err := s.dao.GetImgByID(imgid)
	return img, err
}

// SaveImg 保存轮播图信息
func (s *MessageServ) SaveImg(imginfo model.TaCmsImages) (*model.TaCmsImages, error) {
	if imginfo.ImageUrl == "" {
		return nil, errors.New("图片不允许为空！")
	}

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

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

	if imginfo.ImageId == "" {
		newinfo, err := s.dao.AddCmsImg(imginfo)
		return newinfo, err
	}
	err := s.dao.UpdateCmsImg(imginfo)
	return &imginfo, err
}

// DelImg 删除轮播图
func (s *MessageServ) DelImg(imgid string) error {
	err := s.dao.DelCmsImg(imgid)
	return err
}
