package credit_usage

import (
	"context"
	"github.com/suyuan32/simple-admin-core/rpc/types/core"

	"wechat-api/ent/creditusage"
	"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 GetCreditUsageListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

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

func (l *GetCreditUsageListLogic) GetCreditUsageList(req *types.CreditUsageListReq) (*types.CreditUsageListResp, error) {
	var predicates []predicate.CreditUsage
	if req.OrganizationId != nil {
		predicates = append(predicates, creditusage.OrganizationID(*req.OrganizationId))
	}
	data, err := l.svcCtx.DB.CreditUsage.Query().Where(predicates...).Page(l.ctx, req.Page, req.PageSize)

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

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

	departmentInfo, err := l.svcCtx.CoreRpc.GetDepartmentById(l.ctx, &core.IDReq{Id: *req.OrganizationId})
	if err != nil {
		return nil, err
	}

	for _, v := range data.List {
		bUserInfo := types.UserInfo{}
		if v.UserID != "" {
			userInfo, _ := l.svcCtx.CoreRpc.GetUserById(l.ctx, &core.UUIDReq{Id: v.UserID})
			if userInfo != nil {
				bUserInfo.Id = userInfo.Id
				bUserInfo.Username = userInfo.Username
				bUserInfo.Nickname = userInfo.Nickname
				bUserInfo.Avatar = userInfo.Avatar
			}
		}
		resp.Data.Data = append(resp.Data.Data,
			types.CreditUsageInfo{
				BaseIDInfo: types.BaseIDInfo{
					Id:        &v.ID,
					CreatedAt: pointy.GetPointer(v.CreatedAt.UnixMilli()),
					UpdatedAt: pointy.GetPointer(v.UpdatedAt.UnixMilli()),
				},
				UserId:           &v.UserID,
				UserInfo:         bUserInfo,
				Number:           &v.Number,
				Status:           &v.Status,
				Ntype:            &v.Ntype,
				Table:            &v.Table,
				OrganizationId:   &v.OrganizationID,
				OrganizationName: departmentInfo.Name,
				Nid:              &v.Nid,
				Reason:           &v.Reason,
				Operator:         &v.Operator,
			})
	}

	return resp, nil
}
