package admin_agent

import (
	"context"

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

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

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

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

func (l *AdminGetAgentCommissionDeductionListLogic) AdminGetAgentCommissionDeductionList(req *types.AdminGetAgentCommissionDeductionListReq) (resp *types.AdminGetAgentCommissionDeductionListResp, err error) {
	builder := l.svcCtx.AgentCommissionDeductionModel.SelectBuilder()
	if req.AgentId != nil {
		builder = builder.Where(squirrel.Eq{"agent_id": *req.AgentId})
	}
	if req.Type != nil && *req.Type != "" {
		builder = builder.Where(squirrel.Eq{"type": *req.Type})
	}
	if req.Status != nil {
		builder = builder.Where(squirrel.Eq{"status": *req.Status})
	}
	// 产品名筛选需先查product_id
	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.AdminGetAgentCommissionDeductionListResp{Total: 0, Items: []types.AgentCommissionDeductionListItem{}}, nil
		}
		builder = builder.Where("product_id = ?", products[0].Id)
	}

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

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

	items := make([]types.AgentCommissionDeductionListItem, 0, len(list))
	for _, v := range list {
		item := types.AgentCommissionDeductionListItem{}
		_ = 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.AdminGetAgentCommissionDeductionListResp{
		Total: total,
		Items: items,
	}
	return
}
