package service

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

	"go-admin/app/operate/models"
	"go-admin/app/operate/service/dto"
	"go-admin/common/actions"
)

type OrgTeamMatchEvaluate struct {
	service.Service
}

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

	field := "omtp.id, ol.league_name, od.division_name, os.season_name, om.rounds," +
		"omtp.player_name, om.match_start_time, om.match_end_time, " +
		"IF(ome.content_status='' or ome.content_status is null,1,ome.content_status)as content_status," +
		"ome.mv_status, ome.status, ome.remark"
	err = e.Orm.Table("org_match_team_player as omtp").
		Select(field).
		Joins("left join org_match_evaluate as ome on omtp.match_id = ome.match_id and omtp.rounds = ome.rounds and omtp.player_id = ome.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").
		Joins("left join org_division as od on od.id = om.division_id").
		Joins("left join org_season as os on os.id = om.season_id").
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
			actions.Permission("omtp", p),
			cDto.PassDel("omtp"),
		).
		Where("om.status=?", 3).
		Where("omtp.team_id=?", c.TeamId).
		Find(list).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("OrgMatchService GetPage error:%s \r\n", err)
		return err
	}
	return nil
}

// GetPage 获取OrgMatchEvaluate列表
func (e *OrgTeamMatchEvaluate) GetMatchInfo(id string, p *actions.DataPermission, data *cDto.PageMatchInfo) error {
	var err error

	err = e.Orm.Table("org_match_team_player as omtp").
		Select("omtp.id, omtp.match_id, omtp.team_id, ol.league_name, od.division_name, os.season_name, om.rounds,"+
			"oc.club_name, ot.team_name, omtp.player_name, omtp.player_number, omtp.position,"+
			"ome.wonderful_moment_img, ome.wonderful_moment_mv,ome.wonderful_moment_img_title,"+
			"ome.wonderful_moment_mv_title, ome.content, omtp.player_id, om.season_id").
		Joins("left join org_match_evaluate as ome on omtp.player_id = ome.player_id and omtp.match_id=ome.match_id and omtp.rounds=ome.rounds").
		Joins("left join org_club as oc on omtp.club_id = oc.id").
		Joins("left join org_team as ot on omtp.team_id = ot.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").
		Joins("left join org_division as od on od.id = om.division_id").
		Joins("left join org_season as os on os.id = om.season_id").
		Scopes(
			actions.Permission("omtp", p),
		).
		First(data, id).Error
	if err != nil {
		e.Log.Errorf("OrgMatchService GetMatchInfo error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *OrgTeamMatchEvaluate) GetRoundsScoring(playerId string, rounds string, teamPlayerId string, data *[]cDto.RoundsScoring) error {
	var err error

	err = e.Orm.Table("org_match_team_player as omtp").
		Select("omtp.id, om.match_start_time, om.rounds, om.grouping, ot.team_name as other_team, "+
			"omtp.scoring, omtp.scoring, omtp.rebound, omtp.assist, omtp.steal, omtp.free_throw, "+
			"omtp.block_shot, omtp.foul, omtp.two_point_shot, omtp.three_point_shot").
		Joins("left join org_match as om on omtp.match_id = om.id and omtp.rounds = om.rounds").
		Joins("left join org_team as ot on omtp.other_team_id = ot.id").
		Scopes(
			cDto.SetWhere("omtp", "player_id", playerId),
			cDto.SetWhere("omtp", "rounds", rounds),
			cDto.SetWhere("omtp", "id", teamPlayerId),
		).
		Find(data).Error
	if err != nil {
		e.Log.Errorf("OrgMatchService GetRoundsScoring error:%s \r\n", err)
		return err
	}
	return nil
}

func (e *OrgTeamMatchEvaluate) statisticsScoring(playerId string, rounds string, seasonId string, statistics string, data *cDto.TotalScoring) error {
	var err error
	field := ""

	if statistics == "sum" {
		field += "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"
	}

	if statistics == "avg" {
		field += "avg(omtp.scoring)as scoring," +
			"avg(omtp.rebound)as rebound," +
			"avg(omtp.assist)as assist," +
			"avg(omtp.steal)as steal," +
			"avg(omtp.free_throw)as free_throw," +
			"avg(omtp.block_shot)as block_shot," +
			"avg(omtp.foul)as foul," +
			"avg(omtp.two_point_shot)as two_point_shot," +
			"avg(omtp.three_point_shot)as three_point_shot"
	}

	err = e.Orm.Table("org_match_team_player as omtp").
		Joins("left join org_match as om on omtp.match_id = om.id and omtp.rounds = om.rounds").
		Select(field).
		Where("omtp.player_id = ?", playerId).
		Where("omtp.rounds = ?", rounds).
		Scopes(cDto.SetWhere("om", "season_id", seasonId)).
		First(data).Error

	if err != nil {
		e.Log.Errorf("OrgMatchService GetTotalScoring error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取OrgMatchEvaluate对象
func (e *OrgTeamMatchEvaluate) GetTotalScoring(playerId string, rounds string, seasonId string, data *[]cDto.TotalScoring) error {
	replyGetTotalScoring1 := new(cDto.TotalScoring)
	e.statisticsScoring(playerId, rounds, "0", "sum", replyGetTotalScoring1)
	*data = append(*data, *replyGetTotalScoring1)

	replyGetTotalScoring2 := new(cDto.TotalScoring)
	e.statisticsScoring(playerId, rounds, "0", "avg", replyGetTotalScoring2)
	*data = append(*data, *replyGetTotalScoring2)

	replyGetTotalScoring3 := new(cDto.TotalScoring)
	e.statisticsScoring(playerId, rounds, seasonId, "sum", replyGetTotalScoring3)
	*data = append(*data, *replyGetTotalScoring3)

	replyGetTotalScoring4 := new(cDto.TotalScoring)
	e.statisticsScoring(playerId, rounds, seasonId, "avg", replyGetTotalScoring4)
	*data = append(*data, *replyGetTotalScoring4)

	replyGetTotalScoring5 := new(cDto.TotalScoring)
	e.statisticsRankingList(playerId, seasonId, replyGetTotalScoring5)
	*data = append(*data, *replyGetTotalScoring5)

	return nil
}

func (e *OrgTeamMatchEvaluate) statisticsRankingList(playerId string, seasonId string, scoring *cDto.TotalScoring) error {

	replyGetPlayerRank := make([]models.OrgMatchTeamPlayer, 0)
	err := e.statisticsRanking(seasonId, &replyGetPlayerRank)
	if err != nil {
		e.Log.Errorf("OrgMatchService GetTotalScoring error:%s \r\n", err)
		return err
	}
	e.rankingScoring(replyGetPlayerRank, playerId, scoring)
	e.rankingRebound(replyGetPlayerRank, playerId, scoring)
	e.rankingAssist(replyGetPlayerRank, playerId, scoring)
	e.rankingSteal(replyGetPlayerRank, playerId, scoring)
	e.rankingFreeThrow(replyGetPlayerRank, playerId, scoring)
	e.rankingBlockShot(replyGetPlayerRank, playerId, scoring)
	e.rankingFoul(replyGetPlayerRank, playerId, scoring)
	e.rankingTwoPointShot(replyGetPlayerRank, playerId, scoring)
	e.rankingThreePointShot(replyGetPlayerRank, playerId, scoring)

	return nil
}

func (e *OrgTeamMatchEvaluate) rankingScoring(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].Scoring > replyGetPlayerRank[j].Scoring
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.Scoring = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingRebound(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].Rebound > replyGetPlayerRank[j].Rebound
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.Rebound = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingAssist(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].Assist > replyGetPlayerRank[j].Assist
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.Assist = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingSteal(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].Steal > replyGetPlayerRank[j].Steal
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.Steal = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingFreeThrow(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].FreeThrow > replyGetPlayerRank[j].FreeThrow
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.FreeThrow = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingBlockShot(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].BlockShot > replyGetPlayerRank[j].BlockShot
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.BlockShot = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingFoul(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].Foul > replyGetPlayerRank[j].Foul
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.Foul = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingTwoPointShot(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].TwoPointShot > replyGetPlayerRank[j].TwoPointShot
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.TwoPointShot = strconv.Itoa(k + 1)
		}
	}
}
func (e *OrgTeamMatchEvaluate) rankingThreePointShot(replyGetPlayerRank []models.OrgMatchTeamPlayer, playerId string, scoring *cDto.TotalScoring) {
	sort.Slice(replyGetPlayerRank, func(i, j int) bool {
		return replyGetPlayerRank[i].ThreePointShot > replyGetPlayerRank[j].ThreePointShot
	})
	for k, v := range replyGetPlayerRank {
		if v.PlayerId == playerId {
			scoring.ThreePointShot = strconv.Itoa(k + 1)
		}
	}
}

func (e *OrgTeamMatchEvaluate) statisticsRanking(seasonId string, data *[]models.OrgMatchTeamPlayer) error {
	var err error
	field := "player_id," +
		"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"
	err = e.Orm.Table("org_match_team_player as omtp").
		Select(field).
		Joins("left join org_match as om on omtp.match_id = om.id").
		Where("om.season_id = ?", seasonId).
		Order("player_id asc").
		Group("player_id").
		Find(&data).Error

	if err != nil {
		e.Log.Errorf("OrgMatchService GetTotalScoring error:%s \r\n", err)
		return err
	}
	return nil
}

// Get 获取OrgMatchEvaluate对象
func (e *OrgTeamMatchEvaluate) Get(d *dto.OrgMatchEvaluateGetReq, p *actions.DataPermission, model *models.OrgMatchEvaluate) error {
	var data models.OrgMatchEvaluate

	err := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).
		First(model, d.GetId()).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetOrgMatchEvaluate error:%s \r\n", err)
		return err
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err
	}
	return nil
}

