package dictionary

import (
	"context"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/dictionarydetail"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/ent/predicate"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/utils/hander"

	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/internal/svc"
	"git.noahlan.cn/n-admin/n-admin-server/rpc/core/types/core"
)

type GetDictionaryDetailListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetDictionaryDetailListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetDictionaryDetailListLogic {
	return &GetDictionaryDetailListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetDictionaryDetailListLogic) GetDictionaryDetailList(in *core.DictionaryDetailReq) (*core.DictionaryDetailListResp, error) {
	var predicates []predicate.DictionaryDetail
	if in.DictId != 0 {
		predicates = append(predicates, dictionarydetail.DictionaryIDEQ(in.DictId))
	}
	if in.Title != "" {
		predicates = append(predicates, dictionarydetail.TitleContains(in.Title))
	}
	if in.Key != "" {
		predicates = append(predicates, dictionarydetail.KeyContains(in.Key))
	}
	if in.Value != "" {
		predicates = append(predicates, dictionarydetail.ValueEQ(in.Value))
	}

	query := l.svcCtx.DB.DictionaryDetail.Query().Where(predicates...)
	if in.WithDictionary {
		query.WithDictionary()
	}
	var (
		pagination *core.Pagination
		list       []*ent.DictionaryDetail
		err        error
	)
	if in.Page != nil {
		result, pageErr := query.Page(l.ctx, in.Page.Current, in.Page.Size)
		if pageErr == nil {
			pagination = utils.ConvertPaginationDb(result.PageDetails)
			list = result.List
		} else {
			err = pageErr
		}
	} else {
		list, err = query.All(l.ctx)
	}
	if err != nil {
		return nil, hander.HandleEntErr(err, in)
	}
	resp := &core.DictionaryDetailListResp{
		Page: pagination,
		Data: make([]*core.DictionaryDetailInfo, len(list)),
	}

	for i, v := range list {
		resp.Data[i] = l.svcCtx.Convert.ConvertDictionaryDetailRpc(l.ctx, v)
	}
	return resp, nil
}
