package agent

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

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

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

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

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

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

func (l *GetLinkDataLogic) GetLinkData(req *types.GetLinkDataReq) (resp *types.GetLinkDataResp, err error) {
	agentLinkModel, err := l.svcCtx.AgentLinkModel.FindOneByLinkIdentifier(l.ctx, req.LinkIdentifier)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理链接数据失败, %v", err)
	}

	productModel, err := l.svcCtx.ProductModel.FindOne(l.ctx, agentLinkModel.ProductId)
	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[productFeature.FeatureId] = productFeature.Sort
	}

	var features []types.Feature
	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("获取产品功能失败: %s, 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)
			features = append(features, feature)
		}
	})

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

	return &types.GetLinkDataResp{
		AgentId:         agentLinkModel.AgentId,
		ProductId:       agentLinkModel.ProductId,
		SetPrice:        agentLinkModel.SetPrice,
		ActualBasePrice: agentLinkModel.ActualBasePrice,
		ProductName:     productModel.ProductName,
		ProductEn:       productModel.ProductEn,
		SellPrice:       agentLinkModel.SetPrice, // 使用代理设定价格作为销售价格
		Description:     productModel.Description,
		Features:        features,
	}, nil
}
