package credit_balance

import (
	"context"
	"github.com/suyuan32/simple-admin-common/msg/errormsg"
	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"github.com/zeromicro/go-zero/core/logx"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
)

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

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

func (l *GetCreditBalanceByIdLogic) GetCreditBalanceById(req *types.IDReq) (*types.CreditBalanceInfoResp, error) {
	cbDao := l.svcCtx.WechatQ.CreditBalance

	query := cbDao.Where()

	if req.Id > 0 {
		query = query.Where(cbDao.ID.Eq(int64(req.Id)))
	}
	data, err := query.First()

	if err != nil {
		return nil, err
	}

	departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: uint64(data.OrganizationID)})
	if err != nil {
		return nil, err
	}

	id := uint64(data.ID)
	status := int(data.Status)
	balance, _ := data.Balance.Float64()
	organizationId := uint64(data.OrganizationID)
	organizationName := *departmentInfo.Name
	return &types.CreditBalanceInfoResp{
		BaseDataInfo: types.BaseDataInfo{
			Code: 0,
			Msg:  errormsg.Success,
		},
		Data: types.CreditBalanceInfo{
			BaseIDInfo: types.BaseIDInfo{
				Id:        &id,
				CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
				UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
			},
			Status:           &status,
			Balance:          &balance,
			OrganizationId:   &organizationId,
			OrganizationName: &organizationName,
		},
	}, nil

	//data, err := l.svcCtx.DB.CreditBalance.Get(l.ctx, req.Id)
	//if err != nil {
	//	return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	//}
	//
	//departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: data.OrganizationID})
	//if err != nil {
	//	return nil, err
	//}
	//return &types.CreditBalanceInfoResp{
	//	BaseDataInfo: types.BaseDataInfo{
	//		Code: 0,
	//		Msg:  errormsg.Success,
	//	},
	//	Data: types.CreditBalanceInfo{
	//		BaseIDInfo: types.BaseIDInfo{
	//			Id:        &data.ID,
	//			CreatedAt: pointy.GetPointer(data.CreatedAt.UnixMilli()),
	//			UpdatedAt: pointy.GetPointer(data.UpdatedAt.UnixMilli()),
	//		},
	//		Status:           &data.Status,
	//		Balance:          &data.Balance,
	//		OrganizationId:   &data.OrganizationID,
	//		OrganizationName: departmentInfo.Name,
	//	},
	//}, nil
}
