package service

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

var Retrofit = new(sRetrofit)

type sRetrofit struct{}

func (s *sRetrofit) AddPlayer(ctx *gin.Context, req forms.RetrofitGroupAddPlayerReq) serializer.Response {

	if req.UserId <= 0 {
		return serializer.Err(consts.CodeParamErr, "用户ID不能为空！", nil)
	}

	var (
		q                = query.Use(config.DB).RetrofitGroup
		r                = query.Use(config.DB).Retrofit
		materials        = make(map[int64]int64)
		equipments       []int64
		userAccountModel model.UserAccount
	)

	playerAttr, err := player.GetAttrByUserId(req.UserId)
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 GetDBByUserId", err)
	}

	DB, err := player.GetDBByPlayerAttr(playerAttr)
	if err != nil {
		return serializer.Response{}
	}
	//获取userAccount
	err = config.LDB.WithContext(ctx).Scopes(model.UserAccountTable(&userAccountModel, playerAttr.AccID)).Where("accId = ?", playerAttr.AccID).First(&userAccountModel).Error
	if err != nil {
		return serializer.Err(consts.CodeParamErr, err.Error(), err)
	}
	openIdArr := strings.Split(userAccountModel.Openid, "@")

	data, err := q.WithContext(ctx).Where(q.ID.Eq(req.ID), q.Status.Eq(consts.StatusNormal)).First()
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 First", err)
	}

	retrofits, err := r.WithContext(ctx).Where(r.GroupID.Eq(data.ID), r.Status.Eq(consts.StatusNormal)).Find()
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 First2", err)
	}

	if len(retrofits) == 0 {
		return serializer.Err(consts.CodeParamErr, "该模板下没有可用的配装！", err)
	}

	for _, retrofit := range retrofits {
		// 装备
		if retrofit.Type == consts.RetrofitTypeEquipment {
			for i := 0; i < int(retrofit.Nums); i++ {
				equipments = append(equipments, retrofit.Mid)
			}
			continue
		}

		// 材料
		if retrofit.Type == consts.RetrofitTypeMaterial || retrofit.Type == consts.RetrofitTypeDiamond || retrofit.Type == consts.RetrofitTypeCoin {
			materials[retrofit.Mid] = retrofit.Nums
		}
	}

	// 批量添加
	if len(materials) > 0 || len(equipments) > 0 {
		msg := msg2.GmAddMaterial{
			MsgId:      character.GenerateMsgId(),
			PlayerID:   req.UserId,
			Materials:  materials,
			Equipments: equipments,
			ClientPlat: openIdArr[1],
		}
		//if err = gate.SendToWorld(0, &materialsMsg); err != nil {
		//	return serializer.Err(consts.CodeParamErr, fmt.Sprintf("添加配装失败，请检查！model.id:%d", data.ID), err)
		//}
		rpc_share.MsgMap[msg.MsgId] = fmt.Sprintf("GM为玩家[%d]添加配装[%s]", req.UserId, data.Name)

		var resp *msg2.ResponseGmAddMaterial
		res, err := config.GmNats.GmRequest(DB, "GmAddMaterial", msg)
		if err != nil {
			return serializer.Err(consts.CodeParamErr, err.Error(), err)
		}

		if err = json.Unmarshal(res, &resp); err != nil {
			return serializer.Err(consts.CodeParamErr, err.Error(), err)
		}

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

	return serializer.Suc(nil)
}

func (s *sRetrofit) GroupOptions(ctx *gin.Context) serializer.Response {

	var (
		q     = query.Use(config.DB).RetrofitGroup
		m     = q.WithContext(ctx)
		lists []forms.OptionInt64
	)

	if err := m.Select(q.ID.As("value"), q.Name.As("label")).
		Where(q.Status.Eq(consts.StatusNormal)).
		Order(q.ID.Desc()).
		Limit(200).
		Scan(&lists); err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 lists", err)
	}

	return serializer.Suc(lists)
}

func (s *sRetrofit) GroupList(ctx *gin.Context, req forms.RetrofitGroupListReq) serializer.Response {

	var (
		q            = query.Use(config.DB).RetrofitGroup
		m            = q.WithContext(ctx)
		offset int64 = 0
		models forms.UserAccountListRes
		lists  []model.RetrofitGroup
	)

	m = m.Order(q.ID.Desc())

	req.Page, req.PerPage, offset = forms.CalculatePage(req.Page, req.PerPage)

	count, err := m.Count()
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 count", err)
	}

	if count > 0 {
		if err = m.Limit(int(req.PerPage)).Offset(int(offset)).Scan(&lists); err != nil {
			return serializer.Err(consts.CodeParamErr, "查询出错 lists", err)
		}
	}

	models.List = lists
	models.Page = req.Page
	models.PerPage = req.PerPage
	models.PageCount = (count + req.PerPage - 1) / req.PerPage

	return serializer.Suc(models)
}

