package service

import (
	"gadmin/config"
	"gadmin/internal/admin/consts"
	"gadmin/internal/admin/forms"
	"gadmin/internal/gorm/query"
)

var LevelOutput = new(sLevelOutput)

type sLevelOutput struct{}

type LevelOutputReportInfo struct {
	Level   []int64 `json:"Level"`
	Coin    []int64 `json:"Coin"`
	Diamond []int64 `json:"Diamond"`
}

type LevelOutputLogItem struct {
	Level   int64 `json:"Level"`
	Coin    int64 `json:"Coin"`
	Diamond int64 `json:"Diamond"`
}

type LevelOutputInfo struct {
	Info LevelOutputReportInfo `json:"info"`
	Rows []LevelOutputLogItem  `json:"rows"`
}

func (s *sLevelOutput) QueryLog(params forms.LevelOutputReq) (respData LevelOutputInfo, err error) {
	resp := LevelOutputReportInfo{}
	rdb := query.Use(config.DB).ReportLevelOutput
	m := rdb.Select(rdb.ALL, rdb.ID, rdb.Level,
		rdb.Coin.Sum().As("coin"),
		rdb.Diamond.Sum().As("diamond"),
	).Where(rdb.Level.Gte(int64(params.StartLevel)), rdb.Level.Lt(int64(params.EndLevel)))

	switch params.ChannelId {
	case consts.ChannelIdNone:
		// 不选择渠道
	case consts.ChannelIdAllAdv, consts.ChannelIdAllWx, consts.ChannelIdAllTT:
		// 所有的广告渠道
		m = m.Where(rdb.ChannelID.In(Channel.GetIdsByType(params.ChannelId)...))
	default:
		// 指定渠道
		m = m.Where(rdb.ChannelID.Eq(params.ChannelId))
	}

	if params.ServerId > 0 {
		m = m.Where(rdb.ServerID.Eq(int32(params.ServerId)))
	}

	result, err := m.Group(rdb.Level).Order(rdb.Level.Desc()).Find()
	if err != nil {
		return
	}

	for _, v := range result {
		if v != nil {
			resp.Level = append(resp.Level, v.Level)
			resp.Coin = append(resp.Coin, v.Coin)
			resp.Diamond = append(resp.Diamond, v.Diamond)

			item := LevelOutputLogItem{
				Level:   v.Level,
				Coin:    v.Coin,
				Diamond: v.Diamond,
			}
			respData.Rows = append(respData.Rows, item)

		}
	}
	respData.Info = resp
	return
}
