package user

import (
	"context"

	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"

	"git.i2edu.net/i2/go-zero/core/logx"
)

type BindMobileLogic struct {
	logx.Logger
	ctx        context.Context
	svcCtx     *svc.ServiceContext
	UserId     int64
	SessionKey string
}

func NewBindMobileLogic(ctx context.Context, svcCtx *svc.ServiceContext) BindMobileLogic {
	return BindMobileLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *BindMobileLogic) BindMobile(req types.BindMobileRequest) (*types.Response, error) {
	mobile, err := l.svcCtx.Wechat.DecryptMobile(l.SessionKey, req.EncryptedData, req.Iv)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	_, err = l.svcCtx.SqlConn.Exec(`update i2bill_user set mobile = ? where id = ?`, mobile, l.UserId)
	if err != nil {
		logx.Error(err)
		return nil, err
	}
	resp := make(map[string]interface{})
	resp["id"] = l.UserId
	resp["mobile"] = mobile
	return &types.Response{
		200, "", resp,
	}, nil
}
