package appservice

import (
	"go-admin/app/admin/models"
	"go-admin/app/admin/service/dto"
	cDto "go-admin/common/dto"
	"time"

	"github.com/go-admin-team/go-admin-core/logger"
	"github.com/go-admin-team/go-admin-core/sdk/service"
)

type InviteLog struct {
	service.Service
}

// 分页查询
func (e *InviteLog) GetPage(req *dto.PersonnalInviteLogPageReq, list *[]dto.InviteLogResp, count *int64) error {
	var datas []models.LineUser
	var childs []models.LineUser
	pids := make([]int, 0)

	if err := e.Orm.Model(&models.LineUser{}).Where("pid = ?", req.UserId).Scopes(cDto.Paginate(req.GetPageSize(), req.GetPageIndex())).Find(&datas).Count(count).Error; err != nil {
		return err
	}

	for _, v := range datas {
		pids = append(pids, v.Id)
	}
	if err := e.Orm.Model(&models.LineUser{}).Where("pid in (?)", pids).Find(&childs).Error; err != nil {
		logger.Error("查询子邀请失败", err)
	}

	for _, v := range datas {
		item := dto.InviteLogResp{
			UserId:       v.Id,
			NickName:     v.Username,
			RegisterTime: v.CreatedAt.UnixNano() / int64(time.Millisecond),
		}

		for _, v2 := range childs {
			if v2.Pid == v.Id {
				item.Childs = append(item.Childs, dto.InviteLogResp{
					UserId:       v2.Id,
					NickName:     v2.Nickname,
					RegisterTime: v2.CreatedAt.UnixNano() / int64(time.Millisecond),
				})
			}
		}

		*list = append(*list, item)
	}

	return nil
}
