<?php


namespace App\Services;


use App\Exceptions\VipException;
use App\Http\Params\DynamicParam;
use App\Http\Params\DynamicZanParam;
use App\Http\Params\UserReportParam;
use App\Models\DynamicModel;
use App\Models\DynamicTag;
use App\Models\DynamicZanModel;
use App\Models\User;
use App\Models\UserBlacklistModel;
use App\Models\UserInfoModel;
use App\Models\UserReportModel;
use App\Models\UserVipLimit;
use Illuminate\Support\Facades\DB;
use PHPUnit\Util\Exception;
use function PHPUnit\Framework\isEmpty;

class DynamicService
{
    //话题列表
    public function tag_list($keyword,$type=0){
        $query = DB::table("dynamic_tag");
        if(!empty($keyword)){
            $query = $query->where("title","like","%{$keyword}%");
        }
        $query =  $query->where(["type"=>$type,'is_delete'=>0])
            ->orderBy("hot","desc")
            ->limit(20)
            ->get();
//        $data = DB::table("dynamic_tag")
//            ->where("title","like","%{$keyword}%")
//            ->where("type",$type)
//            ->orderBy("hot","desc")
//            ->limit(20)
//            ->get();
        return $query;
    }


    //删除话题
    public function del_tag($id){
        $user = auth('api')->user();
        if(empty($id)){
            throw new Exception('参数错误');
        }
        $tag = DynamicTag::query()->where(['id'=>$id])->first();
        if(!$tag){
            throw new Exception('话题不存在');
        }
        if($tag->user_id!=$user->id){
            throw new Exception('只能删除自己的话题');
        }
        $tag->is_delete = 1;
        $tag->save();
        return true;
    }

    /**
     * 发布动态
     */
    public function release(DynamicParam $dynamicParam){
        $user = auth('api')->user();
        //判断会员特权和普通用户
        if($user->is_vip==0){
            throw new VipException("开通VIP即可发布动态");
        }else{
            $limit = UserVipLimit::query()->where('user_id',$user->id)->first();
            if($limit->dynamic>=get_vip_config("dynamic")){
                throw new Exception("每天只能发布5条");
            }else{
                //增加记录
                UserVipLimit::query()->where('user_id',$user->id)->increment('dynamic',1);
            }
        }

        if(count($dynamicParam->img_url)>6){
            throw new Exception("最多上传6张图片");
        }


        //如果设置了标签   新标签则添加  否则就热度加1
        $tag_ins = '';
        //throw new Exception(json_encode($dynamicParam->tag));
        if(!empty($dynamicParam->tag)){
            //$tag = json_decode($dynamicParam->tag,true);
            $tag = $dynamicParam->tag;

            foreach ($tag as $v){
                if($v['id']==0){
                    if(!empty($v['title'])){
                        if($tag = DB::table('dynamic_tag')->where('title',$v['title'])->first()){
                            DB::table('dynamic_tag')->where(['id'=>$tag->id])->increment('hot',1);
                            $id = $tag->id;
                        }else{
                            $id = DB::table('dynamic_tag')->insertGetId([
                                "title"=>htmlspecialchars($v['title']),
                                "hot"=>1,
                                "type"=>1,
                                "user_id"=>$user->id,
                            ]);
                        }
                    }else{
                        throw new Exception("请输入话题内容");
                    }


                    $tag_ins.= $id.',';
                }else{
                    DB::table('dynamic_tag')->where(['id'=>$v['id']])->increment('hot',1);
                    $tag_ins.= $v['id'].',';
                }
            }
            if(strlen($tag_ins)>0){
                $tag_ins = substr($tag_ins,0,-1);
            }
        }
        $data = [
          "content"=>$dynamicParam->content,
          "img_url"=>json_encode($dynamicParam->img_url),
          "status"=>$dynamicParam->status,
          "type"=>$dynamicParam->type,
          "tag"=>$tag_ins,
          "user_id"=>$dynamicParam->user_id,
          "city"=>$dynamicParam->city,
          "latitude"=>$dynamicParam->latitude,
          "longitude"=>$dynamicParam->longitude,
        ];
        DynamicModel::create($data);

        //推送消息
        if($user->sex==1){
            $push_users = User::query()->where(['notice_status'=>1,'sex'=>2])->whereNotNull('registrationId')->get(['id','registrationId'])->toArray();
        }elseif($user->sex==2){
            $push_users = User::query()->where(['notice_status'=>1,'sex'=>1])->whereNotNull('registrationId')->get(['id','registrationId'])->toArray();
        }

        $registrationIds = array_column($push_users,'registrationId');

        $user_info = UserInfoModel::query()->where('user_id',$user->id)->first();
        JPushService::pushNotify([
            //标题
            'title' => "@".$user_info->nickname."发布了新动态，来打个招呼吧~",
            //内容
            'content' => $dynamicParam->content,
            //设备标识，跟设备相关
            'reg_id' => $registrationIds,
            //扩展字段
            'extras' => [
                'type' => 'notice',
            ],
            //推送类型
            'type' => JPushService::PUSH_TYPE_REG_ID,
        ]);


        return true;
    }



