<?php

namespace Modules\User\Traits;

use Illuminate\Support\Facades\DB;
use Modules\User\Models\User;

trait RankDataTrait
{
    /**
     * 根据时间范围获取推荐VIP排行
     *
     * @param  array  $timeBetween
     * @return mixed
     */
    public function getRankDataTrait(array $timeBetween)
    {
        $vipJion = DB::table('user_identity')
            ->whereBetween('started_at', $timeBetween)
            ->where('ended_at', '>=', now())
            ->select('user_id as middle_user_Id',
                DB::raw('any_value(started_at) as started_at'),
                DB::raw('any_value(identity_id) as identity_id'))
            ->groupBy('middle_user_Id');

        $vipRelationJion = DB::table('user_relations')
            ->leftJoinSub($vipJion, 'vipJion', function ($join) {
                $join->on('user_relations.user_id', '=', 'vipJion.middle_user_Id');
            })
            ->where('identity_id', '>', 1)
            ->select('parent_id',
                DB::raw('ifnull(count(user_id),0) as countChild'),
                DB::raw('max(started_at) as lastOpenTime'))
            ->groupBy('parent_id');

        return User::query()
            ->leftJoinSub($vipRelationJion, 'vipRelationJion', function ($join) {
                $join->on('users.id', '=', 'vipRelationJion.parent_id');
            })
            ->where('countChild', '>', 0)
            ->orderBy('countChild', 'desc')
            ->orderBy('lastOpenTime', 'asc')
            ->limit(10)
            ->get();
    }

    public function getTotalUser(array $timeBetween)
    {
        $relationJion = DB::table('user_relations')
            ->whereBetween('created_at', $timeBetween)
            ->select('parent_id',
                DB::raw('ifnull(count(user_id),0) as countChild'),
                DB::raw('max(created_at) as lastRegTime')
            )
            ->groupBy('parent_id');

        return User::query()
            ->leftJoinSub($relationJion, 'relationJion', function ($join) {
                $join->on('users.id', '=', 'relationJion.parent_id');
            })
            ->where('countChild', '>', 0)
            ->orderBy('countChild', 'desc')
            ->orderBy('lastRegTime', 'asc')
            ->limit(10)
            ->get();
    }
}
