package auth

import (
	"context"
	"github.com/suyuan32/simple-admin-common/config"
	"github.com/suyuan32/simple-admin-common/enum/common"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/encrypt"
	"github.com/suyuan32/simple-admin-common/utils/jwt"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"github.com/zeromicro/go-zero/core/logx"
	"net/http"
	"strings"
	"time"
	"wechat-api/internal/logic/fastgpt"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	rw     http.ResponseWriter
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext, rw http.ResponseWriter) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		rw:     rw,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	//判断调用类型

	if l.svcCtx.Config.LoginConf.LoginVerify != "captcha" && l.svcCtx.Config.LoginConf.LoginVerify != "all" {
		return nil, errorx.NewCodeAbortedError("login.loginTypeForbidden")
	}
	ok := l.svcCtx.Captcha.Verify(config.RedisCaptchaPrefix+req.CaptchaId, req.Captcha, true)
	if !ok {
		return nil, errorx.NewCodeInvalidArgumentError("login.wrongCaptcha")
	}
	user, err := l.svcCtx.CoreRpc.GetUserByUsername(l.ctx,
		&core.UsernameReq{
			Username: req.Username,
		})
	if err != nil {
		return nil, err
	}
	if !encrypt.BcryptCheck(req.Password, *user.Password) {
		return nil, errorx.NewCodeInvalidArgumentError("login.wrongUsernameOrPassword")
	}
	token, err := jwt.NewJwtToken(l.svcCtx.Config.Auth.AccessSecret, time.Now().Unix(),
		l.svcCtx.Config.Auth.AccessExpire, jwt.WithOption("userId", user.Id), jwt.WithOption("roleId",
			strings.Join(user.RoleCodes, ",")), jwt.WithOption("deptId", user.DepartmentId))
	if err != nil {
		return nil, err
	}
	// add token into database
	expiredAt := time.Now().Add(time.Second * time.Duration(l.svcCtx.Config.Auth.AccessExpire)).UnixMilli()
	_, err = l.svcCtx.CoreRpc.CreateToken(l.ctx, &core.TokenInfo{
		Uuid:      user.Id,
		Token:     pointy.GetPointer(token),
		Source:    pointy.GetPointer("core_user"),
		Status:    pointy.GetPointer(uint32(common.StatusNormal)),
		Username:  user.Username,
		ExpiredAt: pointy.GetPointer(expiredAt),
	})
	if err != nil {
		return nil, err
	}
	err = l.svcCtx.Rds.Del(l.ctx, config.RedisCaptchaPrefix+req.CaptchaId).Err()
	if err != nil {
		logx.Errorw("failed to delete captcha in redis", logx.Field("detail", err))
	}
	//请求fastgpt，并种cookie。先同步，后期可以异步
	//set_cookie.NewFastGpt(l.svcCtx, fastgptLogic)
	fastgptLogic := fastgpt.NewSetTokenLogic(l.ctx, l.svcCtx, l.rw)
	//userId := *user.Id
	//静默执行
	_, _ = fastgptLogic.SetTokenByUserId(*user.Id)
	//if err != nil {
	//	return nil, err
	//}
	resp = &types.LoginResp{
		BaseDataInfo: types.BaseDataInfo{Msg: errormsg.Success},
		Data: types.LoginInfo{
			UserId: *user.Id,
			Token:  token,
			Expire: uint64(expiredAt),
		},
	}
	return resp, nil
}
