<?php

namespace App\Http\Services\V1;

use App\Generated\V1\Messages\Homepage\OpenidFeedMessage;
use App\Generated\V1\Messages\Homepage\FeedMessage;
use App\Generated\V1\Messages\Homepage\FeedScoreMessage;
use App\Generated\Exceptions\DailyFeedLimitException;
use App\Generated\V1\Messages\Homepage\ActivityTimeTableMessage;
use App\Http\Controllers\Core\Auth;
use App\Jobs\FeedCleanPartnerJob;
use App\Models\ArticleLookModel;
use App\Models\ArticleModel;
use App\Models\Fpdx\ActivityModel;
use App\Models\User\OpenidUserModel;
use App\Models\User\UserModel;
use App\Models\Fpdx\PairModel;
use App\Services\Home\FeedService;

class HomepageService
{
    protected $feedService;

    public function __construct(FeedService $feedService)
    {
        $this->feedService = $feedService;
    }

    public function activityTimeTable(ActivityTimeTableMessage $message)
    {
        $uid = Auth::auth();
        if (PairModel::where(['uid' => $uid, 'activity_type' => 'qbj', 'stage_id' => 78])->first()) {
            $qbj_pair = ActivityModel::where('qbj_stage_id', '>', 0)->OrderBy(
                'qbj_stage_id',
                'asc'
            )->value('signend_time');
        } else {
            $qbj_pair = ActivityModel::where('qbj_stage_id', '>', 0)->where(
                'signend_time',
                '>',
                time()
            )->OrderBy('qbj_stage_id', 'asc')->value('signend_time');
        }
        $wx_game = \App\Models\Gteam\ActivityModel::where('match_end_at', '>', time())->where(
            'type',
            'wz_wx'
        )->OrderBy('id', 'asc')->value('match_end_at');
        $cj_game = \App\Models\Gteam\ActivityModel::where('match_end_at', '>', time())->where(
            'type',
            'cj_wx'
        )->OrderBy('id', 'asc')->value('match_end_at');
        $goodnight = \App\Models\Goodnight\ActivityModel::where('closed_at', '>', time())->OrderBy(
            'id',
            'asc'
        )->value('closed_at');
        $looked_at = ArticleLookModel::where('uid', $uid)->value('looked_at') ?: 0;
        $unlook_article_count = ArticleModel::whereBetween("showed_at", [$looked_at, time()])->count();


        $pair = [
            'sign_end_time' => ActivityModel::where('signend_time', '>', time())->OrderBy(
                'stage_id',
                'asc'
            )->value('signend_time'),
            'is_enter' => PairModel::where('uid', $uid)->value('id') ? true : false,
        ];


        $message->setResponse([
            'pair' => $pair,
            'qbj_pair' => $qbj_pair,
            'bqj_pair' => $qbj_pair,
            'wx_game' => $wx_game,
            'cj_game' => $cj_game,
            'goodnight' => $goodnight,
            'unlook_article_count' => $unlook_article_count
        ]);
    }

    public function openidFeed(OpenidFeedMessage $message)
    {
        $openid = $message->getOpenid();
        $take = $message->getTake() ?? 5;

        /** @var OpenidUserModel $openuser */
        $openuser = OpenidUserModel::where('openid', $openid)->firstOrFail();

        // 滑动的性别
        if (in_array($openuser->feed_sex, [1, 2])) {
            $sxo = $openuser->feed_sex;
        } else {
            $sxo = 2;
        }

        $data = $openuser->toArray();
        $data['uid'] = $openuser->openid;
        $data['partner_id'] = 0;
        $data['feed_level'] = 'A';
        $data['only_last'] = 0;

        $res = $this->feedService->feed($data, $sxo, $take);

        $message->setResponse($res);
    }

    /**
     * @param  FeedMessage  $message
     * @throws DailyFeedLimitException
     * @throws \App\Exceptions\AlertException
     */
    public function feed(FeedMessage $message)
    {
        $take = $message->getTake() ?? 5;
        $uid = Auth::auth();
        // 流量控制
        if ("production" == config('app.env') && !$this->feedService->limit($uid)) {
            throw new DailyFeedLimitException('每日限流200张');
        }

        /** @var UserModel $user */
        $user = UserModel::findOrFail($uid);

        // 滑动的性别
        if (in_array($user->feed_sex, [1, 2])) {
            $sxo = $user->feed_sex;
        } else {
            $sxo = 2;
        }

        $userArr = $user->toArray();

        // 定义用户分级
        if ($user->feed_cnt < 30) {
            $userArr['feed_level'] = 'A';
        } elseif ($user->feed_cnt >= 500) {
            $userArr['feed_level'] = 'E';
            if (1 == $user->sex) {
                if (floatval($user->feed_like / $user->feed_cnt) < 0.1) {
                    $userArr['feed_level'] = 'E';
                } elseif (floatval($user->feed_like / $user->feed_cnt) > 0.8) {
                    $userArr['feed_level'] = 'G';
                } else {
                    $userArr['feed_level'] = 'F';
                }
            } else {
                if (floatval($user->feed_like / $user->feed_cnt) < 0.05) {
                    $userArr['feed_level'] = 'E';
                } elseif (floatval($user->feed_like / $user->feed_cnt) > 0.3) {
                    $userArr['feed_level'] = 'G';
                } else {
                    $userArr['feed_level'] = 'F';
                }
            }
        } else {
            if (1 == $user->sex) {
                if (floatval($user->feed_like / $user->feed_cnt) < 0.1) {
                    $userArr['feed_level'] = 'B';
                } elseif (floatval($user->feed_like / $user->feed_cnt) > 0.8) {
                    $userArr['feed_level'] = 'D';
                } else {
                    $userArr['feed_level'] = 'C';
                }
            } else {
                if (floatval($user->feed_like / $user->feed_cnt) < 0.05) {
                    $userArr['feed_level'] = 'B';
                } elseif (floatval($user->feed_like / $user->feed_cnt) > 0.3) {
                    $userArr['feed_level'] = 'D';
                } else {
                    $userArr['feed_level'] = 'C';
                }
            }
        }

        $res = $this->feedService->feed($userArr, $sxo, $take);


        // 清理我看过的缓存
        1 == rand(0, 15) && FeedCleanPartnerJob::dispatch($uid);

        $message->setResponse($res);
    }

    public function feedScore(FeedScoreMessage $message)
    {
        $uid = Auth::auth();
        $partnerId = $message->getPartnerId();
        $fs = new FeedService();
        list($location, $dis, $score, $info) = $fs->getScoreUid2Partner($uid, $partnerId);
        $message->setResponse([
            'location' => [
                'location' => $location,
                'dis' => $dis
            ],
            'score' => $score,
            'info' => $info
        ]);
    }
}
