package product

import (
	"context"
	"fmt"
	"sort"
	"in-server/app/main/model"
	"in-server/common/xerr"

	"github.com/Masterminds/squirrel"
	"github.com/jinzhu/copier"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/mr"

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

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

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

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

func (l *GetProductByEnLogic) GetProductByEn(req *types.GetProductByEnRequest) (resp *types.ProductResponse, err error) {
	productModel, err := l.svcCtx.ProductModel.FindOneByProductEn(l.ctx, req.ProductEn)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "产品查询, 查找产品错误: %v", err)
	}

	build := l.svcCtx.ProductFeatureModel.SelectBuilder().Where(squirrel.Eq{
		"product_id": productModel.Id,
	})
	productFeatureAll, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, build, "")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "产品查询, 查找产品关联错误: %v", err)
	}

	// 创建featureId到sort的映射，用于后续排序
	featureSortMap := make(map[string]int64)
	for _, productFeature := range productFeatureAll {
		featureSortMap[fmt.Sprintf("%d", productFeature.FeatureId)] = productFeature.Sort
	}

	var product types.Product
	err = copier.Copy(&product, productModel)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "用户信息, 用户信息结构体复制失败, %v", err)
	}
	mr.MapReduceVoid(func(source chan<- interface{}) {
		for _, productFeature := range productFeatureAll {
			source <- productFeature.FeatureId
		}
	}, func(item interface{}, writer mr.Writer[*model.Feature], cancel func(error)) {
		id := item.(string)

		feature, findFeatureErr := l.svcCtx.FeatureModel.FindOne(l.ctx, id)
		if findFeatureErr != nil {
			logx.WithContext(l.ctx).Errorf("产品查询, 查找关联feature错误: %d, err:%v", id, findFeatureErr)
			return
		}
		if feature != nil && feature.Id != "" {
			writer.Write(feature)
		}
	}, func(pipe <-chan *model.Feature, cancel func(error)) {
		for item := range pipe {
			var feature types.Feature
			_ = copier.Copy(&feature, item)
			product.Features = append(product.Features, feature)
		}
	})

	// 按照productFeature.Sort字段对features进行排序
	sort.Slice(product.Features, func(i, j int) bool {
		sortI := featureSortMap[product.Features[i].ID]
		sortJ := featureSortMap[product.Features[j].ID]
		return sortI < sortJ
	})

	return &types.ProductResponse{Product: product}, nil
}
