package admin_agent

import (
	"context"

	"qnc-server/app/main/api/internal/svc"
	"qnc-server/app/main/api/internal/types"
	"qnc-server/common/xerr"
	"qnc-server/pkg/lzkit/crypto"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminGetAgentListLogic) AdminGetAgentList(req *types.AdminGetAgentListReq) (resp *types.AdminGetAgentListResp, err error) {
	builder := l.svcCtx.AgentModel.SelectBuilder()

	// 如果传入TeamLeaderId，则查找该团队首领下的所有代理
	if req.TeamLeaderId != nil {
		builder = builder.Where(squirrel.Eq{"team_leader_id": *req.TeamLeaderId})
	}
	if req.Level != nil {
		builder = builder.Where(squirrel.Eq{"level": *req.Level})
	}
	if req.Mobile != nil && *req.Mobile != "" {
		// 加密手机号进行查询
		encryptedMobile, err := crypto.EncryptMobile(*req.Mobile, l.svcCtx.Config.Encrypt.SecretKey)
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "加密手机号失败: %v", err)
		}
		builder = builder.Where(squirrel.Eq{"mobile": encryptedMobile})
	}
	if req.Region != nil && *req.Region != "" {
		// 注意：region字段现在是可选的，查询时需要处理NULL值
		// 如果region字段是NULL，使用IS NULL查询；否则使用等值查询
		// 这里简化处理，直接使用等值查询（如果数据库中有NULL值，需要特殊处理）
		builder = builder.Where(squirrel.Eq{"region": *req.Region})
	}

	agents, total, err := l.svcCtx.AgentModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "id DESC")
	if err != nil {
		return nil, err
	}

	items := make([]types.AgentListItem, 0, len(agents))

	for _, agent := range agents {
		// 获取等级名称
		levelName := ""
		switch agent.Level {
		case 1:
			levelName = "普通"
		case 2:
			levelName = "黄金"
		case 3:
			levelName = "钻石"
		}

		agent.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)
		}

		// 查询钱包信息
		wallet, _ := l.svcCtx.AgentWalletModel.FindOneByAgentId(l.ctx, agent.Id)

		// 查询实名认证信息
		realNameInfo, _ := l.svcCtx.AgentRealNameModel.FindOneByAgentId(l.ctx, agent.Id)
		isRealName := false
		if realNameInfo != nil && realNameInfo.VerifyTime.Valid {
			isRealName = true // verify_time不为空表示已通过三要素核验
		}

		wechatId := ""
		if agent.WechatId.Valid {
			wechatId = agent.WechatId.String
		}
		teamLeaderId := ""
		if agent.TeamLeaderId.Valid {
			teamLeaderId = agent.TeamLeaderId.String
		}

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

		item := types.AgentListItem{
			Id:              agent.Id,
			UserId:          agent.UserId,
			Level:           agent.Level,
			LevelName:       levelName,
			Region:          region,
			Mobile:          agent.Mobile,
			WechatId:        wechatId,
			TeamLeaderId:    teamLeaderId,
			AgentCode:       agent.AgentCode,
			Balance:         0,
			TotalEarnings:   0,
			FrozenBalance:   0,
			WithdrawnAmount: 0,
			IsRealName:      isRealName,
			CreateTime:      agent.CreateTime.Format("2006-01-02 15:04:05"),
		}

		if wallet != nil {
			item.Balance = wallet.Balance
			item.TotalEarnings = wallet.TotalEarnings
			item.FrozenBalance = wallet.FrozenBalance
			item.WithdrawnAmount = wallet.WithdrawnAmount
		}

		items = append(items, item)
	}

	resp = &types.AdminGetAgentListResp{
		Total: total,
		Items: items,
	}
	return
}
