package agent

import (
	"context"
	"strings"
	"time"

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

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

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

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

func (l *GetAgentSubordinateListLogic) GetAgentSubordinateList(req *types.GetAgentSubordinateListReq) (resp *types.GetAgentSubordinateListResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理下级列表, 获取用户ID%v", err)
	}
	agentModel, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理信息%v", err)
	}
	agentID := agentModel.Id

	builder := l.svcCtx.AgentClosureModel.SelectBuilder().Where(squirrel.Eq{
		"ancestor_id": agentID,
	})
	agentClosureModelList, total, err := l.svcCtx.AgentClosureModel.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)
	}

	// 构建ID到CreateTime的映射
	createTimeMap := make(map[int64]time.Time)
	descendantIDs := make([]int64, 0)
	for _, v := range agentClosureModelList {
		descendantIDs = append(descendantIDs, v.DescendantId)
		createTimeMap[v.DescendantId] = v.CreateTime
	}

	// 并发查询代理信息
	agentMap := make(map[int64]*model.Agent)
	var descendantList []types.AgentSubordinateList
	err = mr.Finish(func() error {
		return mr.MapReduceVoid(func(source chan<- interface{}) {
			for _, id := range descendantIDs {
				source <- id
			}
		}, func(item interface{}, writer mr.Writer[interface{}], cancel func(error)) {
			id := item.(int64)
			agent, err := l.svcCtx.AgentModel.FindOne(l.ctx, id)
			if err != nil {
				cancel(err)
				return
			}
			writer.Write(agent)
		}, func(pipe <-chan interface{}, cancel func(error)) {
			for item := range pipe {
				agent := item.(*model.Agent)
				agentMap[agent.Id] = agent
			}
		})
	}, func() error {
		// 并发查询佣金扣除信息
		deductionBuilder := l.svcCtx.AgentCommissionDeductionModel.SelectBuilder().
			Where(squirrel.Eq{"agent_id": agentID}).
			Where(squirrel.Eq{"deducted_agent_id": descendantIDs})
		deductionList, err := l.svcCtx.AgentCommissionDeductionModel.FindAll(l.ctx, deductionBuilder, "")
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理佣金扣除信息%v", err)
		}
		deductionMap := make(map[int64]float64)
		for _, v := range deductionList {
			deductionMap[v.DeductedAgentId] += v.Amount
		}

		// 并发查询奖励信息
		rewardsBuilder := l.svcCtx.AgentRewardsModel.SelectBuilder().
			Where(squirrel.Eq{"agent_id": agentID}).
			Where(squirrel.Eq{"relation_agent_id": descendantIDs})
		rewardsList, err := l.svcCtx.AgentRewardsModel.FindAll(l.ctx, rewardsBuilder, "")
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理奖励信息%v", err)
		}
		rewardsMap := make(map[int64]float64)
		for _, v := range rewardsList {
			if v.RelationAgentId.Valid {
				rewardsMap[v.RelationAgentId.Int64] += v.Amount
			}
		}

		// 并发查询佣金信息
		commissionBuilder := l.svcCtx.AgentCommissionModel.SelectBuilder().
			Where(squirrel.Eq{"agent_id": descendantIDs})
		commissionList, err := l.svcCtx.AgentCommissionModel.FindAll(l.ctx, commissionBuilder, "")
		if err != nil {
			return errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理下级列表, 获取代理佣金信息%v", err)
		}
		commissionMap := make(map[int64]float64)
		orderCountMap := make(map[int64]int64)
		for _, v := range commissionList {
			commissionMap[v.AgentId] += v.Amount
			orderCountMap[v.AgentId]++
		}

		// 构建返回结果
		secretKey := l.svcCtx.Config.Encrypt.SecretKey
		descendantList = make([]types.AgentSubordinateList, 0, len(descendantIDs))
		for _, id := range descendantIDs {
			agent, exists := agentMap[id]
			if !exists {
				continue
			}

			mobile, err := crypto.DecryptMobile(agent.Mobile, secretKey)
			if err != nil {
				return errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取代理信息, 解密手机号失败: %v", err)
			}

			subordinate := types.AgentSubordinateList{
				ID:                id,
				Mobile:            maskPhone(mobile),
				LevelName:         agent.LevelName,
				CreateTime:        createTimeMap[id].Format("2006-01-02 15:04:05"),
				TotalContribution: deductionMap[id] + rewardsMap[id],
				TotalEarnings:     commissionMap[id],
				TotalOrders:       orderCountMap[id],
			}
			descendantList = append(descendantList, subordinate)
		}
		return nil
	})

	if err != nil {
		return nil, err
	}

	return &types.GetAgentSubordinateListResp{
		Total: total,
		List:  descendantList,
	}, nil
}

// 手机号脱敏
func maskPhone(phone string) string {
	length := len(phone)
	if length < 8 {
		return phone // 如果长度太短，可能不是手机号，不处理
	}
	// 保留前3位和后4位
	return phone[:3] + strings.Repeat("*", length-7) + phone[length-4:]
}
