package admin_agent

import (
	"context"

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

	"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()
	if req.Mobile != nil && *req.Mobile != "" {
		builder = builder.Where("mobile = ?", *req.Mobile)
	}
	if req.Region != nil && *req.Region != "" {
		builder = builder.Where("region = ?", *req.Region)
	}

	// 新增：如果传入ParentAgentId，则查找其所有1级下级代理
	if req.ParentAgentId != nil {
		closureBuilder := l.svcCtx.AgentClosureModel.SelectBuilder().Where("ancestor_id = ? AND depth = 1", *req.ParentAgentId)
		closures, cerr := l.svcCtx.AgentClosureModel.FindAll(l.ctx, closureBuilder, "")
		if cerr != nil {
			return nil, cerr
		}
		if len(closures) == 0 {
			resp = &types.AdminGetAgentListResp{Total: 0, Items: []types.AgentListItem{}}
			return resp, nil
		}
		ids := make([]int64, 0, len(closures))
		for _, c := range closures {
			ids = append(ids, c.DescendantId)
		}
		builder = builder.Where("id IN (?)", ids)
	}

	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 {
		item := types.AgentListItem{
			Id:         agent.Id,
			UserId:     agent.UserId,
			LevelName:  agent.LevelName,
			Region:     agent.Region,
			CreateTime: agent.CreateTime.Format("2006-01-02 15:04:05"),
		}
		if req.ParentAgentId != nil {
			item.ParentAgentId = *req.ParentAgentId
		}
		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)
		}
		item.Mobile = agent.Mobile
		if agent.MembershipExpiryTime.Valid {
			item.MembershipExpiryTime = agent.MembershipExpiryTime.Time.Format("2006-01-02 15:04:05")
		}

		// 查询钱包信息
		wallet, _ := l.svcCtx.AgentWalletModel.FindOneByAgentId(l.ctx, agent.Id)
		if wallet != nil {
			item.Balance = wallet.Balance
			item.TotalEarnings = wallet.TotalEarnings
			item.FrozenBalance = wallet.FrozenBalance
			item.WithdrawnAmount = wallet.WithdrawnAmount
		}

		// 查询实名认证信息
		realNameInfo, _ := l.svcCtx.AgentRealNameModel.FindOneByAgentId(l.ctx, agent.Id)
		if realNameInfo != nil {
			item.IsRealNameVerified = realNameInfo.Status == model.AgentRealNameStatusApproved
			item.RealName = realNameInfo.Name
			item.IdCard = realNameInfo.IdCard
			item.RealNameStatus = realNameInfo.Status
		} else {
			item.IsRealNameVerified = false
			item.RealName = ""
			item.IdCard = ""
			item.RealNameStatus = ""
		}

		items = append(items, item)
	}

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