func (s *sRetrofit) GroupEdit(ctx *gin.Context, req forms.RetrofitGroupEditReq) serializer.Response {

	var (
		q   = query.Use(config.DB).RetrofitGroup
		err error
	)

	// 编辑
	if req.ID > 0 {
		_, err = query.Use(config.DB).RetrofitGroup.WithContext(ctx).Where(q.ID.Eq(req.ID)).Updates(model.RetrofitGroup{
			Name:      req.Name,
			Remark:    req.Remark,
			Sort:      req.Sort,
			Status:    req.Status,
			UpdatedAt: time.Now(),
		})
		if err != nil {
			return serializer.DBErr(err.Error(), err)
		}

		return serializer.Suc(nil)
	}

	// 新增
	createData := model.RetrofitGroup{
		Name:      req.Name,
		Remark:    req.Remark,
		Sort:      req.Sort,
		Status:    req.Status,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	if err = query.Use(config.DB).RetrofitGroup.WithContext(ctx).Create(&createData); err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	if createData.ID < 1 {
		return serializer.ParamErr("创建失败，请稍后重试！", nil)
	}

	return serializer.Suc(nil)
}

func (s *sRetrofit) GroupDelete(ctx *gin.Context, req forms.RetrofitGroupDeleteReq) serializer.Response {

	var (
		q = query.Use(config.DB).RetrofitGroup
		//r   = query.Use(config.DB).Retrofit
		err error
	)

	// 编辑
	if req.ID <= 0 {
		return serializer.ParamErr("ID不能空，删除失败！", nil)
	}

	//count, err := query.Use(config.DB).Retrofit.WithContext(ctx).Where(r.GroupID.Eq(req.ID)).Count()
	//if err != nil {
	//	return serializer.DBErr(err.Error(), err)
	//}
	//
	//if count > 0 {
	//	return serializer.ParamErr("防止误操作，请先删除模板的所有配装！", nil)
	//}

	_, err = query.Use(config.DB).RetrofitGroup.WithContext(ctx).Where(q.ID.Eq(req.ID)).Delete()
	if err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	return serializer.Suc(nil)
}

func (s *sRetrofit) List(ctx *gin.Context, req forms.RetrofitListReq) serializer.Response {

	var (
		q            = query.Use(config.DB).Retrofit
		m            = q.WithContext(ctx)
		offset int64 = 0
		models forms.UserAccountListRes
		lists  []model.Retrofit
	)

	if req.GroupId > 0 {
		m = m.Where(q.GroupID.Eq(req.GroupId))
	}
	m = m.Order(q.ID.Desc())

	req.Page, req.PerPage, offset = forms.CalculatePage(req.Page, req.PerPage)

	count, err := m.Count()
	if err != nil {
		return serializer.Err(consts.CodeParamErr, "查询出错 count", err)
	}

	if count > 0 {
		if err = m.Limit(int(req.PerPage)).Offset(int(offset)).Scan(&lists); err != nil {
			return serializer.Err(consts.CodeParamErr, "查询出错 lists", err)
		}
	}

	models.List = lists
	models.Page = req.Page
	models.PerPage = req.PerPage
	models.PageCount = (count + req.PerPage - 1) / req.PerPage

	return serializer.Suc(models)
}

func (s *sRetrofit) Edit(ctx *gin.Context, req forms.RetrofitEditReq) serializer.Response {

	var (
		q   = query.Use(config.DB).Retrofit
		err error
	)

	if req.Type == consts.RetrofitTypeEquipment && req.Mid != gmdata.GetEquipmentStartID(req.Mid) {
		return serializer.ParamErr("目前只能添加1级装备", nil)
	}

	// 编辑
	if req.ID > 0 {
		_, err = query.Use(config.DB).Retrofit.WithContext(ctx).Where(q.ID.Eq(req.ID)).Updates(model.Retrofit{
			GroupID:   req.GroupID,
			Name:      req.Name,
			Type:      req.Type,
			Mid:       req.Mid,
			Nums:      req.Nums,
			Status:    req.Status,
			CreatedAt: time.Now(),
		})
		if err != nil {
			return serializer.DBErr(err.Error(), err)
		}

		return serializer.Suc(nil)
	}

	// 新增
	createData := model.Retrofit{
		GroupID:   req.GroupID,
		Name:      req.Name,
		Type:      req.Type,
		Mid:       req.Mid,
		Nums:      req.Nums,
		Status:    req.Status,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}

	if err = query.Use(config.DB).Retrofit.WithContext(ctx).Create(&createData); err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	if createData.ID < 1 {
		return serializer.ParamErr("创建失败，请稍后重试！", nil)
	}

	return serializer.Suc(nil)
}

func (s *sRetrofit) Delete(ctx *gin.Context, req forms.RetrofitDeleteReq) serializer.Response {

	var (
		q   = query.Use(config.DB).Retrofit
		err error
	)

	// 编辑
	if req.ID <= 0 {
		return serializer.ParamErr("ID不能空，删除失败！", nil)
	}

	_, err = query.Use(config.DB).Retrofit.WithContext(ctx).Where(q.ID.Eq(req.ID)).Delete()
	if err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	return serializer.Suc(nil)
}
