package dictionary

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

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/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")
	}

	// 找出第一级字典项，（父字典项id为0）
	dictItemFormat := make([]types.DictItemInfo, 0)
	for _, item := range dictList {
		if item.ParentId == "0" {
			dictItemFormat = append(dictItemFormat, item)
		}
	}
	// 排序
	sort.Slice(dictItemFormat, func(i, j int) bool {
		return dictItemFormat[i].SortOrder < dictItemFormat[j].SortOrder
	})

	// 递归找出一级路由下面的子路由
	getTreeMap(dictItemFormat, dictList)

	resp.List = dictItemFormat
	return resp, nil
}
