package dictionary

import (
	"context"
	"github.com/pkg/errors"

	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/api/internal/types"

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

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

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

func (l *ListDictItemByCodeLogic) ListDictItemByCode(req *types.DictCodeReq) (resp *types.PageResult, err error) {
	var dictList []types.DictItemInfo
	resp = &types.PageResult{}
	db := l.svcCtx.DbEngin.Model(&types.DictInfo{}).Table("t_dict")

	// 左连接查询
	err = db.Select("t_dict_item.*").Joins("left join t_dict_item on t_dict.id = t_dict_item.dict_id").
		Where("t_dict.dict_code = ?", req.DictCode).
		Where("t_dict_item.status", 1).
		Order("t_dict_item.sort_order").Scan(&dictList).Error
	if err != nil {
		logx.Errorf("ListDictItemByCode()=> failed %s", err.Error())
		return nil, errors.New("description Failed to query dictionary entry data")
	}
	resp.List = dictList
	return resp, nil
}
