package rpc

import (
	"fmt"
	"github.com/gogf/gf/v2/net/gtrace"

	. "bp.jydev.jianyu360.cn/BaseService/gateway/common/gatecode"
	"bp.jydev.jianyu360.cn/BaseService/powerCheckCenter/rpc/pb"
	"bp.jydev.jianyu360.cn/BaseService/powerCheckCenter/rpc/powercheck"
	"github.com/gogf/gf/v2/os/gcfg"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/zeromicro/go-zero/core/discov"
	"github.com/zeromicro/go-zero/zrpc"
)

var PowerCheckCenterRpc powercheck.PowerCheck

func initPowerCheckCenterRpcRpc() {
	PowerCheckCenterRpc = powercheck.NewPowerCheck(zrpc.MustNewClient(zrpc.RpcClientConf{
		Etcd: discov.EtcdConf{
			Key:   gcfg.Instance().MustGet(gctx.New(), "etcd.baseserver.powerCheckCenter.key", nil).String(),
			Hosts: gcfg.Instance().MustGet(gctx.New(), "etcd.baseserver.powerCheckCenter.address", nil).Strings(),
		},
	}))
}

func CheckUserPower(ctx gctx.Ctx, power_type int, appid, userId string, baseUserId, accountId, entId, positionType, positionId int64) error {
	ctx, span := gtrace.NewSpan(ctx, "CheckUserPower")
	defer span.End()
	res, err := PowerCheckCenterRpc.Check(gctx.New(), &pb.CheckReq{
		Appid:        appid,
		Userid:       userId,
		BaseUserId:   baseUserId,
		AccountId:    accountId,
		EntId:        entId,
		PositionType: positionType,
		PositionId:   positionId,
	})
	if err != nil {
		return err
	}
	/*
		权益判断方式、0走资源中台
		1前置代理判断，是否是付费用户
		2前置代理判断，是否是超级订阅
		3前置代理判断，是否是大会员
		4前置代理判断，是否是商机管理
	*/
	switch power_type {
	case 1:
		if res.Vip.Status <= 0 && res.Member.Status <= 0 && res.Entniche.Status <= 0 {
			return NewErrorWithCode(GLOBAL_ERR_NOPOWER, fmt.Sprintf("该用户非付费用户"))
		}
	case 2:
		if res.Vip.Status <= 0 {
			return NewErrorWithCode(GLOBAL_ERR_NOPOWER, fmt.Sprintf("该用户非超级订阅用户"))
		}
	case 3:
		if res.Member.Status <= 0 {
			return NewErrorWithCode(GLOBAL_ERR_NOPOWER, fmt.Sprintf("该用户非大会员用户"))
		}
	case 4:
		if res.Entniche.Status <= 0 {
			return NewErrorWithCode(GLOBAL_ERR_NOPOWER, fmt.Sprintf("该用户非商机管理用户"))
		}
	case 22: //临时加大会员专家版、商机版判断
		if !(res.Member.Status == 1 || res.Member.Status == 2 || res.Member.Status == 6 || res.Member.Status == 7) {
			return NewErrorWithCode(GLOBAL_ERR_NOPOWER, fmt.Sprintf("该用户非大会员专家版、商机版用户"))
		}
	}
	return nil
}
