package credit_balance

import (
	"context"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"
	"wechat-api/ent/creditbalance"
	"wechat-api/ent/predicate"
	"wechat-api/internal/svc"
	"wechat-api/internal/types"
	"wechat-api/internal/utils/dberrorhandler"

	"github.com/suyuan32/simple-admin-common/msg/errormsg"

	"github.com/suyuan32/simple-admin-common/utils/pointy"
	"github.com/zeromicro/go-zero/core/logx"
)

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

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

func (l *GetCreditBalanceListLogic) GetCreditBalanceList(req *types.CreditBalanceListReq) (*types.CreditBalanceListResp, error) {
	var predicates []predicate.CreditBalance
	if req.UserId != nil && *req.UserId != "" {
		predicates = append(predicates, creditbalance.UserID(*req.UserId))
	}
	if req.OrganizationId != nil && *req.OrganizationId > 0 {
		predicates = append(predicates, creditbalance.OrganizationID(*req.OrganizationId))
	}
	data, err := l.svcCtx.DB.CreditBalance.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

	if err != nil {
		return nil, dberrorhandler.DefaultEntError(l.Logger, err, req)
	}

	resp := &types.CreditBalanceListResp{}
	resp.Msg = errormsg.Success
	resp.Data.Total = data.PageDetails.Total

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

		resp.Data.Data = append(resp.Data.Data,
			types.CreditBalanceInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				UserId:           &v.UserID,
				Balance:          &v.Balance,
				OrganizationId:   &v.OrganizationID,
				OrganizationName: departmentInfo.Name,
			})
	}

	return resp, nil
}
