package rpc

import (
	. "bp.jydev.jianyu360.cn/BaseService/gateway/common/gatecode"
	"bp.jydev.jianyu360.cn/BaseService/gateway/core/router"
	"bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/pb"
	"bp.jydev.jianyu360.cn/BaseService/userCenter/rpc/usercenter"
	"fmt"
	"github.com/gogf/gf/v2/net/gtrace"
	"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 UserCenterRpc usercenter.UserCenter

func initUserCenterRpc() {
	UserCenterRpc = usercenter.NewUserCenter(zrpc.MustNewClient(zrpc.RpcClientConf{
		Etcd: discov.EtcdConf{
			Key:   gcfg.Instance().MustGet(gctx.New(), "etcd.baseserver.userCenter.key", nil).String(),
			Hosts: gcfg.Instance().MustGet(gctx.New(), "etcd.baseserver.userCenter.address", nil).Strings(),
		},
	}))
}

// CheckAccountStatus 校验企业认证状态及账户状态
func CheckAccountStatus(ctx gctx.Ctx, entId int64, userId string, rule *router.Router) error {
	_, span := gtrace.NewSpan(ctx, "CheckAccountStatus")
	defer span.End()

	if rule.AuthCheck.GetCode() == 0 && rule.AccountCheck.GetCode() == 0 {
		return nil
	}

	//查询个人状态
	if rule.AuthCheck.CheckUserAuth() || rule.AccountCheck.CheckUserAccount() {
		if userErr := checkPersonalStatus(userId, rule.AuthCheck.CheckUserAuth(), rule.AccountCheck.CheckUserAccount()); userErr != nil {
			return userErr
		}
	}

	//查询企业状态
	if rule.AuthCheck.CheckEntAuth() || rule.AccountCheck.CheckEntAccount() {
		if entErr := checkEntStatus(entId, rule.AuthCheck.CheckEntAuth(), rule.AccountCheck.CheckEntAccount()); entErr != nil {
			return entErr
		}
	}
	return nil
}

// checkEntStatus 校验企业状态
func checkEntStatus(entId int64, authCheck, accountCheck bool) error {
	res, err := UserCenterRpc.CheckEnt(gctx.New(), &pb.CheckEntReq{
		EntId: entId,
	})
	if err != nil {
		return NewErrorWithCode(GATEWAY_RPC_USERCENTER_ERR, err.Error())
	}

	//校验是否冻结
	if accountCheck && res.Data.FrozenStatus == 1 {
		return NewErrorWithCode(GLOBAL_ERR_ENTACCOUNT_STATUS, fmt.Sprintf("企业账户 %d 已被冻结", entId))
	}

	//校验是否认证
	if authCheck {
		//-1 未通过，0 未认证，1 已认证. -2 已到期 3 待审核
		switch res.Data.AuthStatus {
		case 0:
			return NewErrorWithCode(GLOBAL_ERR_ENTACCOUNT_AUTH_NOT, fmt.Sprintf("企业账户 %d 未认证", entId))
		case 3:
			return NewErrorWithCode(GLOBAL_ERR_ENTACCOUNT_AUTH_AWAIT, fmt.Sprintf("企业账户 %d 待审核", entId))
		case -1:
			return NewErrorWithCode(GLOBAL_ERR_ENTACCOUNT_AUTH_NOTPASS, fmt.Sprintf("企业账户 %d 未通过", entId))
		case -2:
			return NewErrorWithCode(GLOBAL_ERR_ENTACCOUNT_AUTH_EXPIRED, fmt.Sprintf("企业账户 %d 已到期", entId))
		}
	}
	return nil
}

// checkPersonalStatus 校验个人状态账户状态
func checkPersonalStatus(userId string, authCheck, accountCheck bool) error {
	return NewErrorWithCode(GLOBAL_ERR_UNFINISH, "checkPersonalStatus")
}
