package gm_services

import (
	"encoding/json"
	"errors"
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/admin/gm_rpc/rpc_share"
	sqlModel "gadmin/internal/gorm/model"
	"gadmin/package/gmdata"
	"gadmin/utility"
	"gadmin/utility/character"
	"gadmin/utility/player"
	"gadmin/utility/token"
	"github.com/gin-gonic/gin"
	"leafstalk/covenant/msg"
	"strings"
	"time"
)

var (
	errNoUser = errors.New("playerId不能为空")
)

// 给用户加装备
func AddEquipment(ctx *gin.Context, params forms.AddMaterialReq) (err error) {
	if params.UserId == 0 {
		return errNoUser
	}

	playerAttr, err := player.GetAttrByUserId(params.UserId)
	if err != nil {
		return
	}
	DB, err := player.GetDBByPlayerAttr(playerAttr)
	if err != nil {
		return
	}
	//获取userAccount
	var userAccountModel sqlModel.UserAccount
	err = config.LDB.WithContext(ctx).Scopes(sqlModel.UserAccountTable(&userAccountModel, playerAttr.AccID)).Where("accId = ?", playerAttr.AccID).First(&userAccountModel).Error
	if err != nil {
		return
	}
	openIdArr := strings.Split(userAccountModel.Openid, "@")
	msgs := msg.GmAddMaterial{
		MsgId:      character.GenerateMsgId(),
		PlayerID:   params.UserId,
		Equipments: NewEquipments(params),
		OperatorId: token.GetUID(ctx),
		ClientPlat: openIdArr[1],
	}

	for _, EID := range msgs.Equipments {
		if EID != gmdata.GetEquipmentStartID(EID) {
			return errors.New("目前只能添加1级装备")
		}
	}
	//err = gate.SendToWorld(0, &msgs)
	//if err == nil {
	//
	//}

	if params.SuitName != "" {
		rpc_share.MsgMap[msgs.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]添加装备套装[%s],数量共计[%d]件", utility.FormatSecond(time.Now()), params.UserId, params.SuitName, len(params.Equipments))
	} else {
		rpc_share.MsgMap[msgs.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]添加装备[%d],数量[%d]", utility.FormatSecond(time.Now()), params.UserId, params.Id, params.Count)
	}

	var resp *msg.ResponseGmAddMaterial
	res, err := config.GmNats.GmRequest(DB, "GmAddMaterial", msgs)
	if err != nil {
		return
	}

	if err = json.Unmarshal(res, &resp); err != nil {
		return
	}

	rpc_share.LogChan <- rpc_share.LogMsg{
		MsgID: msgs.MsgId,
		Data:  resp,
	}

	return
}

// 给用户加材料
func AddMaterial(ctx *gin.Context, params forms.AddMaterialReq) (err error) {
	if params.UserId == 0 {
		return errNoUser
	}

	playerAttr, err := player.GetAttrByUserId(params.UserId)
	if err != nil {
		return
	}
	DB, err := player.GetDBByPlayerAttr(playerAttr)
	if err != nil {
		return
	}

	//获取userAccount
	var userAccountModel sqlModel.UserAccount

	err = config.LDB.WithContext(ctx).Scopes(sqlModel.UserAccountTable(&userAccountModel, playerAttr.AccID)).Where("accId = ?", playerAttr.AccID).First(&userAccountModel).Error
	if err != nil {
		return
	}
	openIdArr := strings.Split(userAccountModel.Openid, "@")
	msgs := msg.GmAddMaterial{
		MsgId:      character.GenerateMsgId(),
		PlayerID:   params.UserId,
		Materials:  map[int64]int64{params.Id: params.Count},
		OperatorId: token.GetUID(ctx),
		ClientPlat: openIdArr[1],
	}
	//err = gate.SendToWorld(0, &msgs)
	//if err == nil {
	//}
	rpc_share.MsgMap[msgs.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]添加材料[%d],数量[%d]", utility.FormatSecond(time.Now()), params.UserId, params.Id, params.Count)

	var resp *msg.ResponseGmAddMaterial
	res, err := config.GmNats.GmRequest(DB, "GmAddMaterial", msgs)
	if err != nil {
		return
	}

	if err = json.Unmarshal(res, &resp); err != nil {
		return
	}

	rpc_share.LogChan <- rpc_share.LogMsg{
		MsgID: msgs.MsgId,
		Data:  resp,
	}
	return
}

