package admin_agent

import (
	"context"
	"qnc-server/common/globalkey"
	"qnc-server/common/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/pkg/errors"

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

	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *AdminGetAgentOrderListLogic) AdminGetAgentOrderList(req *types.AdminGetAgentOrderListReq) (resp *types.AdminGetAgentOrderListResp, err error) {
	builder := l.svcCtx.AgentOrderModel.SelectBuilder().
		Where("del_state = ?", globalkey.DelStateNo)

	if req.AgentId != nil {
		builder = builder.Where("agent_id = ?", *req.AgentId)
	}
	if req.OrderId != nil {
		builder = builder.Where("order_id = ?", *req.OrderId)
	}
	if req.ProcessStatus != nil {
		builder = builder.Where("process_status = ?", *req.ProcessStatus)
	}

	// 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 20
	}

	orders, total, err := l.svcCtx.AgentOrderModel.FindPageListByPageWithTotal(l.ctx, builder, page, pageSize, "create_time DESC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "查询代理订单列表失败, %v", err)
	}

	// 批量查询产品名称
	productIdSet := make(map[string]struct{})
	for _, order := range orders {
		productIdSet[order.ProductId] = struct{}{}
	}
	productIdList := make([]string, 0, len(productIdSet))
	for id := range productIdSet {
		productIdList = append(productIdList, id)
	}
	productNameMap := make(map[string]string)
	if len(productIdList) > 0 {
		products, _ := l.svcCtx.ProductModel.FindAll(l.ctx, l.svcCtx.ProductModel.SelectBuilder().Where(squirrel.Eq{"id": productIdList}), "")
		for _, p := range products {
			productNameMap[p.Id] = p.ProductName
		}
	}

	// 组装响应
	items := make([]types.AgentOrderListItem, 0, len(orders))
	for _, order := range orders {
		items = append(items, types.AgentOrderListItem{
			Id:              order.Id,
			AgentId:         order.AgentId,
			OrderId:         order.OrderId,
			ProductId:       order.ProductId,
			ProductName:     productNameMap[order.ProductId],
			OrderAmount:     order.OrderAmount,
			SetPrice:        order.SetPrice,
			ActualBasePrice: order.ActualBasePrice,
			PriceCost:       order.PriceCost,
			AgentProfit:     order.AgentProfit,
			ProcessStatus:   order.ProcessStatus,
			CreateTime:      order.CreateTime.Format("2006-01-02 15:04:05"),
		})
	}

	return &types.AdminGetAgentOrderListResp{
		Total: total,
		Items: items,
	}, nil
}
