<?php

namespace App\Http\Controllers\Home;

use App\Exceptions\AlertException;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Core\Auth;
use App\Http\Resources\Home\ArticleCollection;
use App\Jobs\FeedCleanPartnerJob;
use App\Jobs\FeedMockPushJob;
use App\Jobs\HomeHdLogJob;
use App\Models\ArticleLookModel;
use App\Models\ArticleModel;
use App\Models\Fpdx\ActivityModel;
use App\Models\PraiseModel;
use App\Models\User\UserModel;
use App\Models\Fpdx\PairModel;
use App\Models\Gnight\UserModel as GnightUserModel;
use App\Models\Goodnight\UserModel as GoodnightUserModel;
use App\Models\Log\FeedLogModel;
use App\Services\Home\FeedService;
use Exception;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Symfony\Component\HttpFoundation\Response;
use Tymon\JWTAuth\Exceptions\JWTException;

/**
 * 信息流API
 * Class HomeController
 * @package App\Http\Controllers\Home
 * @deprecated
 */
class HomeController extends Controller
{
    /**
     * 首页feed
     * @param  FeedService  $fs
     * @return array
     * @throws AlertException
     * @deprecated Homepage/Feed
     */
    public function feed(FeedService $fs)
    {
        $uid = Auth::auth();

        // 流量控制
        if (!$fs->limit($uid)) {
            throw new AlertException("每日限流200张", 202);
        }

        /** @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';
        } 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 = $fs->feed($userArr, $sxo);

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $res
        );
    }

    /**
     * 获取匹配分
     * @param  int  $partner_id
     * @return array
     * @throws JWTException
     */
    public function score(int $partner_id)
    {
        $uid = Auth::auth();

        $fs = new FeedService();

        list($location, $dis, $score, $info) = $fs->getScoreUid2Partner($uid, $partner_id);

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'location' => [
                    'location' => $location,
                    'dis' => $dis
                ],
                'score' => $score,
                'info' => $info
            ],
        );
    }

    /**
     * 提醒TA补全信息
     * @param  Request  $request
     * @return array
     * @throws JWTException
     */
    public function remindType4(Request $request)
    {
        $this->validate($request, [
            'remind_uid' => 'required'
        ]);
        $remind_uid = $request->get("remind_uid");
        $type = $request->get('type', 1) ?: 1;
        /** @var integer $uid */
        $uid = Auth::auth();
        $fs = new FeedService();
        $fs->remindType4($uid, $remind_uid, $type);
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 获取点赞队列存量
     */
    public function getHasThumb()
    {
        $uid = Auth::auth();

        $fs = new FeedService();
        $cnt = $fs->getHasThumb($uid);

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $cnt
        );
    }

    /**
     * 游乐场模块人数
     */
    public function modelCnt()
    {
        $data = Redis::get('app:model:cnt');
        if (empty($data)) {
            $pair = PairModel::count(DB::raw('DISTINCT(`uid`)')) * 5;
            $goodnight = GoodnightUserModel::count() * 5;
            $voice = GnightUserModel::count() * 5;
            $data = [
                'pair' => $pair,
                'voice' => $voice,
                'goodnight' => $goodnight
            ];
        } else {
            $data = json_decode($data, true);
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $data
        );
    }

    /**
     * 记录每日滑动数量
     * @param  Request  $request
     * @param  int  $partner_id
     * @return array
     */
    public function hdCnt(Request $request, int $partner_id)
    {
        try {
            $uid = Auth::auth();
        } catch (JWTException $exception) {
            $uid = $request['uid'];
        }
        Redis::hincrby("session_msy_{$uid}", "hd_cnt", 1);
        if ($partner_id > 0) {
            $post = $request->post();
            if (!empty($post)) {
                $detail = $post['type_detail'];
                $data = [
                    'created_at' => time(),
                    'created_date' => date('Y-m-d'),
                    'uid' => $uid,
                    'partner_id' => $partner_id,
                    'type' => $post['type'],
                    'attach' => isset($post['attach']) ? $post['attach'] : null,
                    'photo_num' => 0,
                    'voice' => 0,
                    'remind' => 0,
                    'retention_time' => is_null($post['retention_time']) ? 0 : $post['retention_time'],
                    'like' => $post['like'],
                    'each_like' => isset($post['each_like']) ? $post['each_like'] : 0,
                    'page' => isset($post['page']) ? $post['page'] : "",
                    'app' => Config::get("platform", 'wx')
                ];
                if (in_array($data['type'], [1, 2])) {
                    $data['photo_num'] = $detail['photo_num'];
                    $data['voice'] = $detail['voice'];
                } else {
                    if (!is_array($detail)) {
                        $detail = json_decode($detail, true);
                    }
                    $data['remind'] = isset($detail['remind']) ? $detail['remind'] : 0;
                }
                HomeHdLogJob::dispatch($uid, $data);
                // 递交模拟拉卡片任务
                FeedMockPushJob::dispatch($uid);
            }
        }
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 发现页
     * @return ResponseFactory|Response
     * @deprecated Homepage/ActivityTimeTable
     */
    public function activityTimetable()
    {
        try {
            $uid = Auth::auth();
        } catch (Exception $e) {
            $uid = 0;
        }
        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();


        $activity = ActivityModel::OrderBy('stage_id', 'desc')->first();
        $enroll_number = PairModel::where([
                ['stage_id', $activity->stage_id],
                ['state', '>', 100]
            ])->count() + 1;
        $pair = [
            'activity' => $activity,
            'sign_end_time' => $activity->signend_time,
            'is_enter' => PairModel::where('uid', $uid)->value('id') ? true : false,
            'enroll_number' => $enroll_number * 6,
        ];


        return response([
            "code" => 200,
            "message" => "OK",
            "data" => [
                '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
            ]
        ]);
    }

    /**
     * 文章列表
     * @param  Request  $request
     * @return ArticleCollection
     */
    public function articles(Request $request)
    {
        $articles = ArticleModel::where("showed_at", '<=', time())
            ->orderBy('showed_at', 'desc')->paginate($request->get('per_page', 10));

        // 阅读
        try {
            $uid = Auth::auth();
            ArticleLookModel::updateOrCreate(
                ['uid' => $uid],
                ['looked_at' => time()]
            );
        } catch (Exception $e) {
        }
        return new ArticleCollection($articles);
    }
}
