package user

import (
	"context"
	"encoding/json"
	"git.i2edu.net/i2/i2-bill-api/internal/svc"
	"git.i2edu.net/i2/i2-bill-api/internal/types"
	"git.i2edu.net/i2/i2-bill-api/model"
	"io/ioutil"
	"net/http"

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

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

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

func (l *UpdateUserLogic) UpdateUser(r *http.Request) (*types.Response, error) {
	// todo: add your logic here and delete this line
	userId := l.svcCtx.GetUserIdByJwt(l.ctx)
	user := new(model.UserXorm)
	bodyByte, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	err = json.Unmarshal(bodyByte, user)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	user.Id = userId
	_, err = l.svcCtx.DB.ID(user.Id).Cols("avatar").Update(user)
	if err != nil {
		logx.Error(err.Error())
		return &types.Response{500, err.Error(), nil}, nil
	}
	return &types.Response{200, "", nil}, nil
}
