<?php


namespace App\Services;


use App\Enums\ApiEnum;
use App\Exceptions\AuthException;
use App\Exceptions\VipException;
use App\Http\Params\UserCommentParam;
use App\Http\Params\UserLikeParam;
use App\Models\User;
use App\Models\UserBlacklistModel;
use App\Models\UserComment;
use App\Models\UserInfoModel;
use App\Models\UserLikeModel;
use App\Models\UserPhotoDestroy;
use App\Models\UserVipLimit;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use PHPUnit\Util\Exception;

class HomeService
{
    /**
     * 获取首页内容
     * @param $param
     */
    public function get_list($param){
        $query = User::query()
            ->leftJoin("users_info",'users.id','=','users_info.user_id')
            ->select(['users.id','users.is_vip','users.tencent_im_user_id','users.sex','users.is_auth','users.latitude','users.longitude','users.online','users_info.avatar','users_info.nickname','users_info.area','users_info.birthday','users_info.height','users_info.weight','users_info.video','users_info.photo'])
            ->addSelect(DB::raw("acos(cos(" .$param['latitude'] . "*pi()/180)*cos(cl_users.latitude*pi()/180)*cos(" . $param['longitude'] . "*pi()/180-cl_users.longitude*pi()/180)+sin(" . $param['latitude'] . "*pi()/180)*sin(cl_users.latitude * pi()/180)) * 6367000 AS distance"))
            ->where('users.is_distory','=','0');
        $user = auth('api')->user();
        if($user){
            //用户已经登录
            //不看拉黑用户
            $black_list = UserBlacklistModel::query()
                ->where('user_id',$user->id)
                ->orWhere('black_id',$user->id)
                ->select(['black_id'])
                ->get()
                ->toArray();
            $ids = array_column($black_list,'black_id');
            $ids[]= $user->id;
            $query = $query->whereNotIn('users.id',$ids);

            if($user->sex==1){
                //只看女性
                $query = $query->where('users.sex','=',2);
            }else{
                //只看男性
                $query = $query->where('users.sex','=',1);
            }
        }else{
            //逛一逛
            $sex = Redis::get(ApiEnum::SET_GYG_SEX.request()->header('uniqueID'));
            if($sex==1){
                //只看女性
                $query = $query->where('users.sex','=',2);
            }else{
                //只看男性
                $query = $query->where('users.sex','=',1);
            }
        }
        //根据关键词搜索
        if($param['keyword']!=""){
            $query = $query->where('users_info.nickname','like','%'.$param['keyword'].'%')
                ->orWhere('users_info.hobby','like','%'.$param['keyword'].'%');
        }
        //在线
        if($param['online']==1){
            $query = $query->where(['users.online'=>$param['online']]);
        }
        //新人优先
        if($param['new']==1){
            $query = $query->orderBy('users.created_at','desc');
        }
        //距离优先
        if($param['nearby']==1){
            $query = $query->orderBy('distance','ASC');
        }
        $query = $query->paginate(request('perPage',20));
        $query = $query->toArray();
        foreach ($query['data'] as $k=>$v){
            $query['data'][$k]['age'] =!empty($v['birthday'])? birthday($v['birthday']):0;
            //计算距离
            $query['data'][$k]['distance'] =  $v['distance']>1000?round($v['distance']/1000,2).'km':round($v['distance']).'m';
            //判断是否上传视频
            $video = json_decode($v['video'],true);
            $query['data'][$k]['has_video'] = count($video)>0?1:0;
            if(!empty($v['photo'])){
                $photo = json_decode($v['photo'],true);
                if(count($photo)>0){
                    $query['data'][$k]['avatar'] = $photo[0]['url'];
                }
            }
        }
        return $query;
    }

