<?php


namespace App\Services\Api;


use App\Models\Game;
use App\Models\GameUser;
use App\Models\UserJoin;
use App\Services\ToolServer;
use Illuminate\Http\Request;
use App\Models\FeedComment;
use App\Models\UserMessage;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use PHPUnit\Util\Exception;

class MessageService
{
    public static function getMessageContent($type)
    {
        switch ($type) {
            case 1: //系统通知
                $content = trans('api.STSTEM_NOTICE');
                break;
            case 2: //赞了你的动态
                $content = trans('api.THUMBS_UP');
                break;
            case 3: //评论了你的动态
                $content = trans('api.COMMENT');
                break;
            case 4: //回复通知
                $content = trans('api.REPLY');
                break;
            case 5: //邀请加入球队
                $content = trans('api.INVITE_TEAM');
                break;
            case 6: //申请加入球队
                $content = trans('api.APPLY_TEAM');
                break;
            case 7: //比赛邀请通知
                $content = trans('api.INVITE_GAME');
                break;
            case 8: //比赛申请通知
                $content = trans('api.GAME_APPLY');
                break;
            default: //系统通知
                $content = trans('api.STSTEM_NOTICE');
                break;
        }

        return $content;
    }

    //获取消息首页记录
    public function getindex()
    {
        $user = auth('api')->user();

        $list = UserMessage::query()->where(['status' => 0, 'user_id' => $user->id])->select('id', 'type')->get();
        $system_num = 0; //系统通知未读数量
        $like_num = 0; //点赞未读数量
        $comment_num = 0; //评论和回复未读数量
        $my_num = 0; //我的通知未读数量
        $follow_feeds_num = 0; //我关注的用户，发布的动态未读
        $follow_me = 0; //点赞未读数量

        foreach ($list as $key => $val) {
            $type = $val['type'];
            if ($type == 1) {
                $system_num = $system_num + 1;
            } elseif ($type == 2) {
                $like_num = $like_num + 1;
            }elseif (in_array($type, [3, 4])) {
                $comment_num = $comment_num + 1;
            }elseif (in_array($type, [5, 6, 7, 8])) {
                $my_num = $my_num + 1;
            }elseif ($type == 9){
                $follow_feeds_num = $follow_feeds_num +1;
            }elseif ($type == 10){
                $follow_me = $follow_me +1;
            }else{

            }
        }

        $res = [
            'system_num' => $system_num,
            'like_num' => $like_num,
            'comment_num' => $comment_num,
            'my_num' => $my_num,
            'follow_feeds_num' => $follow_feeds_num,
            'follow_me' => $follow_me,
        ];

        return $res;
    }

    //获取我的通知列表
    public function getMyList()
    {
        $user = auth('api')->user();

        $data = UserMessage::query()
            ->where(['user_id' => $user->id])
            ->select(DB::raw('max(id) as id,type,do_user'))
            ->whereIn('type', [5, 6, 7, 8])
            ->groupBy('do_user')
            ->orderByDesc('id')
            ->paginate(request('perPage', 20));

        $data = $data->toArray();
        foreach ($data['data'] as &$v) {
            $v = UserMessage::query()->with('do_user:id,avatar,name,is_auth')->find($v['id'])->toArray();
            $v['content'] = self::getMessageContent($v['type']);
            $v['time'] = ToolServer::uc_time_ago(strtotime($v['created_at']));
            $v['no_read_num'] = UserMessage::query()
                ->where(['user_id' => $user->id, 'do_user' => $v['do_user'], 'status' => 0])
                ->whereIn('type', [5, 6, 7, 8])
                ->count();
            if(isset($v['do_user']['id'])){
                $v['do_user']['have_user_course'] =  UserService::haveUserCourse($v['do_user']['id']);
            }else{
                $v['do_user']['have_user_course'] = 0;
            }
            unset($v['status']);
            // 1系统通知  2点赞通知 3评论通知 4回复通知 5球队邀请通知 6球队申请通知 7比赛邀请通知 8比赛申请通知 9发布动态通知 10被关注提示
            if ($v['type'] == 5 || $v['type'] == 6) {
                //5球队邀请通知  //6球队申请通知
                $user_join = UserJoin::query()
                    ->leftJoin('teams', 'user_joins.matter_id', '=', 'teams.id')
                    ->select(['user_joins.id', 'user_joins.status', 'user_joins.reason', 'teams.id as team_id', 'teams.name as team_name'])
                    ->where(['user_joins.id' => $v['sub_id']])
                    ->whereNull('teams.deleted_at')
                    ->first();
                if ($user_join) {
                    $user_join = $user_join->toArray();
                    $v['cont'] = $user_join;
                } else {
                    $v['cont'] = null;
                }
            } elseif ($v['type'] == 7 || $v['type'] == 8) {
                //7比赛邀请通知  //8比赛申请通知
                $user_join = UserJoin::query()
                    ->leftJoin('games', 'user_joins.matter_id', '=', 'games.id')
                    ->select(['user_joins.id', 'user_joins.status', 'user_joins.reason', 'games.id as games_id', 'games.name as games_name'])
                    ->where(['user_joins.id' => $v['sub_id']])
                    ->where('games.begin_time', '<', Carbon::now())
                    ->whereNull('games.deleted_at')
                    ->first();
                if ($user_join) {
                    $user_join = $user_join->toArray();
                    $v['cont'] = $user_join;
                } else {
                    $v['cont'] = null;
                }
            }
        }

        return $data;
    }

