package wiki

import (
	"context"
	"fmt"
	"time"

	filePb "sundynix-micro-go/app/file/rpc/file"
	"sundynix-micro-go/app/plant/api/internal/svc"
	"sundynix-micro-go/app/plant/api/internal/types"
	plantPb "sundynix-micro-go/app/plant/rpc/plant"

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

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

// 百科详情
func NewGetWikiDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetWikiDetailLogic {
	return &GetWikiDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetWikiDetailLogic) GetWikiDetail(req *types.IdPathReq) (interface{}, error) {
	userId := fmt.Sprintf("%v", l.ctx.Value("userId"))
	result, err := l.svcCtx.PlantRpc.GetWikiDetail(l.ctx, &plantPb.IdReq{Id: req.Id})
	if err != nil {
		return nil, err
	}
	if result == nil || result.Wiki == nil {
		return nil, nil
	}

	// 通过 FileRpc 获取图片
	imgList := fetchWikiImages(l.ctx, l.svcCtx, result.Wiki.OssIds)

	_ = userId
	return map[string]interface{}{
		"wiki":           result.Wiki,
		"imgList":        imgList,
		"classIds":       result.Wiki.ClassIds,
		"relatedWikiIds": result.Wiki.RelatedWikiIds,
	}, nil
}

func fetchWikiImages(ctx context.Context, svcCtx *svc.ServiceContext, ossIds []string) []map[string]interface{} {
	if len(ossIds) == 0 {
		return []map[string]interface{}{}
	}
	resp, err := svcCtx.FileRpc.GetFilesByIds(ctx, &filePb.GetFilesByIdsReq{Ids: ossIds})
	if err != nil || resp == nil {
		return []map[string]interface{}{}
	}
	// 按 ossIds 顺序排列
	fileMap := make(map[string]*filePb.FileInfo)
	for _, f := range resp.Files {
		fileMap[f.Id] = f
	}
	var list []map[string]interface{}
	for _, id := range ossIds {
		if f, ok := fileMap[id]; ok {
			list = append(list, map[string]interface{}{
				"id": f.Id, "name": f.Name, "url": f.Url, "tag": f.Tag,
				"key": f.Key, "suffix": f.Suffix, "md5": f.Md5,
				"createdAt":    unixToRFC3339(f.CreatedAt),
				"updatedAt":    unixToRFC3339(f.CreatedAt),
				"createdAtStr": unixToShort(f.CreatedAt),
			})
		}
	}
	return list
}

func unixToRFC3339(ts int64) string {
	if ts == 0 {
		return ""
	}
	return time.Unix(ts, 0).Format(time.RFC3339)
}

func unixToShort(ts int64) string {
	if ts == 0 {
		return ""
	}
	return time.Unix(ts, 0).Format("2006-01-02 15:04:05")
}
