package admin_agent

import (
	"context"
	"time"

	"tydata-server/app/main/api/internal/svc"
	"tydata-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.OrderId != nil {
		builder = builder.Where(squirrel.Eq{"order_id": *req.OrderId})
	}
	if req.Status != nil {
		builder = builder.Where(squirrel.Eq{"status": *req.Status})
	}

	// 时间范围筛选
	if req.CreateTimeStart != nil && *req.CreateTimeStart != "" {
		startTime, err := time.Parse("2006-01-02 15:04:05", *req.CreateTimeStart)
		if err == nil {
			builder = builder.Where(squirrel.GtOrEq{"create_time": startTime})
		}
	}
	if req.CreateTimeEnd != nil && *req.CreateTimeEnd != "" {
		endTime, err := time.Parse("2006-01-02 15:04:05", *req.CreateTimeEnd)
		if err == nil {
			builder = builder.Where(squirrel.LtOrEq{"create_time": endTime})
		}
	}

	// 先查出所有product_id对应的product_name（如有product_name筛选，需反查id）
	if req.ProductName != nil && *req.ProductName != "" {
		// 支持模糊匹配产品名称
		products, err := l.svcCtx.ProductModel.FindAll(l.ctx, l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Like{"product_name": "%" + *req.ProductName + "%"}), "")
		if err != nil || len(products) == 0 {
			return &types.AdminGetAgentCommissionListResp{Total: 0, Items: []types.AgentCommissionListItem{}}, nil
		}
		productIds := make([]int64, 0, len(products))
		for _, p := range products {
			productIds = append(productIds, p.Id)
		}
		builder = builder.Where(squirrel.Eq{"product_id": productIds})
	}

	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
}
