package channel

import (
	"spaceofcheng/services/models"
	"spaceofcheng/services/models/model"
	"spaceofcheng/services/utils"
	"strconv"
	"strings"
	"time"

	"github.com/go-xorm/xorm"
)

// ChannelDAO 当前数据库操作对象
type ChannelDAO struct {
	ctx *utils.Context
	db  *xorm.Session
}

// NewChannelDAO New Inst
func NewChannelDAO(ctx *utils.Context) *ChannelDAO {
	return &ChannelDAO{
		ctx: ctx,
		db:  ctx.DB,
	}
}

type Channel struct {
	model.TaChannel `xorm:"extends"`
	CaseName        string
}

// GetChannelsCount 获取渠道总数
func (m *ChannelDAO) GetChannelsCount(caseid string) (int, error) {
	var channels []model.TaChannel
	dao := m.db.Where("status >" + strconv.Itoa(models.STATUS_DEL)).And("case_id in ('" + strings.Replace(caseid, ",", "','", -1) + "')")
	err := dao.Find(&channels)
	return len(channels), err
}

// GetChannels 根据案场获取渠道
func (m *ChannelDAO) GetChannels(caseid string, page int, pageSize int) ([]Channel, error) {
	var channels []Channel
	sql := `
	select a.*,b.case_name 
	from ta_channel a 
	inner join sys_case b on a.case_id = b.case_id 
	where a.case_id in('` + strings.Replace(caseid, ",", "','", -1) + `') and b.status> ` + strconv.Itoa(models.STATUS_DEL) + ` and  a.status > ` + strconv.Itoa(models.STATUS_DEL)
	sql += ` order by a.create_date desc limit ` + strconv.Itoa((page-1)*pageSize) + `, ` + strconv.Itoa(page*pageSize)
	err := m.db.Sql(sql).Find(&channels)
	return channels, err
}

// GetChannelById 根据渠道id获取渠道
func (m *ChannelDAO) GetChannelById(channelId string) (*model.TaChannel, error) {
	var channel []model.TaChannel
	err := m.db.Where("channel_id = ?", channelId).And("status > ?", models.STATUS_DEL).Find(&channel)
	if err != nil {
		return nil, err
	}
	if len(channel) > 0 {
		return &channel[0], nil
	}
	return nil, nil
}

// AddNewChannel 新增渠道
func (m *ChannelDAO) AddNewChannel(channel model.TaChannel) (*model.TaChannel, error) {
	channel.ChannelId = utils.GetGUID()
	channel.CreateDate = time.Now()
	channel.Status = models.STATUS_NORMAL
	_, err := m.db.Insert(channel)
	return &channel, err
}

// UpdateChannel 修改渠道
func (m *ChannelDAO) UpdateChannel(channel model.TaChannel) error {
	var cols = []string{
		"channel_name",
		"case_id",
		"org_id",
	}
	_, err := m.db.Cols(cols...).Where("channel_id=?", channel.ChannelId).Update(channel)
	return err
}

// DeleteChannel 删除渠道
func (m *ChannelDAO) DeleteChannel(channelId string) error {
	var channel = model.TaChannel{
		ChannelId: channelId,
		Status:    models.STATUS_DEL,
	}
	var cols = []string{
		"status",
	}
	_, err := m.db.Cols(cols...).Where("channel_id=?", channel.ChannelId).Update(channel)
	return err
}
