package admin_product

import (
	"context"
	"in-server/app/main/api/internal/svc"
	"in-server/app/main/api/internal/types"
	"in-server/app/main/model"
	"in-server/common/xerr"

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

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

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

func (l *AdminGetProductFeatureListLogic) AdminGetProductFeatureList(req *types.AdminGetProductFeatureListReq) (resp *[]types.AdminGetProductFeatureListResp, err error) {
	// 1. 构建查询条件
	builder := l.svcCtx.ProductFeatureModel.SelectBuilder().
		Where("product_id = ?", req.ProductId)

	// 2. 执行查询
	list, err := l.svcCtx.ProductFeatureModel.FindAll(l.ctx, builder, "sort ASC")
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询产品功能列表失败, err: %v, product_id: %d", err, req.ProductId)
	}

	// 3. 获取所有功能ID
	featureIds := make([]string, 0, len(list))
	for _, item := range list {
		featureIds = append(featureIds, item.FeatureId)
	}

	// 4. 并发查询功能详情
	type featureResult struct {
		feature *model.Feature
		err     error
	}

	results := make([]featureResult, len(featureIds))
	err = mr.MapReduceVoid(func(source chan<- interface{}) {
		for i, id := range featureIds {
			source <- struct {
				index int
				id    string
			}{i, id}
		}
	}, func(item interface{}, writer mr.Writer[featureResult], cancel func(error)) {
		data := item.(struct {
			index int
			id    string
		})
		feature, err := l.svcCtx.FeatureModel.FindOne(l.ctx, data.id)
		writer.Write(featureResult{
			feature: feature,
			err:     err,
		})
	}, func(pipe <-chan featureResult, cancel func(error)) {
		for result := range pipe {
			if result.err != nil {
				l.Logger.Errorf("查询功能详情失败, feature_id: %s, err: %v", result.feature.Id, result.err)
				continue
			}
			results = append(results, result)
		}
	})

	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR),
			"并发查询功能详情失败, err: %v", err)
	}

	// 5. 构建功能ID到详情的映射
	featureMap := make(map[string]*model.Feature)
	for _, result := range results {
		if result.feature != nil {
			featureMap[result.feature.Id] = result.feature
		}
	}

	// 6. 构建响应列表
	items := make([]types.AdminGetProductFeatureListResp, 0, len(list))
	for _, item := range list {
		feature, exists := featureMap[item.FeatureId]
		if !exists {
			continue // 跳过不存在的功能
		}

		listItem := types.AdminGetProductFeatureListResp{
			Id:          item.Id,
			ProductId:   item.ProductId,
			FeatureId:   item.FeatureId,
			ApiId:       feature.ApiId,
			Name:        feature.Name,
			Sort:        item.Sort,
			Enable:      item.Enable,
			IsImportant: item.IsImportant,
			CreateTime:  item.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:  item.UpdateTime.Format("2006-01-02 15:04:05"),
		}
		items = append(items, listItem)
	}

	// 7. 返回结果
	return &items, nil
}
