<?php


namespace App\Services\Api;


use App\Http\Requests\FeedsRequest;
use App\Models\Course;
use App\Models\Feed;
use App\Models\FeedComment;
use App\Models\FeedForward;
use App\Models\FeedLike;
use App\Models\FeedReport;
use App\Models\Game;
use App\Models\GameUser;
use App\Models\UserFollow;
use App\Models\UserReport;
use App\Services\ToolServer;
use Illuminate\Http\Request;
use PHPUnit\Util\Exception;
use Illuminate\Support\Facades\DB;

class FeedsService
{

    //动态列表
    public function getList(Request $request)
    {
        $user = auth('api')->user();
        $type = $request->input('type', 1); // 1全部  2关注  3热门
        $page = $request->input('page', 1);
        $teamId = $request->input('team_id', 0);
        $userId = $request->input('user_id', 0);

        //注销或被删除的用户 User::query() 不生效 , 需 DB::table('users')
        $disableUserId = DB::table('users')->whereNotNull('deleted_at')->pluck('id');
        $disableUserId = $disableUserId->isNotEmpty() ? $disableUserId->toArray() : [];

        $feeds = Feed::query()
            ->with('user:id,name,avatar,tencent_im_user_id,is_auth')
            ->where('team_id', $teamId)
            ->whereNotIn('user_id', $disableUserId)
            ->whereNull('deleted_at');

        $desc = 'id';
        if (!empty($type) && $type > 1) {
            $followIds = UserFollow::query()->where(['user_id' => $user->id, 'status' => 1])->pluck('target_id');
            $followIds = $followIds->isNotEmpty() ? $followIds->toArray() : [];
            if ($type == 2) {
                $feeds = $feeds->whereIn('user_id', $followIds);
            } elseif ($type == 3) { //热门, 只有未关注的，不显示已关注的人发的
                $desc = 'like_num';
                $feeds = $feeds->whereNotIn('user_id', $followIds);
            }
        }
        if (!empty($userId)) {
            $feeds->where('user_id', $userId);
        }
        $limit  = 10;
        $offset = ($page - 1) * $limit;
        $feeds  = $feeds->orderByDesc($desc)->limit($limit)->offset($offset)->get();
        if ($feeds->isEmpty()) {
            return $data = [
                'stop' => 1,
                'data' => [],
            ];
        }
        $feeds = $feeds->toArray();
        foreach ($feeds as &$v) {
            $v['have_user_course'] = UserService::haveUserCourse($v['user_id']);
            //查询评论数量
            $v['commemt_num'] = FeedComment::query()->where(['feed_id' => $v['id'], 'pid' => 0])->count();
            $v['file_url'] = json_decode($v['file_url'], true);
            $v['time'] = ToolServer::uc_time_ago(strtotime($v['created_at']));
            if ($user) {
                $v['is_like'] = self::isLike($v['id']);
                $v['is_follow'] = self::isFollow($v['user_id']);
            } else {
                $v['is_like'] = 0;
                $v['is_follow'] = 0;
            }
            //查询转发的原动态
            if ($v['forward_id'] > 0) {
                $v['forward_feed'] = $this->getDetail($v['forward_id'], 2);
            }
            //查询记分卡
            $v['game_score'] = null;
            if ($v['game_per_id'] > 0) {
                $scoreCard = self::queryScoreCard($v['game_per_id']);
                $v['game_info'] = $scoreCard['game_info'];
                $v['game_score'] = $scoreCard['game_score'];
            }
        }
        //修改消息状态为已读
        if (!empty($user)) {
            MessageService::changeStatus($user->id, [9]);
        }
        return $data = [
            'stop' => 0,
            'data' => $feeds,
        ];;
    }

