package admin_agent

import (
	"context"

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

	"github.com/Masterminds/squirrel"
	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminGetAgentCommissionListLogic) AdminGetAgentCommissionList(req *types.AdminGetAgentCommissionListReq) (resp *types.AdminGetAgentCommissionListResp, err error) {
	builder := l.svcCtx.AgentCommissionModel.SelectBuilder()
	if req.AgentId != nil {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}
	if req.Status != nil {
		builder = builder.Where(squirrel.Eq{"status": *req.Status})
	}
	// 先查出所有product_id对应的product_name（如有product_name筛选，需反查id）
	var productIdFilter int64
	if req.ProductName != nil && *req.ProductName != "" {
		// 只支持精确匹配，如需模糊可扩展
		products, err := l.svcCtx.ProductModel.FindAll(l.ctx, l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Eq{"product_name": *req.ProductName}), "")
		if err != nil || len(products) == 0 {
			return &types.AdminGetAgentCommissionListResp{Total: 0, Items: []types.AgentCommissionListItem{}}, nil
		}
		productIdFilter = products[0].Id
		builder = builder.Where("product_id = ?", productIdFilter)
	}

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

	// 批量查product_name
	productIds := make(map[int64]struct{})
	for _, v := range list {
		productIds[v.ProductId] = struct{}{}
	}
	productNameMap := make(map[int64]string)
	if len(productIds) > 0 {
		ids := make([]int64, 0, len(productIds))
		for id := range productIds {
			ids = append(ids, id)
		}
		builder := l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Eq{"id": ids})
		products, _ := l.svcCtx.ProductModel.FindAll(l.ctx, builder, "")
		for _, p := range products {
			productNameMap[p.Id] = p.ProductName
		}
	}

	items := make([]types.AgentCommissionListItem, 0, len(list))
	for _, v := range list {
		item := types.AgentCommissionListItem{}
		_ = copier.Copy(&item, v)
		item.ProductName = productNameMap[v.ProductId]
		item.CreateTime = v.CreateTime.Format("2006-01-02 15:04:05")
		items = append(items, item)
	}
	resp = &types.AdminGetAgentCommissionListResp{
		Total: total,
		Items: items,
	}
	return
}
