package dictionary

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/utils"
	"gorm.io/gorm"
	"time"

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

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

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

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

func (l *AddDictItemLogic) AddDictItem(req *types.DictItemEditReq) (resp *types.DictItemResp, err error) {
	dict := &types.DictInfo{}
	result := l.svcCtx.DbEngin.Table("t_dict").First(&dict, req.DictId)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		return nil, errors.New("Dictionary does not exist")
	}
	var dictItem types.DictItemInfo
	dictItem.DictId = req.DictId
	dictItem.ItemText = req.ItemText
	dictItem.ItemValue = req.ItemValue
	dictItem.Description = req.Description
	dictItem.SortOrder = req.SortOrder
	dictItem.ParentId = "0"
	if req.ParentId != "" {
		dictItem.ParentId = req.ParentId
	}
	dictItem.Status = req.Status
	dictItem.Id = utils.GenSnowflakeIDStr()
	dictItem.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	result = l.svcCtx.DbEngin.Table("t_dict_item").Create(&dictItem)
	if result.Error != nil {
		logx.Errorf("Failed to create dictionary item , errors: %s", result.Error)
		return nil, result.Error
	}
	return
}
