fusenapi/server/map-library/internal/logic/savemaplibrarylogic.go
laodaming e71fb08bd4 fix
2023-06-20 11:52:26 +08:00

99 lines
2.5 KiB
Go

package logic
import (
"context"
"encoding/json"
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
"fusenapi/utils/basic"
"gorm.io/gorm"
"strconv"
"time"
"fusenapi/server/map-library/internal/svc"
"fusenapi/server/map-library/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type SaveMapLibraryLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewSaveMapLibraryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveMapLibraryLogic {
return &SaveMapLibraryLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *SaveMapLibraryLogic) SaveMapLibrary(req *types.SaveMapLibraryReq, userinfo *auth.UserInfo) (resp *basic.Response) {
if userinfo.GetIdType() != auth.IDTYPE_User {
return resp.SetStatusWithMessage(basic.CodeServiceErr, "please login first")
}
//获取所有贴图数据[获取id]
mapLibraryModel := gmodel.NewFsMapLibraryModel(l.svcCtx.MysqlConn)
maplibraryList, err := mapLibraryModel.GetAllEnabledList(l.ctx, "`id`")
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeServiceErr, "failed to get map library list")
}
sort := int64(0)
status := int64(1)
now := time.Now().Unix()
needDeleteMid := make([]int64, 0, len(req.Data))
mapPostMid := make(map[int64]struct{})
//开启事务
err = l.svcCtx.MysqlConn.Transaction(func(tx *gorm.DB) error {
for _, v := range req.Data {
infoByte, _ := json.Marshal(v.Info)
infoJsonStr := string(infoByte)
switch v.Mid {
case "": //新增
err = mapLibraryModel.Create(l.ctx, &gmodel.FsMapLibrary{
Title: &v.Info.Title,
Info: &infoJsonStr,
Sort: &sort,
Status: &status,
Ctime: &now,
TagId: &v.Tag.Id,
})
if err != nil {
return err
}
default: //修改
midInt, err := strconv.ParseInt(v.Mid, 10, 64)
if err != nil {
return err
}
mapPostMid[midInt] = struct{}{}
err = mapLibraryModel.Update(l.ctx, midInt, &gmodel.FsMapLibrary{
Title: &v.Info.Title,
Info: &infoJsonStr,
TagId: &v.Tag.Id,
})
if err != nil {
return err
}
}
}
//删除需要删除的
for _, v := range maplibraryList {
//旧的不在新的里面则删除
if _, ok := mapPostMid[v.Id]; !ok {
needDeleteMid = append(needDeleteMid, v.Id)
}
}
return mapLibraryModel.ChangeStatusByIds(l.ctx, needDeleteMid, 0)
})
if err != nil {
logx.Error(err)
return resp.SetStatusWithMessage(basic.CodeSaveErr, "failed to save map library info")
}
return resp.SetStatusWithMessage(basic.CodeOK, "success")
}