package apis

import (
	"fmt"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	_ "github.com/go-admin-team/go-admin-core/sdk/pkg/response"

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

type OrgTeamMatch struct {
	api.Api
}

func (e OrgTeamMatch) getTeamId(c *gin.Context) string {
	sOrgTeamUser := service.OrgTeamUser{}
	e.MakeContext(c).MakeOrm().MakeService(&sOrgTeamUser.Service)
	_, teamId := sOrgTeamUser.GetTeamId(user.GetUserId(c))
	return teamId
}

// GetPage <球队>获取比赛列表
// @Summary <球队>获取比赛列表
// @Description <球队>获取比赛列表
// @Tags <球队>比赛管理
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Param data body dto.OrgTeamMatchGetPageReq true "data"
// @Success 200 {string} string  "{"code": 200, "data": [...]}"
// @Router /api/v1/org-team-match [get]
// @Security Bearer
func (e OrgTeamMatch) GetPage(c *gin.Context) {
	req := dto.OrgTeamMatchGetPageReq{}
	s := service.OrgTeamMatch{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]dto.OrgTeamMatchGetPageReply, 0)
	var count int64
	fmt.Println(user.GetUserId(c))
	req.TeamId = e.getTeamId(c)

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取比赛 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	for k, v := range list {
		if v.TeamAId == req.TeamId {
			list[k].OwnTeam = "a"
		}
		if v.TeamBId == req.TeamId {
			list[k].OwnTeam = "b"
		}
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Get <球队>获取比赛所有球员
// @Summary <球队>获取比赛所有球员
// @Description <球队>获取比赛所有球员
// @Tags <球队>比赛管理
// @Param id path string false "id"
// @Success 200 {string} string  {data=models.OrgMatch} "{"code": 200, "data": [...]}"
// @Router /api/v1/org-team-match/get-players [get]
// @Security Bearer
func (e OrgTeamMatch) GetPlayers(c *gin.Context) {
	req := dto.OrgPlayerGetPageReq{}
	s := service.OrgPlayer{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]dto.OrgPlayerGetPageReply, 0)
	var count int64

	req.PageIndex = 1
	req.PageSize = 9999

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取球员 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Get <球队>获取比赛已设置球员
// @Summary <球队>获取比赛已设置球员
// @Description <球队>获取比赛已设置球员
// @Tags <球队>比赛管理
// @Param id path string false "id"
// @Success 200 {string} string  {data=models.OrgMatch} "{"code": 200, "data": [...]}"
// @Router /api/v1/org-team-match/get-players-is-set [get]
// @Security Bearer
func (e OrgTeamMatch) GetPlayersIsSet(c *gin.Context) {
	req := dto.OrgMatchTeamPlayerGetPageReq{}
	s := service.OrgMatchTeamPlayer{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	p := actions.GetPermissionFromContext(c)
	list := make([]models.OrgMatchTeamPlayer, 0)
	var count int64

	req.PageIndex = 1
	req.PageSize = 999

	err = s.GetPage(&req, p, &list, &count)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取比赛球员数据 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.PageOK(list, int(count), req.GetPageIndex(), req.GetPageSize(), "查询成功")
}

// Update <球队>修改比赛球员
// @Summary <球队>修改比赛球员
// @Description <球队>修改比赛球员
// @Tags <球队>比赛管理
// @Accept application/json
// @Product application/json
// @Param data body dto.OrgMatchUpdateReq true "body"
// @Success 200 {string} string  	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/org-team-match/update-players [put]
// @Security Bearer
func (e OrgTeamMatch) UpdatePlayers(c *gin.Context) {
	req := dto.UpdateOrgMatchTeamPlayerReq{}
	s := service.OrgMatchTeamPlayer{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}

	if req.MatchId == "" || req.Rounds == "" || req.OtherTeamId == "" {
		e.Logger.Error(err)
		e.Error(500, err, "数据有误，请重新提交")
		return
	}

	playersIds := strings.Split(req.PlayersIds, ",")

	sOrgPlayer := service.OrgPlayer{}
	err = e.MakeContext(c).MakeOrm().MakeService(&sOrgPlayer.Service).Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	p := actions.GetPermissionFromContext(c)

	teamId := ""
	for _, v := range playersIds {
		orgPlayer := new(dto.OrgPlayerGetReply)
		id, _ := strconv.Atoi(v)
		reqOrgPlayer := new(dto.OrgPlayerGetReq)
		reqOrgPlayer.Id = id
		_ = sOrgPlayer.Get(reqOrgPlayer, p, orgPlayer)

		//if orgPlayer.Id == 0 {
		//	e.Error(500, err, "球员不存在")
		//	return
		//}
		teamId = orgPlayer.TeamId
		err, playerId := s.IsBeing(req.MatchId, req.Rounds, v)
		if playerId == 0 {
			orgMatchPlayer := dto.OrgMatchTeamPlayerInsertReq{
				MatchId:      req.MatchId,
				Rounds:       req.Rounds,
				ClubId:       orgPlayer.ClubId,
				TeamId:       orgPlayer.TeamId,
				OtherTeamId:  req.OtherTeamId,
				PlayerId:     v,
				PlayerName:   orgPlayer.PlayerName,
				PlayerNumber: orgPlayer.PlayerNumber,
				Position:     orgPlayer.Position,
			}
			errOrgMatchPlayer := s.Insert(&orgMatchPlayer)
			if errOrgMatchPlayer != nil {
				e.Error(500, err, fmt.Sprintf("创建比赛球员数据  失败，\r\n失败信息 %s", err.Error()))
				return
			}
		} else {
			orgMatchPlayer := dto.OrgMatchTeamPlayerUpdateReq{
				Id:           playerId,
				MatchId:      req.MatchId,
				Rounds:       req.Rounds,
				ClubId:       orgPlayer.ClubId,
				TeamId:       orgPlayer.TeamId,
				OtherTeamId:  req.OtherTeamId,
				PlayerId:     v,
				PlayerName:   orgPlayer.PlayerName,
				PlayerNumber: orgPlayer.PlayerNumber,
				Position:     orgPlayer.Position,
			}
			err = s.Update(&orgMatchPlayer, p)
			if err != nil {
				e.Error(500, err, fmt.Sprintf("创建比赛球员数据  失败，\r\n失败信息 %s", err.Error()))
				return
			}
		}

	}
	reqRemovePlayers := new(dto.OrgMatchTeamPlayerDeleteReq)
	reqRemovePlayers.MatchId = req.MatchId
	reqRemovePlayers.Rounds = req.Rounds
	reqRemovePlayers.TeamId = teamId

	delPlayerIds := ""
	for _, v := range playersIds {
		delPlayerIds += "'" + v + "',"
	}
	delPlayerIds = strings.Trim(delPlayerIds, ",")
	reqRemovePlayers.Ids = delPlayerIds
	err = s.Remove(reqRemovePlayers, p)
	//if err != nil {
	//	e.Error(500, err, fmt.Sprintf("删除比赛球员数据失败，\r\n失败信息 %s", err.Error()))
	//	return
	//}

	e.OK(1, "修改成功")
}

// Get <球队>获取比赛附加数据（比赛详情，联赛，赛区，赛季，球队）
// @Summary <球队>获取比赛附加数据（比赛详情，联赛，赛区，赛季，球队）
// @Description <球队>获取比赛附加数据（比赛详情，联赛，赛区，赛季，球队）
// @Tags <球队>比赛管理
// @Param id path string false "id"
// @Success 200 {string} string  {data=models.OrgMatchGetInfoReq} "{"code": 200, "data": [...]}"
// @Router /api/v1/org-team-match/info [get]
// @Security Bearer
func (e OrgTeamMatch) GetInfo(c *gin.Context) {
	req := dto.OrgMatchGetInfoReq{}
	s := service.OrgMatch{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(500, err, err.Error())
		return
	}
	var match models.OrgMatch

	p := actions.GetPermissionFromContext(c)
	err = s.Get(strconv.Itoa(req.Id), p, &match)
	if err != nil {
		//e.Error(500, err, fmt.Sprintf("获取比赛失败，\r\n失败信息 %s", err.Error()))
		//return
	}

	//联赛级别列表
	sOrgLeague := service.OrgLeague{}
	listOrgLeague := make([]models.OrgLeague, 0)
	var countOrgLeague int64 = 0

	err = e.MakeContext(c).MakeOrm().MakeService(&sOrgLeague.Service).Errors

	reqOrgLeague := new(dto.OrgLeagueGetPageReq)
	reqOrgLeague.PageIndex = 1
	reqOrgLeague.PageSize = 999

	err = sOrgLeague.GetPage(reqOrgLeague, p, &listOrgLeague, &countOrgLeague)

	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取联赛 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	//赛季列表
	sOrgSeason := service.OrgSeason{}
	listOrgSeason := make([]dto.OrgSeasonGetPageReply, 0)
	var countOrgSeason int64 = 0

	err = e.MakeContext(c).MakeOrm().MakeService(&sOrgSeason.Service).Errors

	reqOrgSeason := new(dto.OrgSeasonGetPageReq)
	reqOrgSeason.PageIndex = 1
	reqOrgSeason.PageSize = 999

	err = sOrgSeason.GetPage(reqOrgSeason, p, &listOrgSeason, &countOrgSeason)

	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取联赛 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	//赛区列表
	sOrgDivision := service.OrgDivision{}
	listOrgDivision := make([]models.OrgDivision, 0)
	var countOrgDivision int64 = 0

	err = e.MakeContext(c).MakeOrm().MakeService(&sOrgDivision.Service).Errors

	reqOrgDivision := new(dto.OrgDivisionGetPageReq)
	reqOrgDivision.PageIndex = 1
	reqOrgDivision.PageSize = 999

	err = sOrgDivision.GetPage(reqOrgDivision, p, &listOrgDivision, &countOrgDivision)

	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取联赛 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	//球队列表
	sOrgTeam := service.OrgTeam{}
	listOrgTeam := make([]dto.OrgTeamGetPageReply, 0)
	var countOrgTeam int64 = 0

	err = e.MakeContext(c).MakeOrm().MakeService(&sOrgTeam.Service).Errors

	reqOrgTeam := new(dto.OrgTeamGetPageReq)
	reqOrgTeam.PageIndex = 1
	reqOrgTeam.PageSize = 999

	err = sOrgTeam.GetPage(reqOrgTeam, p, &listOrgTeam, &countOrgTeam)

	if err != nil {
		e.Error(500, err, fmt.Sprintf("获取联赛 失败，\r\n失败信息 %s", err.Error()))
		return
	}

	reply := dto.OrgMatchGetInfoReply{
		OrgMatch:        match,
		OrgLeagueList:   listOrgLeague,
		OrgSeasonList:   listOrgSeason,
		OrgDivisionList: listOrgDivision,
		OrgTeamList:     listOrgTeam,
	}

	e.OK(reply, "查询成功")
}
