package admin_agent

import (
	"context"

	"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 AdminGetAgentProductionConfigListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

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

func (l *AdminGetAgentProductionConfigListLogic) AdminGetAgentProductionConfigList(req *types.AdminGetAgentProductionConfigListReq) (resp *types.AdminGetAgentProductionConfigListResp, err error) {
	builder := l.svcCtx.AgentProductConfigModel.SelectBuilder()
	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.AdminGetAgentProductionConfigListResp{Total: 0, Items: []types.AgentProductionConfigItem{}}, nil
		}
		builder = builder.Where(squirrel.Eq{"product_id": products[0].Id})
	}
	if req.Id != nil {
		builder = builder.Where(squirrel.Eq{"id": *req.Id})
	}
	list, total, err := l.svcCtx.AgentProductConfigModel.FindPageListByPageWithTotal(l.ctx, builder, req.Page, req.PageSize, "create_time DESC")
	if err != nil {
		return nil, err
	}
	// 查询所有涉及到的product_id对应的product_name
	productIdSet := make(map[int64]struct{})
	for _, v := range list {
		productIdSet[v.ProductId] = struct{}{}
	}
	productIdArr := make([]int64, 0, len(productIdSet))
	for id := range productIdSet {
		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.AgentProductionConfigItem, 0, len(list))
	for _, v := range list {
		item := types.AgentProductionConfigItem{}
		_ = 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.AdminGetAgentProductionConfigListResp{
		Total: total,
		Items: items,
	}
	return
}