// Insert 创建OrgMatchEvaluate对象
func (e *OrgTeamMatchEvaluate) Insert(c *dto.OrgMatchEvaluateInsertReq) (error, int) {
	var err error
	var data models.OrgMatchEvaluate
	c.Generate(&data)
	err = e.Orm.Create(&data).Error
	if err != nil {
		e.Log.Errorf("OrgMatchEvaluateService Insert error:%s \r\n", err)
		return err, 0
	}
	return nil, data.Id
}

// Update 修改OrgMatchEvaluate对象
func (e *OrgTeamMatchEvaluate) Update(c *dto.OrgTeamMatchEvaluateUpdateReq, p *actions.DataPermission) (error, int) {
	var err error
	var data = models.OrgMatchEvaluate{}
	e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).
		Where("match_id = ?", c.MatchId).
		Where("rounds = ?", c.Rounds).
		Where("player_id = ?", c.PlayerId).
		First(&data)

	id := data.Id
	c.Generate(&data)

	db := e.Orm.Scopes(
		actions.Permission(data.TableName(), p),
	).
		Where("match_id = ?", c.MatchId).
		Where("rounds = ?", c.Rounds).
		Where("player_id = ?", c.PlayerId).
		Updates(&data)
	if db.Error != nil {
		e.Log.Errorf("OrgMatchEvaluateService Save error:%s \r\n", err)
		return err, 0
	}
	if db.RowsAffected == 0 {
		return errors.New("无权更新该数据"), 0
	}
	return nil, id
}

