package service

import (
	"encoding/json"
	"fmt"
	"gadmin/config"
	"gadmin/internal/admin/forms"
	"gadmin/internal/admin/gm_rpc/rpc_share"
	"gadmin/utility/character"
	"gadmin/utility/serializer"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	clientv3 "go.etcd.io/etcd/client/v3"
	msg2 "leafstalk/covenant/msg"
)

var (
	PaySwitchService = &sPaySwitch{
		key: "covenant/servers/loginparams/PayConfig",
	}
)

type sPaySwitch struct {
	key string
}

func (s *sPaySwitch) GetPaySwitch(ctx *gin.Context) serializer.Response {
	var payConfig forms.PayConfig

	kv := clientv3.NewKV(config.Etcd)
	getResp, err := kv.Get(ctx, s.key)
	if err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	if len(getResp.Kvs) == 0 {
		return serializer.Suc(payConfig)
	}

	if err = json.Unmarshal(getResp.Kvs[0].Value, &payConfig); err != nil {
		return serializer.DBErr(err.Error(), err)
	}

	return serializer.Suc(payConfig)
}

func (s *sPaySwitch) EditPaySwitch(ctx *gin.Context, req forms.EditPaySwitchReq) serializer.Response {
	successIds := make([]int, 0)
	failIds := make([]int, 0)
	for _, serverId := range ServerOption.GetServerIds() {
		msg := msg2.GmIosPay{
			MsgId:           character.GenerateMsgId(),
			IosPayOpenLevel: req.IosOpenLevel,
			OperatorId:      ctx.GetInt64("admin_id"),
		}

		var resp *msg2.ResponseGmIosPay
		res, err := config.GmNats.GmRequest(serverId, "UpdateGmIosPay", msg)
		if err != nil {
			logrus.Warnf("EditPaySwitch serverId:%v, msg:%v GmRequest err:%+v", serverId, msg, err)
			failIds = append(failIds, serverId)
			continue
		}

		if err = json.Unmarshal(res, &resp); err != nil {
			logrus.Warnf("EditPaySwitch serverId:%v, msg:%v Unmarshal err:%+v", serverId, msg, err)
			failIds = append(failIds, serverId)
			continue
		}
		successIds = append(successIds, serverId)
	}
	msgId := character.GenerateMsgId()
	if len(failIds) == 0 {
		rpc_share.MsgMap[msgId] = fmt.Sprintf("GM成功修改苹果支付开启等级为: %v", req.IosOpenLevel)
	} else {
		rpc_share.MsgMap[msgId] = fmt.Sprintf("GM修改服务器%v的苹果支付开启等级为: %v失败", failIds, req.IosOpenLevel)
	}

	rpc_share.LogChan <- rpc_share.LogMsg{
		MsgID: msgId,
	}

	return serializer.Suc(req)

	//payConfig := forms.PayConfig{
	//	IosOpenLevel: req.IosOpenLevel,
	//}
	//
	//marshal, err := json.Marshal(payConfig)
	//if err != nil {
	//	return serializer.DBErr(err.Error(), err)
	//}
	//
	//logrus.Warnf("sPaySwitch PayConfig:%v", string(marshal))
	//
	//kv := clientv3.NewKV(config.Etcd)
	//putResp, err := kv.Put(ctx, s.key, string(marshal), clientv3.WithPrevKV())
	//if err != nil {
	//	return serializer.DBErr(err.Error(), err)
	//}
	//
	//logrus.Warnf("Revision:%v", putResp.Header.Revision)
	//if putResp.PrevKv != nil {
	//	logrus.Warnf("key:%v", string(putResp.PrevKv.Key))
	//	logrus.Warnf("Value:%v", string(putResp.PrevKv.Value))
	//	logrus.Warnf("Version:%v", strconv.FormatInt(putResp.PrevKv.Version, 10))
	//}
	//
	//return serializer.Suc(nil)
}