    //用户动态列表
    public function userFeeds($user_id, $team_id = 0)
    {
        $user = auth('api')->user();
        $feeds = Feed::query()
            ->with(["user:id,name,avatar,tencent_im_user_id,is_auth"])
            ->where('user_id', $user_id)
            ->where('team_id', $team_id)
            ->whereNull('deleted_at')
            ->orderByDesc('id')
            ->paginate(request('perPage', 20));
        $feeds = $feeds->toArray();
        foreach ($feeds['data'] as &$v) {
            $v['have_user_course'] = UserService::haveUserCourse($v['user_id']);
            $v['file_url'] = json_decode($v['file_url'], true);
            $v['time'] = ToolServer::uc_time_ago(strtotime($v['created_at']));
            if ($user) {
                $v['is_like'] = self::isLike($v['id']);
                $v['is_follow'] = self::isFollow($v['user_id']);
            } else {
                $v['is_like'] = 0;
                $v['is_follow'] = 0;
            }
            //查询评论数量
            $v['commemt_num'] = FeedComment::query()->where(['feed_id' => $v['id'], 'pid' => 0])->count();
            //查询转发的原动态
            if ($v['forward_id'] > 0) {
                $v['forward_feed'] = $this->getDetail($v['forward_id'], 2);
            }
            //查询记分卡
            $v['game_score'] = null;
            if ($v['game_per_id'] > 0) {
                $scoreCard = self::queryScoreCard($v['game_per_id']);
                $v['game_info'] = $scoreCard['game_info'];
                $v['game_score'] = $scoreCard['game_score'];
            }
        }
        return $feeds;
    }

    //是否点赞
    public static function isLike($feedId)
    {
        $user = auth('api')->user();
        if (empty($user)) {
            return 0;
        }
        $info = FeedLike::query()->where([
            'user_id' => $user->id,
            'feed_id' => $feedId,
            'status' => 1,
        ])->first();

        return $info ? 1 : 0;
    }

    //是否关注
    public static function isFollow($userId)
    {
        $user = auth('api')->user();
        $info = UserFollow::query()->where([
            'user_id' => $user->id,
            'target_id' => $userId,
            'status' => 1
        ])->first();

        return $info ? 1 : 0;
    }

    //查询积分卡
    public static function queryScoreCard($game_user_id)
    {
        $gameId = GameUser::where('id', $game_user_id)->value('game_id');
        $gameInfo = Game::query()->where('id', $gameId)->whereNull('deleted_at')->first();
        if($gameInfo){
            $gameInfo = $gameInfo->toArray();
            $gameInfo['course_img'] = Course::find($gameInfo['course_id'])->img;
        }else{
            $gameInfo = null;
        }
        return $scoreCard = [
            'game_info' => $gameInfo,
            'game_score' => GameService::getGameUserScore($game_user_id)
        ];
    }

    //动态详情
    public function getDetail($feed_id, $type = 1)
    {

        if (empty($feed_id)) {
            throw new Exception(trans('api.PARAMS_ERROR'));
        }
        $feed = Feed::query()
            ->with(['user:id,name,avatar,tencent_im_user_id,is_auth'])
            ->where(['id' => $feed_id])
            ->whereNull('deleted_at')
            ->first();
        if (!$feed) {
            throw new Exception(trans('api.FEED_NOT_EXIST'));
        }

        //查询评论数量
        $feed['commemt_num'] = FeedComment::query()->where(['feed_id' => $feed['id'], 'pid' => 0])->count();

        $feed['file_url'] = json_decode($feed['file_url'], true);
        $user = auth('api')->user();
        if ($user) {
            //是否点赞
            $feed['is_like'] = FeedLike::query()->where([
                'user_id' => $user->id,
                'status' => 1,
                'feed_id' => $feed['id']
            ])->first() ? 1 : 0;
            //是否关注
            $feed['is_follow'] = UserFollow::query()->where([
                'user_id' => $user->id,
                'target_id' => $feed['user_id'],
                'status' => 1
            ])->first() ? 1 : 0;
        }

        //点赞列表
        $feed['like_list'] = $this->getFeedLikeList($feed['id']);
        //转发列表
        $feed['forward_list'] = $this->getFeedForwardList($feed['id']);

        if ($feed['forward_id'] > 0 && $type == 1) {
            $feed['forward_feed'] = $this->getDetail($feed['forward_id']);
        }

        //查询记分卡
        if ($feed['game_per_id'] > 0) {
            $game_id = GameUser::query()->where(['id' => $feed['game_per_id']])->value('game_id');
            $feed['game_info'] = Game::query()->where('id', $game_id)->first()->toArray() ?: null;
            $game_service = new GameService();
            $feed['game_score'] = $game_service->getGameUserScore($feed['game_per_id']);
        } else {
            $feed['game_score'] = null;
        }

        //先查询直接评论
        $comment = FeedComment::query()
            ->with(['user:id,name,avatar,tencent_im_user_id,is_auth', 'to_user:id,name,avatar,tencent_im_user_id,is_auth'])
            ->where(['feed_id' => $feed['id'], 'pid' => 0])
            ->orderByDesc('id')
            ->get()
            ->toArray();
        //根据评论查询回复内容
        $comment_arr = array();
        if (count($comment) > 0) {
            foreach ($comment as $k => $v) {
                $comment[$k]['user']['have_user_course'] = UserService::haveUserCourse($v['user']['id']);
                $comment[$k]['to_user']['have_user_course'] = UserService::haveUserCourse($v['to_user']['id']);
                $comment[$k]['son'] = $this->get_son_comment($feed['id'], $v['id'], $comment_arr);
            }
        }

        $feed['comment_list'] = $comment;

        return $feed;
    }

