package admin_agent

import (
	"context"
	"bdqr-server/common/globalkey"
	"bdqr-server/common/xerr"
	"bdqr-server/pkg/lzkit/crypto"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"

	"bdqr-server/app/main/api/internal/svc"
	"bdqr-server/app/main/api/internal/types"

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

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

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

func (l *AdminGetInviteCodeListLogic) AdminGetInviteCodeList(req *types.AdminGetInviteCodeListReq) (resp *types.AdminGetInviteCodeListResp, err error) {
	// 1. 构建查询条件
	builder := l.svcCtx.AgentInviteCodeModel.SelectBuilder().
		Where("del_state = ?", globalkey.DelStateNo)

	if req.Code != nil && *req.Code != "" {
		builder = builder.Where("code = ?", *req.Code)
	}
	if req.AgentId != nil && *req.AgentId != "" {
		if *req.AgentId == "0" {
			// agent_id = 0 表示查询平台发放的邀请码（agent_id为NULL）
			builder = builder.Where("agent_id IS NULL")
		} else {
			builder = builder.Where("agent_id = ?", *req.AgentId)
		}
	}
	if req.TargetLevel != nil {
		builder = builder.Where("target_level = ?", *req.TargetLevel)
	}
	if req.Status != nil {
		builder = builder.Where("status = ?", *req.Status)
	}

	// 2. 分页查询
	list, total, err := l.svcCtx.AgentInviteCodeModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询邀请码列表失败, %v", err)
	}

	// 3. 批量查询代理信息（用于显示代理手机号）
	agentIds := make(map[string]struct{})
	for _, v := range list {
		if v.AgentId.Valid && v.AgentId.String != "" {
			agentIds[v.AgentId.String] = struct{}{}
		}
	}

	agentMobileMap := make(map[string]string)
	if len(agentIds) > 0 {
		agentIdList := make([]string, 0, len(agentIds))
		for id := range agentIds {
			agentIdList = append(agentIdList, id)
		}
		agents, _ := l.svcCtx.AgentModel.FindAll(l.ctx, l.svcCtx.AgentModel.SelectBuilder().Where(squirrel.Eq{"id": agentIdList}), "")
		secretKey := l.svcCtx.Config.Encrypt.SecretKey
		for _, agent := range agents {
			mobile, decErr := crypto.DecryptMobile(agent.Mobile, secretKey)
			if decErr == nil {
				agentMobileMap[agent.Id] = mobile
			} else {
				l.Logger.Errorf("解密代理手机号失败: %v", decErr)
			}
		}
	}

	// 4. 格式化返回数据
	items := make([]types.InviteCodeListItem, 0, len(list))
	for _, v := range list {
		item := types.InviteCodeListItem{
			Id:          v.Id,
			Code:        v.Code,
			AgentId:     "",
			AgentMobile: "",
			TargetLevel: v.TargetLevel,
			Status:      v.Status,
			CreateTime:  v.CreateTime.Format("2006-01-02 15:04:05"),
		}

		if v.AgentId.Valid {
			item.AgentId = v.AgentId.String
			item.AgentMobile = agentMobileMap[v.AgentId.String]
		}

		if v.UsedUserId.Valid {
			item.UsedUserId = v.UsedUserId.String
		}
		if v.UsedAgentId.Valid {
			item.UsedAgentId = v.UsedAgentId.String
		}
		if v.UsedTime.Valid {
			item.UsedTime = v.UsedTime.Time.Format("2006-01-02 15:04:05")
		}
		if v.ExpireTime.Valid {
			item.ExpireTime = v.ExpireTime.Time.Format("2006-01-02 15:04:05")
		}
		if v.Remark.Valid {
			item.Remark = v.Remark.String
		}

		items = append(items, item)
	}

	return &types.AdminGetInviteCodeListResp{
		Total: total,
		Items: items,
	}, nil
}
