package service

import (
	"context"
	"encoding/json"
	"errors"
	"kra/internal/biz/system"

	"kra/internal/service/dto"
)

func (s *DictionaryService) ImportDictionaryJSON(ctx context.Context, raw string) error {
	var payload struct {
		Name        string                        `json:"name"`
		Type        string                        `json:"type"`
		Status      *bool                         `json:"status"`
		Description string                        `json:"desc"`
		Details     []dto.DictionaryDetailRequest `json:"sysDictionaryDetails"`
	}
	if err := json.Unmarshal([]byte(raw), &payload); err != nil {
		return errors.New("JSON 格式错误: " + err.Error())
	}
	if payload.Name == "" {
		return errors.New("字典名称不能为空")
	}
	if payload.Type == "" {
		return errors.New("字典类型不能为空")
	}
	dictionary := dictionaryDomain(&dto.DictionaryRequest{Name: payload.Name, Type: payload.Type, Status: payload.Status, Description: payload.Description})
	details := make([]*system.DictionaryDetail, 0, len(payload.Details))
	for i := range payload.Details {
		details = append(details, detailDomain(&payload.Details[i]))
	}
	return s.uc.ImportDictionary(ctx, dictionary, details)
}
func (s *DictionaryService) DictionaryDetailsByParent(ctx context.Context, dictionaryID uint, parentID *uint, includeChildren bool) ([]*dto.DictionaryDetailResponse, error) {
	items, err := s.uc.DictionaryDetailsByParent(ctx, dictionaryID, parentID, includeChildren)
	if err != nil {
		return nil, err
	}
	out := make([]*dto.DictionaryDetailResponse, 0, len(items))
	for _, item := range items {
		out = append(out, detailDTO(item))
	}
	return out, nil
}
