<?php

namespace Modules\User\Http\Controllers\Api\Rank;

use App\Api\Controllers\Controller;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Jason\Api\Api;
use Modules\Mall\Models\Order;
use Modules\Mall\Models\OrderItem;
use Modules\User\Models\User;
use Modules\User\Traits\RankDataTrait;

class IndexController extends Controller
{
    use RankDataTrait;

    /**
     * Notes: 总排行
     *
     * @Author: 玄尘
     * @Date: 2022/8/17 15:10
     * @param  Request  $request
     * @return JsonResponse
     */
    public function total(Request $request): JsonResponse
    {
        $dateBetween = [
            '2022-06-01 00:00:00',
            now()->toDateTimeString(),
        ];

        $vipUsers = $this->getRankDataTrait($dateBetween);
        $data     = [];
        $i        = 1;
        foreach ($vipUsers as $user) {
            $data[] = [
                'rank'     => $i,
                'avatar'   => $user->info->avatar,  //头像
                'nickname' => $user->info->nickname,
                'rate'     => '-',
                'number'   => $user->countChild,
            ];
        }
        return $this->success([
            'page_id' => 6,
            'rand'    => $data
        ]);
    }

    /**
     * Notes: 功德榜
     *
     * @Author: 玄尘
     * @Date: 2022/12/31 18:23
     */
    public function merit()
    {
        $users = $this->getAllUserJz();
        return $this->success($users);
    }

    /**
     * Notes: 推荐用户总排行
     *
     * @Author: 玄尘
     * @Date: 2022/8/17 15:11
     * @return JsonResponse
     */
    public function totalUser(): JsonResponse
    {
        $user = Api::user();

        $users = User::query()
            ->withCount('children')
            ->take(10)
            ->latest('children_count')
            ->oldest('id')
            ->get()
            ->where('children_count', '>', 0)
            ->map(function ($info) use ($user) {
                $children_count = $info->children_count;
                return [
                    'user'  => [
                        'user_id'  => $info->id,
                        'username' => substr_replace($info->username, '****', -4, 4),
                        'nickname' => $info->info->nickname_text ?? '',
                        'avatar'   => $info->info->avatar ?? '',
                    ],
                    'total' => $children_count > 0 ? $children_count : '-',
                ];
            })
            ->pad(10, [
                'user'  => [
                    'user_id'  => 0,
                    'username' => '-',
                    'nickname' => '-',
                    'avatar'   => '-',
                ],
                'total' => '-',
            ]);

        $users = $users->toArray();

        return $this->success($users);
    }

}
