package wxcardvisit

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/wxcardvisit"
	"wechat-api/internal/utils/dberrorhandler"

	"wechat-api/internal/svc"
	"wechat-api/internal/types"

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

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

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

func (l *SubmitApiWxCardVisitLogic) SubmitApiWxCardVisit(req *types.WxCardVisitInfo) (*types.BaseMsgResp, error) {
	userId := l.ctx.Value("userId").(uint64)

	var botId uint64
	var botType uint8
	if req.BotId != nil && *req.BotId > 0 {
		botId = *req.BotId
	}
	if req.BotType != nil && *req.BotType > 0 {
		botType = *req.BotType
	}

	if botId == 0 || botType == 0 {
		return nil, errorx.NewInvalidArgumentError("参数非法")
	}

	_, err := l.svcCtx.DB.WxCardVisit.Query().Where(wxcardvisit.BotID(botId), wxcardvisit.BotType(botType)).First(l.ctx)
	if err != nil && !ent.IsNotFound(err) {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 创建记录
	_, err = l.svcCtx.DB.WxCardVisit.Create().
		SetBotID(botId).
		SetBotType(botType).
		SetUserID(userId).
		Save(l.ctx)
	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	return &types.BaseMsgResp{
		Code: 0,
		Msg:  errormsg.Success,
	}, nil
}
