<?php

namespace App\Http\Controllers\V1;

use App\Models\Episode;
use App\Models\EpisodesCategory;
use App\Models\EpisodesList;
use App\Models\UserEpisodesRecord;
use App\Models\UserWatchRecord;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;

class EpisodeController extends Controller
{
    private $number;

    public function __construct()
    {
        $this->number = env('HOME_RECOMMEND_NUMBER', 6);
    }

    /**
     * 推荐.
     */
    public function recommend()
    {
        $history = UserWatchRecord::filterUser()
            ->withCount(['episode'])
            ->whereHas('episode', function (Builder $query) {
                $query->where('is_opend', 1);
            })
            ->inRandomOrder()
            // ->where('created_at','>=', Carbon::now()->subDays(7)->toDateTime())
            ->first();
        $lists = [];

        $ids = [];
        if ($history) {
            $ids[]                         = $history->episode->id;
            $history->episode->recent      = true;
            $history->episode->status_text = $history->episode->status;
            $history->episode->total       = $history->episode->lists->count();
            unset($history->episode->lists);
            $lists[] = $history->episode;
        }

        $limit = $this->number - count($lists);
        // 推荐
        $episodes = Episode::filterPlatform()->withCount(['lists'])
            ->where('is_opend', 1)
            ->when($history, function ($query) use ($history) {
                /* @var Builder  $query */
                return $query->where('category_id', $history->episode->category_id)
                    ->where('id', '<>', $history->episode->id);
            })
            ->limit($limit)
            ->get();

        /* @var Episode $episode */
        foreach ($episodes as $episode) {
            $ids[]                = $episode->id;
            $episode->status_text = $episode->status;
            $episode->total       = $episode->lists_count;
            $episode->guess       = true;
            $lists[]              = $episode;
        }
        // 推荐的不够两个 需要补充
        $limit = $this->number - count($lists);
        if ($limit) {
            $supplement = Episode::filterPlatform()->withCount(['lists'])
                ->where('is_opend', 1)
                ->when($ids, function ($query) use ($ids) {
                    /* @var Builder  $query */
                    return $query->whereNotIn('id', $ids);
                })
                ->limit($limit)
                ->get();

            /* @var Episode $episode */
            foreach ($supplement as $episode) {
                $episode->status_text = $episode->status;
                $episode->total       = $episode->lists_count;
                $episode->guess       = true;
                $lists[]              = $episode;
            }
        }

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

    /**
     * 最新.
     */
    public function news()
    {
        $limit    = request()->input('limit', $this->number);
        $page     = request()->input('page', 1);
        $offset   = ($page - 1) * $limit;
        $episodes = Episode::filterPlatform()->withCount(['lists'])
            ->where('is_opend', 1)
            // ->inRandomOrder()
            ->orderByDesc('created_at')
            ->limit($limit)
            ->offset($offset)
            ->get();

        $lists = Episode::complete($episodes);

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

    /**
     * 今日推荐.
     */
    public function todayRecommend()
    {
        $limit    = request()->input('limit', $this->number);
        $page     = request()->input('page', 1);
        $offset   = ($page - 1) * $limit;
        $episodes = Episode::filterPlatform()->withCount(['lists'])
            ->where('is_opend', 1)
            // ->inRandomOrder()
            ->orderBy('sort')
            ->limit($limit)
            ->offset($offset)
            ->get();

        $lists = Episode::complete($episodes);

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

    /**
     * 排行.
     */
    public function rank()
    {
        $limit    = request()->input('limit', 12);
        $page     = request()->input('page', 1);
        $offset   = ($page - 1) * $limit;
        $episodes = Episode::filterPlatform()->withCount(['userEpisodesRecords', 'lists'])
            ->where('is_opend', 1)
            ->orderByDesc('user_episodes_records_count')
            ->limit($limit)
            ->offset($offset)
            ->get();

        $lists = [];
        $rank  = (($page - 1) * $limit) + 1;
        /* @var Episode $episode */
        foreach ($episodes as $episode) {
            $episode->status_text = $episode->status;
            $episode->total       = $episode->lists_count;
            $episode->rank        = $rank++;
            $lists[]              = $episode;
        }

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

    public function list()
    {
        $limit    = request()->input('limit', $this->number);
        $page     = request()->input('page', 1);
        $cateId   = request()->input('cateId', 0);
        $offset   = ($page - 1) * $limit;
        $episodes = Episode::filterPlatform()->withCount(['lists'])
            ->when($cateId, function ($query, $cateId) {
                /* @var Builder  $query */
                return $query->where('category_id', $cateId);
            })
            ->where('is_opend', 1)
            ->limit($limit)
            ->offset($offset)
            ->get();

        $lists = [];
        /* @var Episode $episode */
        foreach ($episodes as $episode) {
            $episode->status_text = $episode->status;
            $episode->total       = $episode->lists_count;
            $lists[]              = $episode;
        }

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

    // 追剧
    public function trace()
    {
        $category = EpisodesCategory::with(['child:id,pid'])
            ->where('level', 1)
            ->orderBy('sort')
            ->get(['id', 'name']);

        $lists = [];
        /* @var EpisodesCategory $item */
        foreach ($category as $item) {
            $childIds   = $item->child->pluck('id');
            $childIds[] = $item->id;
            $episodes   = Episode::filterPlatform()->whereIn('category_id', $childIds)
                ->where('is_opend', 1)
                ->limit(3)
                ->get();

            /* @var Episode $episode */
            foreach ($episodes as $episode) {
                $count                = EpisodesList::where('episodes_id', $episode->id)->count();
                $episode->total       = $count;
                $episode->status_text = $episode->status;
            }
            $item->episodes = $episodes;
            unset($item->child);
            if ($episodes->count()) {
                $lists[] = $item;
            }
        }

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

    /**
     * 最新.
     */
    public function search()
    {
        $keywords = request()->input('keywords', '');
        $limit    = request()->input('limit', 3);
        $page     = request()->input('page', 1);
        $offset   = ($page - 1) * $limit;
        $episodes = Episode::filterPlatform()->withCount(['lists'])
            ->where('is_opend', 1)
            ->when($keywords, function ($query, $keywords) {
                /* @var Builder  $query */
                return $query->where('name', 'like', "%$keywords%");
            })
            ->inRandomOrder()
            ->orderByDesc('id')
            ->limit($limit)
            ->offset($offset)
            ->get();

        $lists = Episode::complete($episodes);

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

    public function vipFree()
    {
        $limit    = request()->input('limit', 3);
        $page     = request()->input('page', 1);
        $offset   = ($page - 1) * $limit;
        $episodes = Episode::filterPlatform()->withCount(['lists'])
            ->where('is_opend', 1)
            ->where('is_vip_watch', 1)
            ->inRandomOrder()
            ->orderByDesc('id')
            ->limit($limit)
            ->offset($offset)
            ->get();

        $lists = Episode::complete($episodes);

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

    // 详情
    public function detail($id)
    {
        $episodes = Episode::filterPlatform()->withCount(['userWatchRecord', 'userCollect', 'userFavorite', 'lists'])
            ->with([
                'category:id,name',
                'lists' => function ($query) {
                    $query->select([
                        'id', 'episodes_id', 'sort', 'url', 'is_free', 'origin_price', 'sale_price',
                    ])
                        ->orderBy('sort');
                },
            ])
            ->where('is_opend', 1)
            ->where('id', $id)
            ->first();
        $episodes->user_watch_record_count += $episodes->play_num;
        $episodes->user_favorite_count     += $episodes->favorite_num;
        $episodes->user_collect_count      += $episodes->collect_num;
        $episodes->share_count             += $episodes->virtual_share;

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

    public function listBuyNum($listId)
    {
        $count = UserEpisodesRecord::where('list_id', $listId)->count();
        $info  = EpisodesList::find($listId);
        $res   = Episode::find($info->episodes_id);
        $count += $res->buy_num;

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

    // 分享
    public function shared($id)
    {
        $res = Episode::find($id);
        if (!$res) {
            return $this->success();
        }
        $res->share_count = $res->share_count + 1;
        $res->save();

        return $this->success();
    }
}