    //用户详情
    public function user_detail($param){
        $user = auth('api')->user();
        //根据用户ID查询用户
        if(!empty($param['user_id'])&& $param['user_id']>0){
            $touser = User::query()->where('id',$param['user_id'])->first();
        }
        //根据腾讯IMID查询用户
        if(!empty($param['tencent_im_user_id'])){
            $touser = User::query()->where('tencent_im_user_id',$param['tencent_im_user_id'])->first();
        }
        $user_id = $touser->id;

        //判断逛一逛用户和非会员用户
        if(!$user){
            throw new AuthException("请先登录");
        }else{
            //判断会员特权和普通用户
            if($user->is_vip==0){
                $limit = UserVipLimit::query()->where('user_id',$user->id)->first();
                if($limit->user_detail>=1000){
                    throw new VipException("非VIP用户每天只能看10个人");
                }else{
                    //如果当天没有看过这个人  增加记录
                    if(!DB::table('users_look')->where(['user_id'=>$user->id,'look_id'=>$user_id])->whereBetween('atime',[date('Y-m-d 00:00:00'),date('Y-m-d 23:59:59')])->first()){
                        UserVipLimit::query()->where('user_id',$user->id)->increment('user_detail',1);
                    }
                }
            }
        }

        $is_like = 0;
        $is_comment = 0;

        $userinfo = User::query()
            ->leftJoin('users_info','users.id','=','users_info.user_id')
            ->where('users.id',$user_id)
            ->select(['users.id','users.sex','users.is_auth','users.is_vip','users.latitude','users.longitude','users.tencent_im_user_id','users.online','users_info.*'])
            ->first();
        $userinfo->age = birthday($userinfo->birthday);
        $userinfo->hobby = !empty($userinfo->hobby)?explode(',',$userinfo->hobby):array();

        $photo = !empty($userinfo->photo)?json_decode($userinfo->photo,true):array();

        if($user){
            //登录状态
            //增加 谁看了我记录
            look_log($user->id,$user_id);
            //查询是否喜欢
            if(UserLikeModel::query()->where(['user_id'=>$user->id,'like_id'=>$user_id])->first()){
                $is_like = 1;
            }
            //查询是否评价
            if(UserComment::query()->where(['user_id'=>$user->id,'comment_id'=>$user_id])->first()){
                $is_comment = 1;
            }
            //查询是否阅后即焚
            if(count($photo)>0){
                foreach ($photo as $k=>$v){
                    if($v['state']==1 && UserPhotoDestroy::query()->where(['url'=>$v['url'],'user_id'=>$user->id])->first()){
                        $photo[$k]['state'] = 3;
                    }
                }
            }else{
                $photo = array();
            }
            $distance =  GetDistance($user->latitude,$user->longitude,$userinfo->latitude,$userinfo->longitude);
            if(Redis::get(ApiEnum::GET_WEIXIN.$user_id.'_'.$user->id)){
               $get_weixin = 1;
            }else{
                $get_weixin = 0;
            }
        }else{
            //查询是否阅后即焚
            if(count($photo)>0){
                foreach ($photo as $k=>$v){
                    if($v['state']==1 && Redis::get(ApiEnum::PHOTO_DESTROY_URL.request()->header('uniqueID').md5($v['url']))){
                        $photo[$k]['state'] = 3;
                    }
                }
            }else{
                $photo = array();
            }
            $distance = 0;
            $get_weixin = 0;
        }

        $video_info = !empty($userinfo->video)?json_decode($userinfo->video,true):array();
        if(count($video_info)>0){
            foreach ($video_info as $k=>$v){
                $video_arr = array();
                $video_arr['url'] = isset($v['url'])?$v['url']:"";
                $video_arr['thumb'] = isset($v['thumb'])?$v['thumb']:"";
                $video_arr['state'] = 0;
                array_unshift($photo,$video_arr);
            }
        }

        $userinfo->photo = $photo;
        $userinfo->video = array_column($video_info,'url');
        $userinfo->is_like = $is_like;
        //查询评价
        $userinfo->is_comment = $is_comment;
        //评价星级
        $con1_star = UserComment::query()->where(['comment_id'=>$user_id])->avg('con1');
        $con2_star = UserComment::query()->where(['comment_id'=>$user_id])->avg('con2');
        $con3_star = UserComment::query()->where(['comment_id'=>$user_id])->avg('con3');
        $con4_star = UserComment::query()->where(['comment_id'=>$user_id])->avg('con4');
        $total_star = round(($con1_star+$con2_star+$con3_star+$con4_star)/4,1);
        $total_num = UserComment::query()->where(['comment_id'=>$user_id])->count();
        $comment = array();
        $comment['con1_star'] = round($con1_star,1);
        $comment['con2_star'] = round($con2_star,1);
        $comment['con3_star'] = round($con3_star,1);
        $comment['con4_star'] = round($con4_star,1);
        $comment['total_star'] = $total_star;
        $comment['total_num'] = $total_num;
        $userinfo->comment = $comment;
        $userinfo->distance = $distance;

        $userinfo->see_user_num = UserVipLimit::query()->where('user_id',$user->id)->value("user_detail");
        $userinfo->get_weixin = $get_weixin;
        return $userinfo;
    }

