package admin_agent

import (
	"context"

	"jnc-server/app/main/api/internal/svc"
	"jnc-server/app/main/api/internal/types"
	"jnc-server/common/xerr"
	"jnc-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, Level 筛选条件
	// 只保留 Mobile 和 Region 筛选
	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 {
		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)

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

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

		// 系统简化：移除 Level, LevelName, TeamLeaderId, WithdrawnAmount, IsRealName 字段
		item := types.AgentListItem{
			Id:           agent.Id,
			UserId:       agent.UserId,
			Region:       region,
			Mobile:       agent.Mobile,
			WechatId:     wechatId,
			AgentCode:    agent.AgentCode,
			Balance:      0,
			FrozenAmount: 0,
			TotalEarnings: 0,
			CreateTime:  agent.CreateTime.Format("2006-01-02 15:04:05"),
		}

		if wallet != nil {
			item.Balance = wallet.Balance
			item.FrozenAmount = wallet.FrozenAmount
			item.TotalEarnings = wallet.TotalEarnings
		}

		items = append(items, item)
	}

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