<?php

namespace App\Services\Api;

use App\Models\Game;
use App\Models\Team;
use App\Models\TeamPhoto;
use App\Models\TeamUser;
use App\Models\UserIdentify;
use App\Models\UserJoin;
use Illuminate\Support\Carbon;


class TeamService
{
    public function __construct()
    {
        $this->user = auth('api')->user();
    }

    //是否是球队成员
    public function isTeamUser($teamId)
    {
        $info = TeamUser::query()
            ->where(['team_id' => $teamId, 'user_id' => $this->user->id])
            ->whereNull('deleted_at')
            ->first();

        if (!$info) {
            return false;
        }
        return true;
    }

    //用户是否申请过加入该球队
    public function isUserHadApplyJoin($teamId, $userId)
    {
        $info = UserJoin::query()
            ->where(['type' => 1,'user_id' => $userId,'matter_id' => $teamId,'invitor_id' => 0])
            ->where('status' , 0)
            ->whereNull('deleted_at')
            ->select('id', 'status')
            ->first();

        $status = !empty($info) ? $info['status'] : -1;

        return $status;
    }

    //用户是否被邀请加入该球队
    public function isUserHadInvitedJoin($teamId, $userId)
    {
        $info = UserJoin::query()
            ->where(['type' => 1,'user_id' => $userId,'matter_id' => $teamId,])
            ->where('status' , 0)
            ->where('invitor_id', '!=', 0)
            ->whereNull('deleted_at')
            ->select('id', 'status')
            ->first();

        $status = !empty($info) ? $info['status'] : -1;

        return $status;
    }

    //是否可以删除相册
    public function isHasAuthDel($id)
    {
        $info = TeamPhoto::query()
            ->where(['id' => $id, 'user_id' => $this->user->id, 'is_delete' => 0])
            ->first();

        if (!$info) {
            return false;
        }
        return true;
    }

    //用户是否可以创建球队（一个用户只能创建一个球队）
    public function isCanCreateTeam()
    {
        if (Team::where('creator', $this->user->id)->whereNull('deleted_at')->first()) {
            return false;
        }
        return true;
    }

    //是否已 加入
    public function isHadJoin($teamId, $userId )
    {
        $res = TeamUser::where([
            'user_id' => $userId,
            'team_id' => $teamId
        ])->whereNull('deleted_at')->first();

        if (!$res) {
            return false;
        }

        return true;
    }

    //获取球队相册
    public function getTeamPhotos($teamId, $userId)
    {
        $list = (new TeamPhoto())->setTable('p')->from('team_photos as p')
            ->join('users as u', 'u.id', '=', 'p.user_id')
            ->when($userId, function ($query, $userId) {
                return $query->where('user_id', $userId);
            })
            ->where(['team_id' => $teamId, 'is_delete' => 0])
            ->select('p.id', 'u.id as user_id', 'u.name as username', 'u.avatar', 'p.created_at as time', 'p.photo_urls')
            ->orderBy('id', 'desc')
            ->get()
            ->toArray();

        foreach ($list as $key => $val) {
            $timeParse = Carbon::parse($val['time']);
            $val['for_human_read'] = $timeParse->diffForHumans();
            $val['datetime'] = self::timeFormat($val['time']);
            $val['photo_urls'] = json_decode($val['photo_urls'], true);
            if (count($val['photo_urls']) > 0) {
                $val['photo_urls'] = array_column($val['photo_urls'], 'url');
            }
            unset($val['time']);
            $list[$key] = $val;
        }

        return $list;
    }

    private static function timeFormat($time)
    {
        $diff = (time() - strtotime($time)) / (365 * 24 * 3600);
        if ($diff >= 1) {
            return date('Y-m-d H:i', strtotime($time));
        }

        return date('m-d H:i', strtotime($time));
    }