    //用户喜欢
    public function do_like(UserLikeParam $param){
        if(empty($param->like_id)){
            throw new Exception('参数错误');
        }
        $user = User::query()->where(['id'=>$param->like_id])->first();
        if(!$user){
            throw new Exception("用户不存在");
        }
        $is_like = 0;
        if($like = UserLikeModel::query()->where(['user_id'=>$param->user_id,'like_id'=>$param->like_id])->first()){
            $is_like = 0;
            User::query()->where('id',$param->like_id)->decrement('like_me_num',1);
            User::query()->where('id',$param->user_id)->decrement('like_num',1);
            $like->delete();
        }else{
            $is_like = 1;
            User::query()->where('id',$param->like_id)->increment('like_me_num',1);
            User::query()->where('id',$param->user_id)->increment('like_num',1);
            UserLikeModel::query()->create([
               'user_id'=>$param->user_id,
               'like_id'=>$param->like_id,
               'status'=>0,
               'atime'=>date('Y-m-d H:i:s'),
            ]);
        }
        return $is_like;
    }

    //用户评论
    public function do_comment(UserCommentParam $param){
        if(empty($param->comment_id)){
            throw new Exception('参数错误');
        }
        $user = User::query()->where(['id'=>$param->comment_id])->first();
        if(!$user){
            throw new Exception("用户不存在");
        }
        if(UserComment::query()->where(['user_id'=>$param->user_id,'comment_id'=>$param->comment_id])->first()){
            throw new Exception("已经评价过");
        }
        UserComment::query()->create([
           'user_id'=>$param->user_id,
           'comment_id'=>$param->comment_id,
           'con1'=>$param->con1,
           'con2'=>$param->con2,
           'con3'=>$param->con3,
           'con4'=>$param->con4,
        ]);
        return true;
    }

    //解锁微信
    public function get_weixin($user_id){
        $user = auth('api')->user();
        //判断会员特权和普通用户
        if($user->is_vip==0){
            throw new VipException("开通VIP即可解锁");
        }else{
            $limit = UserVipLimit::query()->where('user_id',$user->id)->first();
            $weixin_num = get_vip_config("weixin");
            if($limit->weixin>=$weixin_num){
                throw new Exception("每天只能解锁".$weixin_num."次");
            }else{
                //增加记录
                UserVipLimit::query()->where('user_id',$user->id)->increment('weixin',1);
            }
        }

        if(empty($user_id)){
            throw new Exception('参数错误');
        }
        $user_v = User::query()->where(['id'=>$user_id])->first();
        if(!$user_v){
            throw new Exception("用户不存在");
        }

        $weixin = UserInfoModel::query()->where('user_id',$user_id)->value('weixin');
        if(!Redis::get(ApiEnum::GET_WEIXIN.$user_id.'_'.$user->id)){
            Redis::setex(ApiEnum::GET_WEIXIN.$user_id.'_'.$user->id,86400*180,$weixin);
        }
        return $weixin;
    }

    //拉黑用户
    public function lahei($param){
        $user = auth('api')->user();
        if(!empty($param['user_id'])&& $param['user_id']>0){
            $touser = User::query()->where('id',$param['user_id'])->first();
        }
        if(!empty($param['tencent_im_user_id'])){
            $touser = User::query()->where('tencent_im_user_id',$param['tencent_im_user_id'])->first();
        }

        if(!$touser){
            throw new Exception("用户不存在");
        }
        if($touser->id==$user->id){
            throw new Exception("不能拉黑自己");
        }

        $tencentim = new TencentImFriendService();

        $res = $tencentim->friend_black_add($user->tencent_im_user_id,$touser->tencent_im_user_id);
        if(UserBlacklistModel::query()->where(['user_id'=>$user->id,'black_id'=>$touser->id])->first()){
            throw new Exception("该用户已被拉黑");
        }

        UserBlacklistModel::query()->create(['user_id'=>$user->id,'black_id'=>$touser->id,'atime'=>date("Y-m-d H:i:s")]);

        return true;
    }


    //用户详情
    public function user_detail_h5($param){
        //根据用户ID查询用户
        if(!empty($param['user_id'])&& $param['user_id']>0){
            $touser = User::query()->where('id',$param['user_id'])->first();
        }
        $user_id = $touser->id;
        $userinfo = User::query()
            ->leftJoin('users_info','users.id','=','users_info.user_id')
            ->where('users.id',$user_id)
            ->select(['users.id','users.sex','users.is_auth','users.is_vip','users.latitude','users.longitude','users.tencent_im_user_id','users.online','users_info.*'])
            ->first();
        $userinfo->age = birthday($userinfo->birthday);
        $userinfo->hobby = !empty($userinfo->hobby)?explode(',',$userinfo->hobby):array();
        $photo = !empty($userinfo->photo)?json_decode($userinfo->photo,true):array();
        $userinfo->photo = $photo;
        return $userinfo;
    }

}
