package service

import (
	"github.com/go-admin-team/go-admin-core/sdk/service"
	cDto "go-admin/common/dto"
	"go-admin/common/utils"
	"sort"
	"strconv"

	"go-admin/app/mobile/service/dto"
	"go-admin/common/actions"
)

type OrgTeamRank struct {
	service.Service
}

// GetPage 获取OrgMatchEvaluate列表
func (e *OrgTeamRank) GetPage(c *dto.OrgPlayerRankGetPageReq, p *actions.DataPermission, list *[]dto.OrgPlayerRankGetPageReply, count *int64) error {
	var err error

	err = e.Orm.Table("org_match_team_player as omtp").
		Select("ol.league_name, omtp.player_name, omtp.player_id as id, omtp.player_number,"+
			"sum(omtp.scoring)as scoring,"+
			"sum(omtp.rebound)as rebound,"+
			"sum(omtp.assist)as assist,"+
			"sum(omtp.steal)as steal,"+
			"sum(omtp.free_throw)as free_throw,"+
			"sum(omtp.block_shot)as block_shot,"+
			"sum(omtp.foul)as foul,"+
			"sum(omtp.two_point_shot)as two_point_shot,"+
			"sum(omtp.three_point_shot)as three_point_shot").
		Joins("left join org_team as ot on ot.id = omtp.team_id").
		Joins("left join org_player as op on op.id = omtp.player_id").
		Joins("left join org_match as om on omtp.match_id = om.id and omtp.rounds = om.rounds").
		Joins("left join org_league as ol on ol.id = om.league_id").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission("omtp", p),
			cDto.PassDel("omtp"),
			cDto.SetWhere("omtp", "league_id", c.LeagueId),
		).
		Group("omtp.player_id").
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("OrgClubPlayer GetPage error:%s \r\n", err)
		return err
	}

	if c.TypeName == "scoring" {
		e.rankingScoring(list)
	}

	return nil
}

func (e *OrgTeamRank) rankingScoring(list *[]dto.OrgPlayerRankGetPageReply) {
	listData := *list
	sort.Slice(listData, func(i, j int) bool {
		return utils.StringToFloat(listData[i].Scoring) > utils.StringToFloat(listData[j].Scoring)
	})

	for k := range listData {
		listData[k].Rank = strconv.Itoa(k + 1)
	}
}
