package dictionary

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

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

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

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

func (l *DeleteDictLogic) DeleteDict(req *types.CId) (resp *types.DictResp, err error) {
	var sId int64
	l.svcCtx.DbEngin.Table("t_dict").Raw("select d.id from t_dict_item di left join t_dict d on di.dict_id=d.id where d.id=? limit 1", req.Id).Scan(&sId)
	if sId != 0 {
		return nil, errors.New("Delete failed,The dictionary is associated with a dictionary item")
	}
	db := l.svcCtx.DbEngin.Table("t_dict").Where("id = ?", req.Id).First(&types.DictInfo{})
	if db.Error != nil {
		logx.Errorf("err %v", db.Error.Error())
		return nil, errors.New("Dictionary does not exist")
	}
	tx := l.svcCtx.DbEngin.Table("t_dict").Delete(types.DictInfo{}, req.Id)
	if tx.Error != nil {
		logx.Errorf("err %v", db.Error.Error())
		return nil, errors.New("Delete dictionary failed")
	}
	return
}