// 给用户加符文
func AddRune(ctx *gin.Context, params forms.AddMaterialReq) (err error) {
	if params.UserId == 0 {
		return errNoUser
	}

	playerAttr, err := player.GetAttrByUserId(params.UserId)
	if err != nil {
		return
	}
	DB, err := player.GetDBByPlayerAttr(playerAttr)
	if err != nil {
		return
	}

	//获取userAccount
	var userAccountModel sqlModel.UserAccount

	err = config.LDB.WithContext(ctx).Scopes(sqlModel.UserAccountTable(&userAccountModel, playerAttr.AccID)).Where("accId = ?", playerAttr.AccID).First(&userAccountModel).Error
	if err != nil {
		return
	}
	openIdArr := strings.Split(userAccountModel.Openid, "@")
	msgs := msg.GmAddMaterial{
		MsgId:      character.GenerateMsgId(),
		PlayerID:   params.UserId,
		Runes:      map[int64]int64{params.Id: params.Count},
		OperatorId: token.GetUID(ctx),
		ClientPlat: openIdArr[1],
	}
	rpc_share.MsgMap[msgs.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]添加符文[%d],数量[%d]", utility.FormatSecond(time.Now()), params.UserId, params.Id, params.Count)

	var resp *msg.ResponseGmAddMaterial
	res, err := config.GmNats.GmRequest(DB, "GmAddMaterial", msgs)
	if err != nil {
		return
	}

	if err = json.Unmarshal(res, &resp); err != nil {
		return
	}

	rpc_share.LogChan <- rpc_share.LogMsg{
		MsgID: msgs.MsgId,
		Data:  resp,
	}
	return
}

// 给用户加铭文
func AddLegend(ctx *gin.Context, params forms.AddMaterialReq) (err error) {
	if params.UserId == 0 {
		return errNoUser
	}

	playerAttr, err := player.GetAttrByUserId(params.UserId)
	if err != nil {
		return
	}
	DB, err := player.GetDBByPlayerAttr(playerAttr)
	if err != nil {
		return
	}

	//获取userAccount
	var userAccountModel sqlModel.UserAccount

	err = config.LDB.WithContext(ctx).Scopes(sqlModel.UserAccountTable(&userAccountModel, playerAttr.AccID)).Where("accId = ?", playerAttr.AccID).First(&userAccountModel).Error
	if err != nil {
		return
	}
	openIdArr := strings.Split(userAccountModel.Openid, "@")
	msgs := msg.GmAddMaterial{
		MsgId:      character.GenerateMsgId(),
		PlayerID:   params.UserId,
		Legends:    map[int64]int64{params.Id: params.Count},
		OperatorId: token.GetUID(ctx),
		ClientPlat: openIdArr[1],
	}
	rpc_share.MsgMap[msgs.MsgId] = fmt.Sprintf("%s,GM为玩家[%d]添加符文[%d],数量[%d]", utility.FormatSecond(time.Now()), params.UserId, params.Id, params.Count)

	var resp *msg.ResponseGmAddMaterial
	res, err := config.GmNats.GmRequest(DB, "GmAddMaterial", msgs)
	if err != nil {
		return
	}

	if err = json.Unmarshal(res, &resp); err != nil {
		return
	}

	rpc_share.LogChan <- rpc_share.LogMsg{
		MsgID: msgs.MsgId,
		Data:  resp,
	}
	return
}

/*
	func NewMaterials(params forms.AddMaterialReq) []*model.DropMaterial {
		return []*model.DropMaterial{
			{
				ID:    params.Id,
				Count: int(params.Count),
			},
		}
	}
*/
func NewEquipments(params forms.AddMaterialReq) []int64 {
	var resp []int64
	if len(params.Equipments) > 0 {
		return params.Equipments
	}

	for i := 0; i < int(params.Count); i++ {
		resp = append(resp, params.Id)
	}
	return resp
}

func AddGift(ctx *gin.Context, params forms.AddGiftReq) (err error) {
	if params.PlayerId == 0 {
		return errNoUser
	}

	playerAttr, err := player.GetAttrByUserId(params.PlayerId)
	if err != nil {
		return
	}

	DB, err := player.GetDBByPlayerAttr(playerAttr)
	if err != nil {
		return
	}

	msgs := forms.GmSendGift{
		MsgId:    character.GenerateMsgId(),
		PlayerID: params.PlayerId,
		Gift:     params.GiftId,
	}

	var resp forms.ResponseGmSendGift
	res, err := config.GmNats.GmRequest(DB, "GmSendGift", msgs)
	if err != nil {
		return
	}

	if err = json.Unmarshal(res, &resp); err != nil {
		return
	}

	rpc_share.LogChan <- rpc_share.LogMsg{
		MsgID: msgs.MsgId,
		Data:  resp,
	}

	return
}