    //我的球队
    public function getMyTeams($userId)
    {
        $teamIds = TeamUser::where('user_id', $userId)->pluck('team_id');

        $list = Team::query()
            ->leftJoin('users', 'users.id', '=', 'teams.creator')
            ->whereIn('teams.id', $teamIds)
            ->whereNull('teams.deleted_at')
            ->select('teams.id', 'teams.name', 'teams.img', 'teams.creator', 'teams.member_counts', 'users.name as creator_name')
            ->orderBy('id', 'desc')
            ->get();

        if($list->isEmpty()){
            return [];
        }
        $list = $list->toArray();
        foreach ($list as $key => $val) {
            $val['actual_member_counts'] = self::getTeamUserCount($val['id']);
            $list[$key] = $val;
        }

        return $list;
    }

    //获取球队人数
    public static function getTeamUserCount($teamId)
    {
        $count = (new TeamUser())->setTable('tu')->from('team_users as tu')
            ->join('users as u', 'u.id', '=', 'tu.user_id')
            ->where('tu.team_id', $teamId)
            ->where('u.status', 1)
            ->whereNull('tu.deleted_at')
            ->whereNull('u.deleted_at')
            ->count();

        return $count;
    }

    //球队成员
    public function getTeamMembers($teamId)
    {
        $userList = (new TeamUser())->setTable('tu')->from('team_users as tu')
            ->join('users as u', 'u.id', '=', 'tu.user_id')
            ->join('teams as t', 't.id', '=', 'tu.team_id')
            ->where('t.id', $teamId)
            ->where('u.status', 1)//用户状态：1正常，0禁用
            ->whereNull('u.deleted_at')
            ->whereNull('tu.deleted_at')
            ->select('u.id as user_id', 'u.name', 'u.avatar', 'u.online','u.is_auth', 't.creator')
            ->orderBy('user_id')
            ->get();

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

        foreach ($userList as $key => $val) {
            $val['is_creator'] = 0;
            $val['have_user_course'] = UserService::haveUserCourse($val['user_id']);
            if ($val['user_id'] == $val['creator']) {
                $val['is_creator'] = 1;
            }
            unset($val['creator']);
            $userList[$key] = $val;
        }
        //让球队创建者排第一位
        $sort_key = array_column($userList, 'is_creator');
        array_multisort($userList, SORT_DESC, $sort_key);

        $memberCount = Team::query()->where('id', $teamId)->value('member_counts');

        $data = [
            'user_list' => $userList,
            'user_count' => count($userList),
            'member_count' => $memberCount,
        ];

        return $data;
    }

    /**
     * 球队比赛
     * @param $teamId
     * @return array
     * 需求：经过组织认证的用户，只能创建一个球队，该用户创建的比赛就属于球队比赛
     */
    public function getTeamGames($teamId)
    {
        //当前球队的创建者是否经过组织认证
        $creator = Team::query()->where('id', $teamId)->value('creator');

        //球队创建者是否经过组织认证
        $isHadIdentify = UserIdentify::query()
            ->where([
                'user_id' => $creator,
                'type' => 1, //组织
                'status' => 1, //审核通过
                'is_delete' => 0,
            ])
            ->whereNull('deleted_at')
            ->first();

        if (!$isHadIdentify) {
            return [];
        }

        //获取此人创建的比赛
        $list = Game::where('creator', $creator)
            ->leftJoin('courses as c', 'c.id', '=', 'games.course_id')
            ->leftJoin('users as u', 'u.id', '=', 'creator')
            ->whereNull('games.deleted_at')
            ->select('games.*', 'c.name as course_name', 'u.name as creator_name')
            ->orderBy('games.id', 'desc')
            ->get();

        if($list->isEmpty()){
            return [];
        }
        $list = $list->toArray();
        //构造最终数据
        $r_list = [];
        foreach ($list as $key => $val) {
            $timeParse = Carbon::parse($val['begin_time']);
            $data['game_id'] = $val['id'];
            $data['game_name'] = $val['name'];
            $data['course_name'] = $val['course_name'];
            $data['for_human_read'] = $timeParse->diffForHumans();
            $data['begin_time'] = self::timeFormat($val['begin_time']);
            $data['is_end'] = !empty($val['end_time']) ? 1 : 0;
            $data['creator_name'] = $val['creator_name'];
            $data['img'] = $val['img'] ?: '';

            $r_list[] = $data;
        }

        return $r_list;
    }
}