    //获取点赞列表
    public function getFeedLikeList($feed_id)
    {
        $list = FeedLike::query()
            ->leftJoin('users as u', 'feed_like.user_id', '=', 'u.id')
            ->where('feed_like.feed_id', $feed_id)
            ->where('feed_like.status', 1)
            ->select(['u.id', 'u.avatar', 'u.name', 'u.is_auth'])
            ->get();

        if ($list->isEmpty()) {
            return [];
        }
        foreach ($list as $key => &$val) {
            $val['have_user_course'] = UserService::haveUserCourse($val['id']);
        }

        return $list;
    }

    //获取评论列表
    public function getFeedForwardList($feed_id)
    {
        $list = FeedForward::query()
            ->leftJoin('users as u', 'feed_forward.user_id', '=', 'u.id')
            ->where('feed_forward.feed_id', $feed_id)
            ->select(['u.id', 'u.avatar', 'u.name', 'u.is_auth'])
            ->get();

        if ($list->isEmpty()) {
            return [];
        }
        foreach ($list as $key => &$val) {
            $val['have_user_course'] = UserService::haveUserCourse($val['id']);
        }

        return $list;
    }

    //查询子评论
    public function get_son_comment($feed_id, $pid, $arr)
    {
        $comment = FeedComment::query()
            ->with(['user:id,name,avatar,tencent_im_user_id,is_auth', 'to_user:id,name,avatar,tencent_im_user_id,is_auth'])
            ->where(['feed_id' => $feed_id, 'pid' => $pid])
            ->get()
            ->toArray();

        $arr = array_merge($arr, $comment);
        if (!empty($comment) && is_array($comment)) {
            foreach ($comment as $k => $v) {
                $v['user']['have_user_course'] = UserService::haveUserCourse($v['user']['id']);
                $comment[$k] = $v;
                if (FeedComment::query()->where(['feed_id' => $feed_id, 'pid' => $v['id']])->count() > 0) {
                    $arr = $this->get_son_comment($feed_id, $v['id'], $arr);
                }
            }
        }
        return $arr;
    }

    //发布动态
    public function release(FeedsRequest $feedsRequest)
    {
        $user = auth('api')->user();
        $feed = array();
        $feed['user_id'] = $user->id;
        $feed['content'] = $feedsRequest->post('content') ?: '';
        $feed['file_url'] = !empty($feedsRequest->post('file_url')) ? json_encode($feedsRequest->post('file_url')) : '';
        $feed['address_info'] = !empty($feedsRequest->post('address_info')) ? $feedsRequest->post('address_info') : '';
        $feed['match_title'] = $feedsRequest->post('match_title');

        $game_id = $feedsRequest->post('game_per_id');
        if (!empty($game_id)) {
            $game_user = GameUser::query()->where(['game_id' => $game_id, 'user_id' => $user->id])->first();
            $feed['game_per_id'] = $game_user->id;
        }

        $feed['team_id'] = $feedsRequest->post('team_id', 0);
        $feed['score_card_bg'] = $feedsRequest->post('score_card_bg') ?: asset('static/img/df_score_card_bg.png');
        if (Feed::query()->create($feed)) {
            //给关注我的用户极光推送
            $myFansIds = $this->getMyFans();
            if (!empty($myFansIds)) {
                //给用户添加消息记录
                $notice = NoticeService::getInstance();;
                foreach ($myFansIds as $userId) {
                    $notice->send_msg($userId, '', 9, $user->id, 'api.PUBLISH_FEED_NEWS', 0);
                }
            }
            return true;
        } else {
            throw new Exception(trans('api.SAVE_ERROR'));
        }
    }

    //关注我的
    public function getMyFans()
    {
        $user = auth('api')->user();

        $userIds = (new UserFollow())->setTable('uf')->from('user_follows as uf')
            ->join('users as u', 'u.id', '=', 'uf.user_id')
            ->where('uf.target_id', $user->id)
            ->where('u.status', 1)
            ->where('uf.status', 1)//0取消关注，1关注
            ->pluck('uf.user_id')
            ->toArray();

        if (!empty($userIds)) {
            $userIds = array_unique($userIds);
        } else {
            $userIds = [];
        }

        return $userIds;
    }

