package agent

import (
	"context"
	"qnc-server/common/ctxdata"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

	"github.com/pkg/errors"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/app/main/model"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetAgentInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAgentInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAgentInfoLogic {
	return &GetAgentInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetAgentInfoLogic) GetAgentInfo() (resp *types.AgentInfoResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户信息失败, %v", err)
	}

	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			// 不是代理，返回空信息
			return &types.AgentInfoResp{
				AgentId:      "",
				Level:        0,
				LevelName:    "",
				Region:       "",
				Mobile:       "",
				WechatId:     "",
				TeamLeaderId: "",
				IsRealName:   false,
			}, nil
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理信息失败, %v", err)
	}

	// 解密手机号
	mobile, err := crypto.DecryptMobile(agent.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "解密手机号失败: %v", err)
	}

	// 查询实名认证状态
	isRealName := false
	agentRealName, err := l.svcCtx.AgentRealNameModel.FindOneByAgentId(l.ctx, agent.Id)
	if err != nil && !errors.Is(err, model.ErrNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询实名认证失败, %v", err)
	}
	if agentRealName != nil && agentRealName.VerifyTime.Valid { // verify_time不为空表示已通过三要素核验
		isRealName = true
	}

	// 获取微信号
	wechatId := ""
	if agent.WechatId.Valid {
		wechatId = agent.WechatId.String
	}

	// 获取团队首领ID
	teamLeaderId := ""
	if agent.TeamLeaderId.Valid {
		teamLeaderId = agent.TeamLeaderId.String
	}

	// 获取区域
	region := ""
	if agent.Region.Valid {
		region = agent.Region.String
	}

	return &types.AgentInfoResp{
		AgentId:      agent.Id,
		Level:        agent.Level,
		LevelName:    l.getLevelName(agent.Level),
		Region:       region,
		Mobile:       mobile,
		WechatId:     wechatId,
		TeamLeaderId: teamLeaderId,
		IsRealName:   isRealName,
		AgentCode:    agent.AgentCode,
	}, nil
}

// getLevelName 获取等级名称
func (l *GetAgentInfoLogic) getLevelName(level int64) string {
	switch level {
	case 1:
		return "普通"
	case 2:
		return "黄金"
	case 3:
		return "钻石"
	default:
		return ""
	}
}
