<?php


namespace App\Services\Api;


use App\Models\Game;
use App\Models\Team;
use App\Models\User;
use App\Models\UserBlacklist;
use App\Models\UserBlacklistModel;
use App\Models\UserFollow;
use App\Models\UserFriend;
use App\Models\UserMessage;
use App\Services\Base\ErrorCode;
use App\Services\TencentImAccountService;
use App\Services\TencentImFriendService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use PHPUnit\Util\Exception;

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

    public function friendsList()
    {
        $user = auth('api')->user();
        return UserFriend::query()
            ->where(['user_id' => $user->id])
            ->with(['to_user:id,name,avatar,tencent_im_user_id'])
            ->orderByDesc('id')
            ->get()
            ->toArray();
    }

    //搜索所有用户、和球队
    public function searchUser(Request $request)
    {
        $keyword = $request->post('keyword');
        $keyword = htmlspecialchars(trim($keyword));
        if (!$keyword) {
            throw new Exception(trans('api.PARAMS_ERROR'));
        }
        if (strpos($keyword, '@')) { //只搜索邮箱
            $list = User::query()
                ->where('email', $keyword)
                ->where('status', 1)
                ->whereNull('deleted_at')
                ->select(['id', 'name', 'avatar', 'mobile', 'email', 'is_auth'])
                ->get();
        } else{
            $list = User::query()
                ->where('status', 1)
                ->where('id', $keyword)
                ->orWhere('name', 'like', "%" . $keyword . "%")
                ->whereNull('deleted_at')
                ->select(['id', 'name', 'avatar', 'mobile', 'email', 'is_auth'])
                ->get();
        }

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

        $list2 = Team::query()
            ->where('name', 'like', '%'.$keyword.'%')
            ->select('id', 'name', 'img')
            ->whereNull('deleted_at')
            ->get();

        $list = [
            'user_list' => $list,
            'team_list' => $list2->isEmpty() ? [] : $list2->toArray(),
        ];

        return $list;
    }

    //申请好友
    public function applyFriend(User $user, Request $request)
    {
        $id = $request->post('id');
        if (!$to_user = User::query()->find($id)) {
            throw new Exception(trans('api.USER_NOT_EXIST'));
        }

        //插入更新状态
        $relation = UserFriend::query()->updateOrCreate(
            ['user_id' => $user->id, 'to_uid' => $id, 'status' => 0]
        );

        //给用户添加消息记录
        UserMessage::query()->create([
            'user_id' => $id,
            'type' => 5,
            'content' => $to_user['name'] . trans('api.APPLY_ADD_FRIEND'),
            'sub_id' => $relation['id']
        ]);

        return true;
    }

    //好友列表
    public function getFriendsList($keyword)
    {
        //获取我关注的
        $targetIds = UserFollow::query()->where(['user_id' => $this->user->id, 'status' => 1])->pluck('target_id');
        $targetIds = !empty($targetIds) ? $targetIds->toArray() : [];

        //获取关注我的
        $userIds = UserFollow::query()->where(['target_id' => $this->user->id, 'status' => 1])->pluck('user_id');
        $userIds = !empty($userIds) ? $userIds->toArray() : [];

        //取交集便是好友
        $friendsIds = array_intersect($targetIds, $userIds);

        $list = User::query()
            ->whereIn('id', $friendsIds)
            ->when($keyword, function ($query, $keyword) {
                return $query->where('name', 'like', $keyword . '%')->orWhere('id', $keyword);
            })
            ->select('id', 'name', 'sex', 'avatar')
            ->orderBy('id', 'desc')
            ->get();

        return $list;
    }

    //通过好友
    public function friend_pass($id)
    {
        $user_friend = UserFriend::query()->find($id);
        if (!$user_friend) {
            throw new Exception(trans('api.DATA_NOT_FOUND'));
        }
        //判断好友状态
        if ($user_friend->status == 1) {
            throw new Exception(trans('api.ALREADY_FRIEND'));
        }

        $user_friend->status = 1;
        if (!$user_friend->save()) {
            throw new Exception(trans('api.SAVE_ERROR'));
        }

        //添加双向好友关系
        $re = UserFriend::query()->updateOrCreate([
            'user_id' => $user_friend->to_uid,
            'to_uid' => $user_friend->user_id,
            'status' => 1,
        ]);
        if (!$re) {
            throw new Exception(trans('api.SAVE_ERROR'));
        }

        $user = User::query()->find($user_friend->to_uid);
        $to_user = User::query()->find($user_friend->user_id);

        //腾讯IM添加好友
        $tencent_account = new TencentImAccountService();
        $tencent_friend = new TencentImFriendService();
        //检测是否已经导入IM账号
        $check_result = $tencent_account->accountCheck([$to_user->tencent_im_user_id]);
        if (!isset($check_result) || (isset($check_result['AccountStatus']) && $check_result['AccountStatus'] == "NotImported")) {
            throw new Exception(trans('api.OPPOSITE_ACCOUNT_ERROR'));
        }

        $tencent_friend->friendAddItem($user->tencent_im_user_id, $to_user->tencent_im_user_id);

        return true;
    }

    //好友操作 拉黑/删除
    public function friendAction(User $user, $id, $type)
    {
        if (empty($type)) {
            throw new Exception(trans('api.PARAMS_ERROR'));
        }
        $touser = User::query()->where('id', $id)->first();
        if (!$touser) {
            throw new Exception(trans('api.USER_NOT_EXIST'));
        }
        switch ($type) {
            case 'black_add'://拉黑
                if ($id == $user->id) {
                    throw new Exception(trans('api.YOU_CANT_BLACK_YOURSELF'));
                }
                $tencentim = new TencentImFriendService();
                $tencentim->friend_black_add($user->tencent_im_user_id, $touser->tencent_im_user_id);
                if (!UserBlacklist::query()->where(['user_id' => $user->id, 'black_id' => $touser->id])->first()) {
                    UserBlacklist::query()->updateOrCreate(['user_id' => $user->id, 'black_id' => $touser->id]);
                }
                UserFriend::query()->where(['user_id' => $user->id, 'to_uid' => $id])->update(['status' => 2]);
                break;
            case 'black_del'://取消拉黑
                if (!$black = UserBlacklist::query()->where(['black_id' => $id, 'user_id' => $user->id])->first()) {
                    throw new Exception(trans('api.NOT_ON_YOUR_BLACKLIST'));
                }
                $tencentim = new TencentImFriendService();
                $tencentim->friend_black_del($user->tencent_im_user_id, $touser->tencent_im_user_id);
                $black->delete();
                UserFriend::query()->where(['user_id' => $user->id, 'to_uid' => $touser->id])->update(['status' => 1]);
                break;
            case 'friend_del'://删除好友
                UserFriend::query()->where(['user_id' => $user->id, 'to_uid' => $touser->id])->update(['status' => 3]);
                $tencentim = new TencentImFriendService();
                $tencentim->del_friend($user->tencent_im_user_id, $touser->tencent_im_user_id);
                break;
            default:
                break;
        }
        return true;
    }
}
