package dictionary

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

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

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

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

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

func (l *EditDictItemLogic) EditDictItem(req *types.DictItemEditReq) (resp *types.DictItemResp, err error) {
	dictItem := &types.DictItemInfo{}
	result := l.svcCtx.DbEngin.Table("t_dict_item").First(&dictItem, req.Id)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		logx.Errorf("Dictionary data editing failure. errors: %s", result.Error)
		return nil, errors.New("DictItem does not exist")
	}
	utils.Convert(req, &dictItem)
	l.svcCtx.DbEngin.Table("t_dict_item").Model(&dictItem).Updates(&dictItem)
	return
}
