<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Jobs\AddErrorLog;
use App\Models\Collaborator;
use App\Models\ServiceUser;
use App\Models\User;
use App\Models\Video;
use App\Models\VideoCollect;
use App\Models\VideoSearch;
use App\Models\VideoVisitor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class VideoController extends Controller
{
    use ResponseJson;


    public function searchVideo(Request $request){
        try {
            $user = auth()->user();
            $keyword = $request->get('keyword');
            $id = $request->get('video_id');
//            if(empty($keyword)){
//                return $this->failure('请输入关键词');
//            }
            $list = Video::query()->join('users','video.user_id','=','users.id')
                ->when(!empty($keyword),function ($query) use($keyword){
                    $query->where('users.name','like','%'.$keyword.'%')
                        ->orWhere('video.video_title','like','%'.$keyword.'%')
                        ->orWhere('video.desc','like','%'.$keyword.'%')
                        ->orWhere('video.country','like','%'.$keyword.'%');
                })
                ->when(!empty($id),function ($query) use ($id){
                    $query->where('video.id',$id);
                })
                ->where('video.status',Video::STATUS_OPEN)
                ->select('users.avatar','users.sex','users.name','users.mobile','users.birthday','video.*')
                ->limit(10)
                ->get();

            if(!empty($keyword)){
                VideoSearch::create(['user_id'=>$user->id,'keyword'=>$keyword]);
            }

            foreach ($list as $item){
                $item->is_collect = VideoCollect::isCollect($item->id,$user->id);
                $service_user = Collaborator::where('user_id',$item->user_id)->first();
                if(!empty($service_user)){
                    $item->name = $service_user->name;
                    $item->avatar = $service_user->avatar;
                }
            }

            $data = Video::dealAcCid($list);
            return $this->success('ok',$data);
        }catch (\Exception $e){
            AddErrorLog::dispatch('searchVideo file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("搜索异常");
        }
    }

    public function getSearchLog(){
        try {
            $user = auth()->user();
            $search_list = VideoSearch::where('user_id',$user->id)->where('is_del',VideoSearch::DEL_STATUS_NO)
                ->select('keyword', DB::raw('MAX(id) AS id'))
                ->groupBy('keyword')
                ->orderByDesc('id')
                ->limit(50)->get();

            $hot_keyword = VideoSearch::select(DB::raw('count(*) as count'),DB::raw('keyword'))
                ->groupBy('keyword')->orderByDesc('count')
                ->limit(20)
                ->get()?->toArray();

            if(!empty($hot_keyword)){
                $hot_keyword = get_random_elements($hot_keyword, 7);
                sort($hot_keyword);
            }
            return $this->success('ok',compact('search_list','hot_keyword'));
        }catch (\Exception $e){
            AddErrorLog::dispatch('getSearchInfo file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }

    public function delSearchLog(Request $request){
        try {
            $user = auth()->user();
            $id = $request->get('id');
            $is_del_all = $request->get('is_del_all');
            if($is_del_all){
                VideoSearch::where('user_id',$user->id)->update(['is_del'=>VideoSearch::DEL_STATUS_YES]);
            }else{
                if(empty($id)){
                    return $this->failure('id不为空');
                }
                //软删除所有相关关键词记录
                $log = VideoSearch::where('id',$id)->first();
                VideoSearch::where('keyword',$log->keyword)->update(['is_del'=>VideoSearch::DEL_STATUS_YES]);
            }
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('delSearchLog file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("删除失败");
        }
    }

    public function getVideoList(){
        try {
            $user = auth()->user();
            $list = Video::where('status',Video::STATUS_OPEN)->orderByDesc('id')->paginate();
            foreach ($list as $item){
                $item->user = User::select('name','birthday','avatar')->find($item->user_id);
                if(empty($item->user)){
                    continue;
                }
                $service_user = Collaborator::where('user_id',$item->user_id)->first();
                if(!empty($service_user)){
                    $item->user->name = $service_user->name;
                    $item->user->avatar = $service_user->avatar;
                }
                $item->user->ac_cid =make_wangyiyun_accid($item->user_id);
                //查看当前用户是否收藏视频
                $item->is_collect = VideoCollect::isCollect($item->id,$user->id);
            }
            return $this->success('ok',$list);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getVideoList file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }

    public function getVideoDetail($id){
        try {
            $detail = Video::findOrfail($id);
            $detail->user = User::select('name','birthday','avatar')->find($detail->user_id);
            $service_user = Collaborator::where('user_id',$detail->user_id)->first();
            if(!empty($service_user)){
                $detail->user->name = $service_user->name;
                $detail->user->avatar = $service_user->avatar;
            }
            $detail->ai_img = "https://img.99ppt.com/pic/a81d5ce4-da64-41a8-bdb2-ad19f5a4aad5.png";
            $detail->status_img = "https://tva1.sinaimg.cn/large/cbc1qrn7xh648wnlqp4x8q5wchk6dt2yky6yyuv6xw7.jpg";
            return $this->success('ok',$detail);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getVideoDetail file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }

    public function collectVideo(Request $request){
        try {
            $user = auth()->user();
            $video_id = $request->input('video_id');
            $video_info = Video::find($video_id);
            if(empty($video_info)){
                return $this->failure('视频错误');
            }
            $is_cancel = $request->input('is_cancel');
            if($is_cancel){
                VideoCollect::where('video_id',$video_id)->where('user_id',$user->id)->delete();
            }else{
                VideoCollect::create(['user_id'=>$user->id,'video_id'=>$video_id,'video_user_id'=>$video_info->user_id]);
            }
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('collectVideo file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("收藏失败");
        }
    }

    public function getCollect(Request $request){
        try {
            $user = auth()->user();
            $is_collect_my = $request->input('is_collect_my');
            $query = VideoCollect::query();
            if($is_collect_my){
//                $list = $query->join('users','users.id','=','video_collect.user_id')
//                    ->select('users.name','users.avatar','users.birthday','video_collect.*')
//                    ->where('video_collect.video_user_id',$user->id)
//                    ->paginate();
                $list = $query->with('video','user','videoUser')->where('video_user_id',$user->id)
                    ->orderByDesc('id')
                    ->paginate();
                foreach ($list as $item){
                    $item->collect_video = Video::where('user_id',$item->user_id)->orderByDesc('id')->first();
                }
            }else{
//                $list = $query->join('video','video.id','=','video_collect.video_id')
//                    ->select('video.*')
//                    ->where('video_collect.user_id',$user->id)
//                    ->orderByDesc('id')
//                    ->paginate();
                $list = $query->with('video','user','videoUser')->where('user_id',$user->id)
                    ->orderByDesc('id')
                    ->paginate();
            }

            $list = Video::dealAcCid($list);
            return $this->success('ok',$list);
        }catch (\Exception $e){
            AddErrorLog::dispatch('collectVideo file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("获取失败");
        }
    }

    public function visitor(Request $request){
        try {
            $user = auth()->user();
            $video_id = $request->input('video_id');
            if(empty($video_id)){
                return $this->failure('视频错误');
            }
            $video_info = Video::find($video_id);
            if(empty($video_info)){
                return $this->failure('视频错误');
            }
            if($video_info->user_id == $user->id){
                return $this->success('ok');
            }
            //访问过只更新访问时间,不再添加记录
            $visitor = VideoVisitor::where('user_id',$user->id)->where('video_id',$video_id)->first();
            if($visitor){
                $visitor->touch();
            }else{
                VideoVisitor::create(['user_id'=>$user->id,'video_id'=>$video_id,'video_user_id'=>$video_info->user_id]);
            }
            return $this->success('ok');
        }catch (\Exception $e){
            AddErrorLog::dispatch('visitor file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("视频错误");
        }
    }

    public function getMyVisitor(){
        try {
            $user = auth()->user();
            $list = VideoVisitor::join('users','users.id','=','video_visitor.user_id')
                ->select('users.name','users.avatar','users.birthday','video_visitor.*')
                ->where('video_user_id',$user->id)
                ->paginate();

            foreach ($list as $item){
                $item->video = Video::where('user_id',$item->user_id)->orderByDesc('id')->first();
            }

            $list = Video::dealAcCid($list);
            return $this->success('ok',$list);
        }catch (\Exception $e){
            AddErrorLog::dispatch('getMyVisitor file:'.$e->getFile().' line:'.$e->getLine().' message:'.$e->getMessage())->onQueue('health');
            return $this->failure("视频错误");
        }
    }
}
