package credit_balance

import (
	"context"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/errorx"
	"wechat-api/ent"
	"wechat-api/ent/creditbalance"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

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

func NewCreateCreditBalanceLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCreditBalanceLogic {
	return &CreateCreditBalanceLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateCreditBalanceLogic) CreateCreditBalance(req *types.CreditBalanceInfo) (*types.BaseMsgResp, error) {
	userId := l.ctx.Value("userId").(string)

	if req.OrganizationId == nil || *req.OrganizationId <= 0 {
		return nil, errorx.NewInvalidArgumentError("参数非法")
	}

	_, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: *req.OrganizationId})
	if err != nil {
		return nil, errorx.NewAlreadyExistsError("租户不存在")
	}

	tx, err := l.svcCtx.DB.Tx(context.Background())
	if err != nil {
		return nil, err
	}

	old, err := tx.CreditBalance.Query().Where(creditbalance.OrganizationID(*req.OrganizationId)).First(l.ctx)
	if err != nil && ent.IsNotFound(err) {
		_, err = tx.CreditBalance.Create().
			SetNotNilUserID(req.UserId).
			SetNotNilBalance(req.Balance).
			SetNotNilOrganizationID(req.OrganizationId).
			Save(l.ctx)

		if err != nil {
			l.Logger.Errorf("create credit_balance failed! err=%v\n", err)
			_ = tx.Rollback()
		}

	} else {
		_, err = tx.CreditBalance.UpdateOneID(old.ID).
			SetBalance(*req.Balance + old.Balance).
			Save(l.ctx)

		if err != nil {
			l.Logger.Errorf("update credit_balance failed! err=%v\n", err)
			_ = tx.Rollback()
		}
	}

	_, err = tx.CreditUsage.Create().
		SetNotNilUserID(req.UserId).
		SetNotNilNumber(req.Balance).
		SetNtype(2).
		SetTable("").
		SetNotNilOrganizationID(req.OrganizationId).
		SetNid(0).
		SetReason("管理员操作").
		SetOperator(userId).
		Save(l.ctx)
	if err != nil {
		l.Logger.Errorf("create credit_usage failed! err=%v\n", err)
		_ = tx.Rollback()
	}
	_ = tx.Commit()

	return &types.BaseMsgResp{Msg: errormsg.CreateSuccess}, nil
}