    //获取我的通知--详细内容
    public function getMyListDetail($id)
    {
        $message = UserMessage::query()->find($id);
        $msg_list = UserMessage::query()
            ->where(['user_id' => $message->user_id, 'do_user' => $message->do_user])
            ->whereIn('type', [5, 6, 7, 8])
            ->orderByDesc('id')
            ->get()
            ->toArray();

        foreach ($msg_list as &$v) {
            if ($v['type'] == 5 || $v['type'] == 6) {
                //5球队邀请通知  //6球队申请通知
                $user_join = UserJoin::query()
                    ->leftJoin('teams', 'user_joins.matter_id', '=', 'teams.id')
                    ->select(['user_joins.id', 'user_joins.status', 'user_joins.reason', 'teams.id as team_id', 'teams.name as team_name'])
                    ->where(['user_joins.id' => $v['sub_id']])
                    ->first();
                if ($user_join) {
                    $user_join = $user_join->toArray();
                    $v['cont'] = $user_join;
                } else {
                    $v['cont'] = null;
                }
            } elseif ($v['type'] == 7 || $v['type'] == 8) {
                //7比赛邀请通知  //8比赛申请通知
                $user_join = UserJoin::query()
                    ->leftJoin('games', 'user_joins.matter_id', '=', 'games.id')
                    ->select(['user_joins.id', 'user_joins.status', 'user_joins.reason', 'games.id as games_id', 'games.name as games_name'])
                    ->where(['user_joins.id' => $v['sub_id']])
                    ->where('games.begin_time', '<', Carbon::now())
                    ->whereNull('games.deleted_at')
                    ->first();
                if ($user_join) {
                    $user_join = $user_join->toArray();
                    $v['cont'] = $user_join;
                } else {
                    $v['cont'] = null;
                }
            }
        }
        //消息通知包含多种，更新具体的某种，而不是全部
        UserMessage::query()
            ->where('user_id', $message->user_id)
            ->where('type', $message->type)
            ->where('do_user', $message->do_user)
            ->update(['status' => 1]);

        return $msg_list;
    }

    //获取点赞消息列表
    public function getLikeList()
    {
        $user = auth('api')->user();

        $data = UserMessage::query()
            ->with(['feed_like', 'feed_like.user:id,name,avatar,is_auth', 'feed_like.feed' => function ($res) {
                $res->select('id', 'user_id', 'content', 'file_url', 'game_per_id')->get();
            }, 'feed_like.feed.user:id,name,avatar'])
            ->where(['user_id' => $user->id, 'type' => 2])
            ->orderByDesc('id')
            ->paginate(request('perPage', 20));

        if($data->isEmpty()){
            return [];
        }
        $data = $data->toArray();

        foreach ($data['data'] as $key => &$val) {
            if (empty($val['feed_like']['feed'])) {
                unset($val);
                continue;
            }
            $have_user_course = isset($val['feed_like']['user']['id']) ? UserService::haveUserCourse($val['feed_like']['user']['id']) : 0;
            $val['feed_like']['user']['have_user_course'] = $have_user_course;

            if (!empty($val['feed_like']['feed']) && !empty($val['feed_like']['feed']['file_url'])) {
                $val['feed_like']['feed']['file_url'] = json_decode($val['feed_like']['feed']['file_url'], true) ?? [];
            } else {
                $val['feed_like']['feed']['file_url'] = null;
            }
            if (!empty($val['feed_like']['feed']) && !empty($val['feed_like']['feed']['game_per_id'])) {
                $gameUserId = $val['feed_like']['feed']['game_per_id'];
                $scoreCard = FeedsService::queryScoreCard($gameUserId);
                $val['feed_like']['feed']['game_info'] = $scoreCard['game_info'];
                $val['feed_like']['feed']['game_score'] = $scoreCard['game_score'];
            } else {
                $val['feed_like']['feed']['game_per_id'] = null;
            }
            if (isset($val['feed_like']) && $val['feed_like']['created_at']) {
                $val['time'] = ToolServer::uc_time_ago(strtotime($val['feed_like']['created_at']));
            } else {
                $val['time'] = '';
            }
            $val['content'] = self::getMessageContent(2);
        }
        $data['data'] = array_values($data['data']);

        self::changeStatus($user->id, [2]);

        return $data;
    }

    //获取评论/回复列表
    public function getCommentList()
    {
        $user = auth('api')->user();
        try{
            $data = UserMessage::query()
                ->where(['user_id' => $user->id, 'type' => 3])
                ->orderByDesc('id')
                ->paginate(request('perPage', 20));

            $data = $data->toArray();

            foreach ($data['data'] as $k => $v) {
                $data['data'][$k]['time'] = ToolServer::uc_time_ago(strtotime($v['created_at']));
                $data['data'][$k]['content'] = self::getMessageContent(3);
                $comment = FeedComment::query()
                    ->with(['feed:id,user_id,content,file_url', 'feed.user:id,name,avatar,is_auth', 'user:id,name,avatar,is_auth'])
                    ->where(['id' => $v['sub_id']])
                    ->first()
                    ->toArray();
                $comment['feed']['user']['have_user_course'] = UserService::haveUserCourse($comment['feed']['user']['id']);
                $comment['feed']['file_url'] = !empty($comment['feed']['file_url']) ? json_decode($comment['feed']['file_url'], true) : null;
                $comment['user']['have_user_course'] = UserService::haveUserCourse($comment['user']['id']);

                $data['data'][$k]['comment'] = $comment;
            }
            $this->changeStatus($user->id, [3]);
        }catch(\Exception $exception){
            info($exception->getLine());
        }

        return $data;
    }

    //修改消息状态为已读
    public static function changeStatus(int $userId, array $type)
    {
        return UserMessage::query()->where('user_id', $userId)->whereIn('type', $type)->update(['status' => 1]);
    }

}