// Remove 删除OrgMatchEvaluate
func (e *OrgTeamMatchEvaluate) Remove(d *dto.OrgMatchEvaluateDeleteReq, p *actions.DataPermission) error {
	var data models.OrgMatchEvaluate

	db := e.Orm.Model(&data).
		Scopes(
			actions.Permission(data.TableName(), p),
		).Delete(&data, d.GetId())
	if err := db.Error; err != nil {
		e.Log.Errorf("Service RemoveOrgMatchEvaluate error:%s \r\n", err)
		return err
	}
	if db.RowsAffected == 0 {
		return errors.New("无权删除该数据")
	}
	return nil
}

// Insert 创建OrgMatchTeamPlayer对象
func (e *OrgTeamMatchEvaluate) IsBeing(matchId string, rounds string, playerId string) (error, int) {
	var data models.OrgMatchEvaluate

	err := e.Orm.Model(&data).
		Where("match_id=?", matchId).
		Where("rounds=?", rounds).
		Where("player_id=?", playerId).
		First(&data).Error
	if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("查看对象不存在或无权查看")
		e.Log.Errorf("Service GetOrgMatchTeamPlayer error:%s \r\n", err)
		return err, 0
	}
	if err != nil {
		e.Log.Errorf("db error:%s", err)
		return err, 0
	}
	return nil, data.Id
}