    //点赞  如果已经点赞 则取消点赞
    public function like(Request $request)
    {
        $user = auth('api')->user();
        $feed_id = $request->post('feed_id');

        if (empty($feed_id)) {
            throw new Exception(trans('api.PARAMS_ERROR'));
        }
        $feed = Feed::query()->where(['id' => $feed_id])->whereNull('deleted_at')->first();
        if (!$feed) {
            throw new Exception(trans('api.FEED_NOT_EXIST'));
        }

        if ($feed_like = FeedLike::query()->where(['user_id' => $user->id, 'feed_id' => $feed_id])->first()) {  //已点赞
            if ($feed_like->status == 1) {
                //已点赞  取消点赞
                Feed::query()->where('id', $feed_id)->decrement('like_num', 1);
                $feed_like->status = 2;
                $feed_like->save();
                $like = 0;
            } else {
                Feed::query()->where('id', $feed_id)->increment('like_num', 1);
                $feed_like->status = 1;
                $feed_like->created_at = date('Y-m-d H:i:s');
                $feed_like->save();
                $like = 1;
            }
        } else {
            //点赞
            Feed::query()->where('id', $feed_id)->increment('like_num', 1);
            $feed_like_id = FeedLike::query()->insertGetId([
                'user_id' => $user->id,
                'feed_id' => $feed_id,
                'status' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            $like = 1;
            //给用户添加消息记录
            if ($feed->user_id != $user->id) { //自己给自己点赞不发通知
                $notice = NoticeService::getInstance();;
                $notice->send_msg($feed->user_id, $feed_like_id, 2, $user->id, 'api.PRAISED_YOUR_FEEDS', 0);
            }
        }
        return $like;
    }

    //删除动态
    public function del(Request $request)
    {
        $feed_id = $request->post('feed_id');
        $user = auth('api')->user();
        if (empty($feed_id)) {
            throw new Exception(trans('api.PARAMS_ERROR'));
        }
        $feed = Feed::query()->where(['id' => $feed_id, 'user_id' => $user->id])->whereNull('deleted_at')->first();
        if (!$feed) {
            throw new Exception(trans('api.FEED_NOT_EXIST'));
        }
        $feed->deleted_at = date('Y-m-d H:i:s');
        $feed->save();
        return true;
    }

    //动态评论
    public function comment(Request $request)
    {
        $user = auth('api')->user();
        $feed_id = $request->post('feed_id');
        $content = $request->post('content');
        $pid = $request->post('pid');
        if (empty($content)) {
            throw new Exception(trans('api.CONTENT_NOT_NULL'));
        }

        if (empty($feed_id)) {
            throw new Exception(trans('api.PARAMS_ERROR'));
        }
        $feed = Feed::query()->where(['id' => $feed_id])->whereNull('deleted_at')->first();
        if (!$feed) {
            throw new Exception(trans('api.FEED_NOT_EXIST'));
        }

        if ($pid > 0) {
            $comment = FeedComment::query()->where(['id' => $pid])->first();
            $to_uid = $comment->user_id;
        } else {
            $to_uid = $feed->user_id;
        }

        $comment_id = FeedComment::query()->insertGetId([
            'feed_id' => $feed_id,
            'user_id' => $user->id,
            'content' => $content,
            'pid' => $pid,
            'to_uid' => $to_uid,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        //如果自己给自己评论  则不发消息
        if ($to_uid != $user->id) {
            $notice = NoticeService::getInstance();;
            $notice->send_msg($to_uid, $comment_id, 3, $user->id, 'api.COMMENTED_ON_YOUR_FEEDS', 0);
        }
        return true;
    }

    //举报动态
    public function report(Request $request)
    {
        $feed_id = $request->post('feed_id');
        $content = $request->post('content');
        $user = auth('api')->user();
        if (empty($feed_id)) {
            throw new Exception(trans('api.PARAMS_ERROR'));
        }
        $feed = Feed::query()->where(['id' => $feed_id])->whereNull('deleted_at')->first();
        if (!$feed) {
            throw new Exception(trans('api.FEED_NOT_EXIST'));
        }
        $report = new UserReport();
        $report->user_id = $user->id;
        $report->type = 1;
        $report->to_id = $feed_id;
        $report->content = $content;
        $report->save();
        return true;
    }

}
