package wxcarduser

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

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

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

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

func (l *UpdateApiWxCardUserLogic) UpdateApiWxCardUser(req *types.WxCardUserInfo) (*types.BaseMsgResp, error) {
	userId := l.ctx.Value("userId").(uint64)

	var nickname, avatar string
	if req.Nickname != nil && *req.Nickname != "" {
		nickname = *req.Nickname
	}
	if req.Avatar != nil && *req.Avatar != "" {
		avatar = *req.Avatar
	}
	if nickname == "" && avatar == "" {
		return nil, errorx.NewInvalidArgumentError("参数错误")
	}

	wxCardUser, err := l.svcCtx.DB.WxCardUser.Query().Where(wxcarduser.ID(userId)).Only(l.ctx)
	if err != nil && !ent.IsNotFound(err) {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	// 这里检查昵称的是否含有敏感词
	AppId := l.svcCtx.Config.Miniprogram.Appid
	Secret := l.svcCtx.Config.Miniprogram.Secret
	app, err := wechat.NewClient(AppId, Secret)
	if err != nil {
		return nil, errorx.NewApiInternalError("init wechat miniprogram failed")
	}
	result, err := app.Security.MsgSecCheck(
		wxCardUser.OpenID,
		1,
		2,
		nickname,
		nickname,
		"",
		"",
	)
	if err != nil {
		return nil, errorx.NewInternalError("网络错误，请稍后重拾")
	}
	if result.Result.Label != 100 {
		return nil, errorx.NewInvalidArgumentError("昵称内容不合法，请修改后重试")
	}
	if wxCardUser != nil {
		query := l.svcCtx.DB.WxCardUser.UpdateOneID(userId)
		if nickname != "" {
			query = query.SetNickname(nickname)
		}
		if avatar != "" {
			query = query.SetAvatar(avatar)
		}
		_, err = query.Save(l.ctx)
		if err != nil {
			return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
		}
	}

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