package account

import (
	"context"

	"github.com/gogf/gf/v2/os/gtime"

	"kami/internal/dao"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/internal/service"
	"kami/utility/config"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/os/glog"
)

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

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

type sAccount struct{}

func (a *sAccount) Add(ctx context.Context, data do.V1AccountInfo, tx gdb.TX) (err error) {
	m := dao.V1AccountInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	data.UpdateTime = gtime.Now()
	data.CreateTime = gtime.Now()
	_, err = m.Save(data)
	if err != nil {
		glog.Error(ctx, "保存钱包错误", err)
		return gerror.New("保存钱包错误")
	}
	return
}

func (a *sAccount) HandleStatus(ctx context.Context, data entity.V1AccountInfo, tx gdb.TX) (err error) {
	m := dao.V1AccountInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	_, err = m.Where(dao.V1AccountInfo.Columns().AccountUid, data.AccountUid).
		Update(do.V1AccountInfo{Status: data.Status})
	if err != nil {
		glog.Error(ctx, "更新商户状态失败", err)
	}
	return err
}

func (a *sAccount) GetAccountByUId(ctx context.Context, Uid string) (data entity.V1AccountInfo, err error) {
	data = *new(entity.V1AccountInfo)
	err = dao.V1MerchantInfo.Ctx(ctx).DB(config.GetDatabaseV1()).Where(dao.V1MerchantInfo.Columns().MerchantUid, Uid).Scan(&data)
	if err != nil {
		glog.Error(ctx, "获取商户钱包失败", err)
	}
	return
}
