package channel

import (
	"spaceofcheng/services/models/channel"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/service"
	"spaceofcheng/services/utils"
)

// ChannelServ 系统处理
type ChannelServ struct {
	ctx *utils.Context
	dao *channel.ChannelDAO
}

// NewChannelServ 初始化
func NewChannelServ(ctx *utils.Context) *ChannelServ {
	return &ChannelServ{
		ctx: ctx,
		dao: channel.NewChannelDAO(ctx),
	}
}

// GetChannelList 获取渠道列表
func (s *ChannelServ) GetChannelList(caseid string, page, pageSize int) (map[string]interface{}, error) {
	if pageSize == 0 {
		pageSize = service.PAGENUM
	}
	channels, err := s.dao.GetChannels(caseid, page, pageSize)
	if err != nil {
		return nil, err
	}
	total, err := s.dao.GetChannelsCount(caseid)
	if err != nil {
		return nil, err
	}
	return map[string]interface{}{
		"list":     channels,
		"pageSize": pageSize,
		"pagenum":  total,
		"page":     page,
	}, err
}

// GetChannelById 根据渠道id获取渠道
func (s *ChannelServ) GetChannelById(channelId string) (*model.TaChannel, error) {
	channel, err := s.dao.GetChannelById(channelId)
	return channel, err
}

// SaveChannel 保存渠道
func (s *ChannelServ) SaveChannel(channel model.TaChannel) (*model.TaChannel, error) {
	var newChannel *model.TaChannel
	var err error
	if channel.ChannelId == "" {
		newChannel, err = s.dao.AddNewChannel(channel)
	} else {
		err = s.dao.UpdateChannel(channel)
		newChannel = &channel
	}
	return newChannel, err
}

// DeleteChannel 删除渠道
func (s *ChannelServ) DeleteChannel(caseid string) error {
	err := s.dao.DeleteChannel(caseid)
	return err
}
