package apis

import (
	"fmt"
	"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/jwtauth/user"
	_ "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 OrgMatch struct {
	api.Api
}

// GetPage <赛事>获取比赛列表
// @Summary <赛事>获取比赛列表
// @Description <赛事>获取比赛列表
// @Tags <赛事>比赛
// @Param pageSize query int false "页条数"
// @Param pageIndex query int false "页码"
// @Success 200 {string} string  "{"code": 200, "data": [...]}"
// @Router /api/v1/org-match [get]
// @Security Bearer
func (e OrgMatch) GetPage(c *gin.Context) {
	req := dto.OrgMatchGetPageReq{}
	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
	}

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

	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-match/{id} [get]
// @Security Bearer
func (e OrgMatch) Get(c *gin.Context) {
	req := dto.OrgMatchGetReq{}
	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 object models.OrgMatch

	p := actions.GetPermissionFromContext(c)
	err = s.Get(&req, p, &object)
	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([]models.OrgSeason, 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([]models.OrgTeam, 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.OrgMatchGetReply{
		OrgMatch:        object,
		OrgLeagueList:   listOrgLeague,
		OrgSeasonList:   listOrgSeason,
		OrgDivisionList: listOrgDivision,
		OrgTeamList:     listOrgTeam,
	}

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

// Insert <赛事>创建比赛
// @Summary <赛事>创建比赛
// @Description <赛事>创建比赛
// @Tags <赛事>比赛
// @Accept application/json
// @Product application/json
// @Param data body dto.OrgMatchInsertReq true "data"
// @Success 200 {string} string  	"{"code": 200, "message": "添加成功"}"
// @Router /api/v1/org-match [post]
// @Security Bearer
func (e OrgMatch) Insert(c *gin.Context) {
	req := dto.OrgMatchInsertReq{}
	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
	}
	// 设置创建人
	req.SetCreateBy(user.GetUserId(c))

	err = s.Insert(&req)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("创建比赛  失败，\r\n失败信息 %s", err.Error()))
		return
	}

	e.OK(req.GetId(), "创建成功")
}

// 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-match/{id} [put]
// @Security Bearer
func (e OrgMatch) Update(c *gin.Context) {
	req := dto.OrgMatchUpdateReq{}
	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
	}
	req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("修改比赛 失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "修改成功")
}

// Delete <赛事>删除比赛
// @Summary <赛事>删除比赛
// @Description <赛事>删除比赛
// @Tags <赛事>比赛
// @Param ids body []int false "ids"
// @Success 200 {string} string  	"{"code": 200, "message": "删除成功"}"
// @Router /api/v1/org-match [delete]
// @Security Bearer
func (e OrgMatch) Delete(c *gin.Context) {
	s := service.OrgMatch{}
	req := dto.OrgMatchDeleteReq{}
	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
	}

	// req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Remove(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("删除比赛失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "删除成功")
}

// Get <赛事>获取比赛所有球员
// @Summary <赛事>获取比赛所有球员
// @Description <赛事>获取比赛所有球员
// @Tags <赛事>比赛
// @Param id path string false "id"
// @Success 200 {string} string  {data=models.OrgMatch} "{"code": 200, "data": [...]}"
// @Router /api/v1/org-match/get-player/{id} [get]
// @Security Bearer
func (e OrgMatch) GetPlayer(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([]models.OrgPlayer, 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(), "查询成功")
}

// Get <赛事>获取比赛已设置球员
// @Summary <赛事>获取比赛已设置球员
// @Description <赛事>获取比赛已设置球员
// @Tags <赛事>比赛
// @Param id path string false "id"
// @Success 200 {string} string  {data=models.OrgMatch} "{"code": 200, "data": [...]}"
// @Router /api/v1/org-match/get-player-is-set/{id} [get]
// @Security Bearer
func (e OrgMatch) GetPlayerIsSet(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.UpdateOrgMatchTeamPlayerReq true "body"
// @Success 200 {string} string  	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/org-match/update-player [put]
// @Security Bearer
func (e OrgMatch) UpdatePlayer(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
	}
	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)

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

		//if orgPlayer.Id == 0 {
		//	e.Error(500, err, "球员不存在")
		//	return
		//}

		if err != nil {
			orgMatchPlayer := dto.OrgMatchTeamPlayerInsertReq{
				MatchId:      req.MatchId,
				ClubId:       orgPlayer.ClubId,
				TeamId:       orgPlayer.TeamId,
				PlayerId:     v,
				PlayerName:   orgPlayer.PlayerName,
				PlayerNumber: orgPlayer.PlayerNumber,
				Position:     orgPlayer.Position,
			}
			err = s.Insert(&orgMatchPlayer)
			if err != nil {
				e.Error(500, err, fmt.Sprintf("创建比赛球员数据  失败，\r\n失败信息 %s", err.Error()))
				return
			}
		} else {
			orgMatchPlayer := dto.OrgMatchTeamPlayerUpdateReq{
				MatchId:      req.MatchId,
				ClubId:       orgPlayer.ClubId,
				TeamId:       orgPlayer.TeamId,
				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
			}
		}

	}

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

// Update <赛事>修改比赛球员数据
// @Summary <赛事>修改比赛球员数据
// @Description <赛事>修改比赛球员数据
// @Tags <赛事>比赛
// @Accept application/json
// @Product application/json
// @Param data body dto.OrgMatchTeamPlayerUpdateReq true "body"
// @Success 200 {string} string  	"{"code": 200, "message": "修改成功"}"
// @Router /api/v1/org-match/update-player-data/{id} [put]
// @Security Bearer
func (e OrgMatch) UpdatePlayerData(c *gin.Context) {
	req := dto.OrgMatchTeamPlayerUpdateReq{}
	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
	}
	req.SetUpdateBy(user.GetUserId(c))
	p := actions.GetPermissionFromContext(c)

	err = s.Update(&req, p)
	if err != nil {
		e.Error(500, err, fmt.Sprintf("修改比赛球员数据 失败，\r\n失败信息 %s", err.Error()))
		return
	}
	e.OK(req.GetId(), "修改成功")
}
