<?php

namespace App\Http\Controllers\Admin;

use App\Events\SendSmsEvent;
use App\Models\Course;
use App\Models\Cate;
use App\Models\BgMusic;
use App\Models\Comment;
use App\Models\Like;
use App\Models\SendSms;
use Carbon\Carbon;
use Illuminate\Http\Request;
use FFMpeg\FFMpeg;
use Illuminate\Validation\Rule;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Overtrue\EasySms\EasySms;
use FFMpeg\Format\Audio\Mp3;
use FFMpeg\Format\Video\X264;

class CourseController extends Controller
{
    //获取列表
    public function list(Request $request): \Illuminate\Http\JsonResponse
    {
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $search_name=$request->input('search_name');
        $type=$request->input('type');
        $c_id=$request->input('c_id');
        $num=$page_size*($page_index-1);
        $course=Course::setField();
        if($search_name){
            $course->where('title','like','%'.$search_name.'%');
        }
        if(isset($type) && $type!='all'){
            $course->where('state',$type);
        }
        if(isset($c_id) && $c_id!='all'){
            $course->where('c_id',$c_id);
        }
        $count=$course->count();
        $list=$course->orderByDesc('id')
            ->orderByDesc('is_top')->orderByDesc('top_at')
            ->skip($num)->take($page_size)->get();
        foreach($list as $key=>$val){
            $pid=Cate::where('id',$val->c_id)->value('pid');
            $list[$key]->p_cate=Cate::where('id',$pid)->value('name');
            $list[$key]->pid=$pid;
        }
        return $this->success_list($list,'',$count);
    }

    //添加课程
    public function addCourse(Request $request)
    {
        $rules=[
            'title' => 'required',
            'c_id' => 'required',
        ];
        $messages = [
            'title.required' => '课程标题为必填项.',
            'c_id.required' => '课程分类为必填项.'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        if($request->input('is_top')==1){
            $top_at=Carbon::now();
        }else{
            $top_at=null;
        }
        $res=Course::create([
            'title'=>$request->input('title'),
            'c_id'=>$request->input('c_id'),
            'cate'=>$request->input('cate'),
            'img'=>$request->input('img'),
            'video'=>$request->input('video'),
            'audio'=>$request->input('audio'),
            'perface'=>$request->input('perface'),
            'content'=>$request->input('content'),
            'avatar'=>$request->input('avatar'),
            'author'=>$request->input('author'),
            'permission'=>$request->input('level'),
            'is_share'=>$request->input('is_share'),
            'state'=>$request->input('state'),
            'is_top'=>$request->input('is_top'),
            'top_at'=>$top_at,
        ]);
        if($res){
            return $this->success([]);
        }
       return $this->error();
    }

    //修改课程
    public function editCourse(Request $request)
    {
        $rules=[
            'title' => 'required',
//            'c_id' => Rule::unique('article')->ignore($request->input('id')),
            'c_id' => 'required',
        ];
        $messages = [
            'title.required' => '课程标题为必填项.',
            'c_id.required' => '课程分类为必填项.'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        if($request->input('is_top')==1){
            $top_at=Carbon::now();
        }else{
            $top_at=null;
        }
        $course=Course::where('id',$request->input('id'))->first();
        $course->title=$request->input('title');
        $course->c_id=$request->input('c_id');
        $course->cate=$request->input('cate');
        $course->img=$request->input('img');
        $course->audio=$request->input('audio');
        $course->video=$request->input('video');
        $course->perface=$request->input('perface');
        $course->content=$request->input('content');
        $course->avatar=$request->input('avatar');
        $course->author=$request->input('author');
        $course->permission=$request->input('level');
        $course->is_share=$request->input('is_share');
        $course->state=$request->input('state');
        $course->is_top=$request->input('is_top');
        $course->top_at=$top_at;
        $res=$course->save();
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //课程上线
    public function onlineCourse(Request $request)
    {
        $id=$request->input('id');
        $course=Course::where('id',$id)->first();
        if(empty($course)){
            return $this->error('450001','课程不存在');
        }
        $course->state = $course->state?0:1;
        $course->online_at = Carbon::now();
        $res=$course->save();
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //课程批量上架
    public function manyOnlineCourse(Request $request)
    {
        $ids=$request->input('ids');
        $type=$request->input('type');
        $state=$type?0:1;
        $count=Course::whereIn('id',$ids)->where('state',$state)->count();
        if($count==0){
            return $this->success('450001','没有可操作状态课程');
        }
        $res=Course::whereIn('id',$ids)->where('state',$state)->update([
            'state'=>$type,
            'online_at'=>Carbon::now(),
        ]);
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //课程是否可分享
    public function shareCourse(Request $request)
    {
        $id=$request->input('id');
        $course=Course::where('id',$id)->first();
        if(empty($course)){
            return $this->error('450001','课程不存在');
        }
        $course->is_share = $course->is_share?0:1;
        $res=$course->save();
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //删除课程
    public function deleteCourse(Request $request)
    {
        $id=$request->input('id');
        $res=Course::where('id',$id)->delete();
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //插入图片
    public function uploadImg(Request  $request){
        $file = $request->file('img')->store('image/'.date('Y-m-d'));
        if(empty($file)){
            return $this->error();
        }else{
            return $this->success(Storage::url($file));
        }
    }

    //插入视频
    public function uploadVideo(Request  $request){
        $file = $request->file('video')->store('video/'.date('Y-m-d'));
        if(empty($file)){
            return $this->error();
        }else{
            return $this->success(Storage::url($file));
        }
    }

    //插入音频
//    public function uploadAudio(Request  $request){
//        $file = $request->file('audio')->store('audio/'.date('Y-m-d'));
//        if(empty($file)){
//            return $this->error();
//        }else{
//            return $this->success(Storage::url($file));
//        }
//    }
    public function uploadAudio(Request  $request){
        $ff_path=[
            'ffmpeg.binaries'  => config('element.ffmpeg'),//ffmpeg运行的路径
            'ffprobe.binaries' => config('element.ffprobe'),//ffprobe运行路径
            'timeout'          => 30000, // The timeout for the underlying process
            'ffmpeg.threads'   => 12, // The number of threads that FFMpeg should use
        ];
        $file = $request->file('audio')->store('audio/'.date('Y-m-d'));
        if(empty($file)){
            return $this->error();
        }else{
            $path=storage_path().'/app/public/audio/'.date('Y-m-d').'/';
            $filename=array_slice(explode('/',$file),-1,1);
            $newFile=$path.$filename[0];
            $ffprobe            = \FFMpeg\FFProbe::create($ff_path);
            $duration = $ffprobe->format($newFile)->get('duration',100);
            $size = $ffprobe->format($newFile)->get('size');

            return $this->success([$duration,$size,Storage::url($file)]);
        }
    }

    //获取课程详情
    public function getCourseDetail(Request $request)
    {
        $id=$request->input('id');
        $info=Course::query()->where('id',$id)->first();
        return $this->success($info);
    }
    //置顶
    public function setTop(Request $request)
    {
        $id=$request->input('id');
        $res=Course::query()->where('id',$id)->update(['is_top'=>1,'top_at'=>Carbon::now()]);
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }
    //取消置顶
    public function cancelTop(Request $request)
    {
        $id=$request->input('id');
        $res=Course::query()->where('id',$id)->update(['is_top'=>0,'top_at'=>null]);
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

}
