package user_center

import (
	"context"
	"kami/api/commonApi"
	"kami/internal/model"
	"kami/internal/service"
	"kami/internal/systemV2/dao"
	"kami/internal/systemV2/model/entity"
	"kami/utility/config"
	"kami/utility/lib/libErr"
	"kami/utility/verify"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
)

func init() {
	service.RegisterUserCenter(New())
}

func New() *sUserCenter {
	return &sUserCenter{}
}

type sUserCenter struct{}

func (c *sUserCenter) GetUserByUserNameOrPhone(ctx context.Context, userInfo entity.V2User) (user entity.V2User, err error) {
	//	登录
	err = dao.V2User.Ctx(ctx).
		Where(dao.V2User.Columns().Username, userInfo.Username).
		WhereOr(dao.V2User.Columns().Phone, userInfo.Phone).Scan(&user)
	if err != nil {
		return user, gerror.New("用户查找失败")
	}

	if user.Id == "" {
		return user, gerror.New("用户查找失败")
	}
	return
}

// CheckPassword 检查新密码和旧密码是不是相同
func (c *sUserCenter) CheckPassword(ctx context.Context, oldPassword, newPassword string) (bool, error) {
	cfg := config.NewConfig(ctx)

	frontendModel, err := cfg.GetFrontendSecret()
	if err != nil {
		return false, err
	}

	backendModel, err := cfg.GetFrontendSecret()
	if err != nil {
		return false, err
	}

	frontendResult, err := verify.AesCBCStdDecryptWithBase64(newPassword, []byte(frontendModel.Key), []byte(frontendModel.IV))
	if err != nil {
		return false, err
	}

	backendResult, err := verify.AesCBCStdDecryptWithBase64(oldPassword, []byte(backendModel.Key), []byte(backendModel.IV))
	if err != nil {
		return false, err
	}

	return string(frontendResult) == string(backendResult), nil
}

func (c *sUserCenter) CreateUser(ctx context.Context, userInfo entity.V2User) (err error) {
	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		return g.Try(ctx, func(ctx context.Context) {
			_, err = dao.V2User.Ctx(ctx).TX(tx).Save(userInfo)
			libErr.ErrIsNil(ctx, err, "添加用户失败")
		})
	})
	return err
}

func (c *sUserCenter) ReGeneratePassword(ctx context.Context, password string) (newPassword string, err error) {
	cfg := config.NewConfig(ctx)

	frontendModel, err := cfg.GetFrontendSecret()
	if err != nil {
		return "", err
	}

	backendModel, err := cfg.GetFrontendSecret()
	if err != nil {
		return "", err
	}

	frontendResult, err := verify.AesCBCStdDecryptWithBase64(password, []byte(frontendModel.Key), []byte(frontendModel.IV))
	if err != nil {
		return "", err
	}

	return verify.AesCBCEncryptWithBase64(string(frontendResult), []byte(backendModel.Key), []byte(backendModel.IV))
}

func (c *sUserCenter) GetUserList(ctx context.Context, req commonApi.CommonPageReq) (list []model.User, total int, err error) {
	m := dao.V2User.Ctx(ctx).Page(req.Current, req.PageSize)
	_, _ = m.Count(&total)
	err = m.Scan(&list)
	return
}