    /**
     * 动态列表
     */
    public function dynamic_list($where){
        $user = auth('api')->user();
        if($user){
            $lat = $user->latitude;
            $lng = $user->longitude;

            if($where['user_id']==0){
                $where['look_type'] = $user->sex==1?2:1;
            }

        }else{
            $lat = "0";
            $lng = "0";
        }

        $dynamic = DynamicModel::query();
        $dynamic = $dynamic
            ->with(["user"=>function($query){
                $query->select('id','sex','is_vip','tencent_im_user_id');
            },'user_info']);
        //查询条件
        //类型  type 1全部  2附近
        if($where['type']==2){
            //附近
        }

        //性别
        if($where['look_type']!=3){
            $dynamic = $dynamic->whereHas('user',function($query)use($where){
                $query->where('sex',$where['look_type'])->select();
            });
        }

        //用户id
        if($where['user_id']!=0){
            $dynamic = $dynamic->where('user_id','=',$where['user_id']);
        }

        //标签
        if($where['tag_id']!=0){
            $dynamic = $dynamic->whereRaw('FIND_IN_SET(?,tag)',[$where['tag_id']]);
        }

        $dynamic = $dynamic->whereHas('user',function($query)use($where,$user){
            if($user){
                //不看拉黑用户
                $black_list = UserBlacklistModel::query()->where('user_id',$user->id)->select(['black_id'])->get()->toArray();
                $ids = array_column($black_list,'black_id');
                if($where['user_id']!=$user->id) {
                    $ids[] = $user->id;
                }
                $query->where('is_distory',0)->whereNotIn('users.id',$ids);
            }else{
                $query->where('is_distory',0)->select();
            }


        });

        $dynamic = $dynamic->orderByDesc('id')
            ->paginate(request('perPage',20));
        $dynamic = $dynamic->toArray();
        foreach ($dynamic['data'] as $k=>$v){
            $dynamic['data'][$k]['img_url'] = json_decode($v['img_url'],true);


            //计算距离 如果设置了位置，使用设置位置  否则使用定位位置
            if(!$v['latitude']||!$v['longitude']){
                //没有设置位置  取用户位置
                $v_user = User::query()->where(['id'=>$v['user_id']])->first();
                if(!$v_user['latitude'] || !$v_user['longitude']){
                    $distance = 0;
                }else{
                    $distance = GetDistance($lat,$lng,$v_user['latitude'],$v_user['longitude']);
                }
            }else{
                $distance = GetDistance($lat,$lng,$v['latitude'],$v['longitude']);
            }
            if($distance>=1){
                $distance = round($distance);
            }else{
                $distance = round($distance*1000);
            }

            $dynamic['data'][$k]['distance'] = $distance;


            $dynamic['data'][$k]['atime'] = uc_time_ago(strtotime($v['created_at']));
            $dynamic['data'][$k]['tag'] = DB::table("dynamic_tag")->whereIn('id',explode(',',$v['tag']))->get();

            $is_zan = 0;
            if($user = auth('api')->user()){
                if(DynamicZanModel::query()->where(['user_id'=>$user->id,'dynamic_id'=>$v['id']])->first()){
                    $is_zan = 1;
                }
            }
            $dynamic['data'][$k]['is_zan'] = $is_zan;



        }

        return $dynamic;
    }

    //点赞  如果已经点赞 则取消点赞
    public function zan(DynamicZanParam $dynamicZanParam){
        if(empty($dynamicZanParam->dynamic_id)){
            throw new Exception('参数错误');
        }
        $dynamic = DynamicModel::where(['id'=>$dynamicZanParam->dynamic_id])->first();
        if(!$dynamic){
            throw new Exception("动态不存在");
        }

        if($dynamic_zan = DynamicZanModel::query()->where(['user_id'=>$dynamicZanParam->user_id,'dynamic_id'=>$dynamicZanParam->dynamic_id])->first()){
            $zan = 0;
            //已点赞  取消点赞
            DynamicModel::query()->where('id',$dynamicZanParam->dynamic_id)->decrement('zan_num',1);
            $dynamic_zan->delete();
        }else{
            $zan = 1;
            //点赞
            DynamicModel::query()->where('id',$dynamicZanParam->dynamic_id)->increment('zan_num',1);
            DynamicZanModel::query()->create([
                'user_id'=>$dynamicZanParam->user_id,
                'dynamic_id'=>$dynamicZanParam->dynamic_id,
                'status'=>0,
                'atime'=>date('Y-m-d H:i:s'),
            ]);
        }
        return $zan;
    }

    //删除动态
    public function del(DynamicParam $dynamicParam){
        if(empty($dynamicParam->id)){
            throw new Exception('参数错误');
        }
        $dynamic = DynamicModel::query()->where(['id'=>$dynamicParam->id])->first();
        if(!$dynamic){
            throw new Exception("动态不存在");
        }
        $dynamic->delete();
        return true;
    }

    //举报动态
    public function report(UserReportParam $userReportParam){
//        if(empty($userReportParam->report_id)){
//            throw new Exception('参数错误');
//        }

        if(empty($userReportParam->content)){
            throw new Exception('请输入举报内容');
        }

        if($userReportParam->type==2){
            $dynamic = DynamicModel::query()->where(['id'=>$userReportParam->report_id])->first();
            if(!$dynamic){
                throw new Exception("动态不存在");
            }
            $report_id = $dynamic->id;
        }else{
            if(!empty($userReportParam->report_id)&& $userReportParam->report_id>0){
                $user = User::query()->where('id',$userReportParam->report_id)->first();
            }
            if(!empty($userReportParam->tencent_im_user_id)){
                $user = User::query()->where('tencent_im_user_id',$userReportParam->tencent_im_user_id)->first();
            }
            if(!$user){
                throw new Exception("用户不存在");
            }
            $report_id = $user->id;
        }
        UserReportModel::query()->create([
           "user_id"=>$userReportParam->user_id,
           "report_id"=>$report_id,
           "type"=>$userReportParam->type,
           "content"=>htmlspecialchars($userReportParam->content),
           "info"=>htmlspecialchars($userReportParam->info),
           "status"=>0,
           "img_url"=>json_encode($userReportParam->img_url),
        ]);
        return true;
    }
}
