<?php

namespace App\Http\Controllers\Admin;

use App\Events\SendSmsEvent;
use App\Models\Article;
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 ArtController extends Controller
{
    //获取列表
    public function list(Request $request): \Illuminate\Http\JsonResponse
    {
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
        $count=Article::query()->count();
        $list=Article::query()
//            ->orderByDesc('stage')
            ->select('title','stage','audio','perface','created_at','id','duration','size','shelves','read','like','share','timing_shelves','shelves_time')
            ->orderByDesc('created_at')->skip($num)->take($page_size)->get();
        return $this->success_list($list,'',$count);
    }

    //点赞
    public function like(Request  $request): \Illuminate\Http\JsonResponse
    {
        return $this->success($this->getMtRandStr(108));
        $user_id=$request->input('user_id');
        $article_id=$request->input('article_id');

//        $res=Redis::sismember('like:article', $article_id.':'.$user_id);
//        if($res){
//            Redis::srem('like:article', $article_id.':'.$user_id);
//            Redis::decr('article_'.$article_id.'_count');
//            Redis::hdel('article_user_like', $article_id.'_'.$user_id);
//        }else{
//            Redis::sadd('like:article', $article_id.':'.$user_id);
//            Redis::incr('article_'.$article_id.'_count');
//            Redis::hset('article_user_like', $article_id.'_'.$user_id, Carbon::now());
//        }

        $res=Like::query()->where('user_id',$user_id)->where('article',$article_id)->first();

        if($res){
            Article::query()->where('id',$article_id)->decrement('like');
            Like::query()->where('user_id',$user_id)->where('article',$article_id)->delete();
        }else{
            Article::query()->where('id',$article_id)->increment('like');
            Like::query()->create([
                'user_id'=>$user_id,
                'article_id'=>$article_id,
            ]);
        }
        return $this->success([]);
//        Redis::set('name','wetalk');
//        return Redis::get('name');
    }

    //音频合成
    public function mergeAudio($filePath)
    {
        Log::info($filePath);
        $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
        ];
        $ffmpeg            = \FFMpeg\FFMpeg::create($ff_path);
        $path='/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/storage/app/public/';
        $files=[];
        $arr=explode('.',$filePath[1]);
        $end=array_pop($arr);
        foreach($filePath as $key=>$val) {
            $files[$key] = $path . $val;
        }
        $filename = 'audio/'.date('Y-m-d').'/z-'.$this->getMtRandStr('28').'.'.$end ;
        $newFile  =  $path.$filename;
        $video  =  $ffmpeg ->open( $files[1] );
        $video ->concat( $files )->saveFromSameCodecs( $newFile , TRUE);

        $ffprobe            = \FFMpeg\FFProbe::create($ff_path);
        $duration = $ffprobe->format($newFile)->get('duration',100);
        $size = $ffprobe->format($newFile)->get('size');

        return ['file'=>$filename,'duration'=>$duration,'size'=>$size];
    }

    //上传音频
    public function uploadAudioSimple(Request $request): \Illuminate\Http\JsonResponse
    {
        $file = $request->file('audio')->store('audio/'.date('Y-m-d'));

        $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
        ];
        $ffmpeg            = \FFMpeg\FFMpeg::create($ff_path);
        $path='/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/storage/app/public/';
//        $files=[];
//        $arr=explode('.',$filePath[1]);
//        $end=array_pop($arr);
//        foreach($filePath as $key=>$val) {
//            $files[$key] = $path . $val;
//        }
//        $filename = 'audio/'.date('Y-m-d').'/z-'.$this->getMtRandStr('28').'.'.$end ;
        $newFile  =  $path.$file;

        $ffprobe            = \FFMpeg\FFProbe::create($ff_path);
//        $duration = $ffprobe->format($newFile)->get('duration',100);
//        $size = $ffprobe->format($newFile)->get('size');
        $duration = $ffprobe->format($newFile)->get('duration',100);
//        $duration = $request->input('duration');
        //保存音频
        $result=Article::create([
            'audio'=>$file,
            'duration'=>$duration,
            'shelves'=>2 //存草稿
        ]);
        if(empty($result)){
            return $this->error();
        }else{
            return $this->success($result);
        }
    }
    //上传音频
    public function uploadAudio(Request $request): \Illuminate\Http\JsonResponse
    {
        Log::info('上传音频');
        $name=$request->input('name');
        $num=$request->input('num');
        $total=$request->input('total');
        $volume=$request->input('volume');
        $file = $request->file('audio')->store('audio/'.date('Y-m-d'));
        if(empty($file)){
            return $this->error('450001','失败');
        }
        Redis::hset($name,$num,$file);
        Redis::sadd($name.'set',$num);
        Log::info('---123--'.Redis::scard($name.'set'));

        if(Redis::scard($name.'set') == $total){
            Redis::hset($name,$num,$file);
            $files=Redis::hgetall($name);
            Log::info($files);
            ksort($files);
            $audio=$this->mergeAudio($files);
            //保存音频
            $result=Article::create([
                'part'=>json_encode($files),
                'audio'=>$audio['file'],
                'duration'=>$audio['duration'],
                'size'=>$audio['size'],
                'volume'=>$volume,
                'shelves'=>2 //存草稿
            ]);
            Redis::del($name);
            Redis::del($name.'set');
            Log::info('判断有误删除redis'.Redis::scard($name.'set'));

            return $this->success($result);
        }else{
            return $this->success(Storage::url($file));
        }
    }

    //
    public function downAudioFile(Request $request){
        $id=$request->input('id');
        $info=Article::query()->where('id',$id)->first();
        if($info->shelves!=1){
            return $this->error('450001','音频未上架不能下载');
        }
        $url = "https://weiliao.woaidakele.cn/storage/".$info->audio;
        $file_name = $info->title?$info->title.'.'.pathinfo($url,PATHINFO_EXTENSION) : basename($url);
        $mime = 'application/force-download';
        header('Pragma: public');     // required
        header('Expires: 0');        // no cache
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: private', false);
        header('Content-Type: ' . $mime);

//        if(strpos($_SERVER['HTTP_USER_AGENT'],”MSIE”)){
            header( 'Content-Disposition: attachment; filename=”'.urlencode($file_name ).'"' );//如果是ie存为的名字要urlencode
//        }else{
//            header( 'Content-Disposition: attachment; filename=”'.$file_name .'"');//存为的名字
//        }

//        header('Content-Disposition: attachment; filename="' . $file_name . '"');


        $ua = $_SERVER["HTTP_USER_AGENT"];

        $file_name = $info->title?$info->title.'.'.pathinfo($url,PATHINFO_EXTENSION) : basename($url);

        $encoded_filename = urlencode($file_name);

        $encoded_filename = str_replace("+", "%20", $encoded_filename);

        if(preg_match("/MSIE/", $ua) || preg_match("/Trident\/7.0/", $ua)){
            header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');

        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'' . $file_name . '"');

        } else {
            header('Content-Disposition: attachment; filename="' . $file_name . '"');

        }


        header('Content-Transfer-Encoding: binary');
        header('Connection: close');
        readfile($url);        // push it out
        exit();

    }

//    public function sendSms($phone){
//        $config=config('easysms');
//        $easySms = new EasySms($config);
//        $content="常来微聊已经发布，请及时查看并发送给代理。";
//        try{
//            $easySms->send($phone, ['content' =>$content ]);
//        } catch (\Overtrue\EasySms\Exceptions\NoGatewayAvailableException $exception) {
//            $message = $exception->getException('qcloud')->getMessage();
//            Log::info($message == null ? '短信发送异常' : $message);
//        }
//        Log::info($phone.'---短信发送成功');
//    }

    //取随机10位字符串
    public function getMtRandStr($n){
        $strs="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        for($i=0;$i<10;$i++){
            $strs.=$strs;
        }
        $name=substr(str_shuffle($strs),mt_rand(0,strlen($strs)-$n-1),$n);
        return $name;
    }

    //保存微聊
    public function editArticle(Request $request): \Illuminate\Http\JsonResponse
    {
        $rules=[
//            'stage' => Rule::unique('article')->ignore($request->input('id')),
//            'title' => 'required',
        ];
        $messages = [
//            'stage.required' => '微聊期数为必填项.',
//            'title.required' => '微聊标题为必填项.',
//            'stage.unique' => '该期数已存在.'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $data['stage'] = $request->input('stage');
        $data['title'] = $request->input('title');
        $data['perface'] = $request->input('perface');
        $data['shelves'] = $request->input('shelves');
        $data['created_at'] = $request->input('created_at')?$request->input('created_at'):Carbon::now();
        if($request->input('shelves') == 1){
            $data['shelves_time']=Carbon::now();
        }
        if($request->has('content') && !empty($request->input('content'))){
            $data['content'] = $request->input('content');
        }
        $data['is_timing']=$request->input('is_timing');
        if($request->input('is_timing') == 1){
            $data['timing_shelves']=date("Y-m-d H:i",strtotime($request->input('timing_shelves')));
        }
        $res=Article::where('id',$request->input('id'))->update($data);
        if($res){
            if($request->input('shelves') == 1){
                event(new SendSmsEvent());
            }
            return $this->success($res);
        }
        return $this->error();
    }

    //保存微聊内容
    public function editArticleContent(Request $request): \Illuminate\Http\JsonResponse
    {
        $data['content'] = $request->input('content');
        if(empty($request->input('content'))){
            return $this->error('450001','微聊内容不能为空');
        }
        $res=Article::where('id',$request->input('id'))->update($data);
        if($res){
            return $this->success($res);
        }
        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 getArticleListNum(Request  $request){
        $data['no_release']=Article::query()->where('shelves',0)->count();
        $data['release']=Article::query()->where('shelves',1)->count();
        $data['draft']=Article::query()->where('shelves',2)->count();
        return $this->success_list($data);
    }

    //微聊列表
    public function getArticleList(Request  $request){
        $shelves=$request->input('shelves');
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
        $count=Article::query()->where('shelves',$shelves)->count();
        $list=Article::query()->where('shelves',$shelves)
            ->select('title','stage','audio','perface','created_at','id','duration','size','shelves','read','content','like','share','timing_shelves','volume','shelves_time')
            ->orderByDesc('created_at')->skip($num)->take($page_size)->get();
        foreach($list as $key=>$val){
            $list[$key]->con=true;
            if(empty($val->title) || empty($val->content)){
                $list[$key]->con=false;
            }
            unset($list[$key]->content);
        }
        return $this->success_list($list,'成功',$count);
    }

    //获取单个信息详情
    public function getArticleDetail(Request $request)
    {
        $id=$request->input('id');
        $info=Article::query()->where('id',$id)->first();
//        $filename = "/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/storage/app/public/".$info->audio;
//        $info->md5file=md5_file($filename);
        return $this->success($info);
    }

    //定时发布手动发布
    public function manualRelease(Request  $request){
        $id=$request->input('id');
        $res=Article::query()->where('id',$id)->update(['shelves'=>1,'shelves_time'=>Carbon::now(),'is_timing'=>0,'timing_shelves'=>null]);
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }

    //下架微聊
    public function cancelShelvesArticle(Request  $request)
    {
        $id=$request->input('id');
        $res=Article::query()->where('id',$id)->update(['shelves'=>2,'shelves_time'=>null]);
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }

    //删除单个信息详情
    public function deleteArticle(Request $request)
    {
        $id=$request->input('id');
        $res=Article::query()->where('id',$id)->delete();
        if($res){
            return $this->success([]);
        }else{
            return $this->error();
        }
    }

    //继续录制音频
    public function continueUploadAudio(Request $request): \Illuminate\Http\JsonResponse
    {
        $id=$request->input('id');
        $file = $request->file('audio')->store('audio/'.date('Y-m-d'));
        if(empty($file)){
            return $this->error('450001','失败');
        }
        $first_file=Article::where('id',$id)->value('audio');
//        return [$first_file,$file];
        $audio=$this->mergeAudio([$first_file,$file]);

        $article=Article::where('id',$id)->first();
        $article->part=json_encode([$first_file,$file]);
        $article->audio=$audio['file'];
        $article->duration=$audio['duration'];
        $article->size=$audio['size'];

        $article->shelves=2; //待上架
        $article->save();
        return $this->success($article);
    }

    //继续上传音频
//    public function continueUploadAudio(Request $request): \Illuminate\Http\JsonResponse
//    {
//        $name=$request->input('name');
//        $id=$request->input('id');
//        $num=$request->input('num');
//        $total=$request->input('total');
//        $volume=$request->input('volume');
//        $file = $request->file('audio')->store('audio/'.date('Y-m-d'));
//        if(empty($file)){
//            return $this->error('450001','失败');
//        }
//        if(empty(Redis::hgetall($name))){
//            Redis::hset($name,1,Article::where('id',$id)->value('audio'));
//            Redis::sadd($name.'set',1);
//        }
//
//        Redis::hset($name,$num+1,$file);
//        Redis::sadd($name.'set',$num+1);
//
//        Log::info('---123--'.Redis::scard($name.'set'));
//        Log:info('----------'.($total+1));
//
//        if(Redis::scard($name.'set') == $total+1){
//            Redis::hset($name,$num+1,$file);
//            $files=Redis::hgetall($name);
//            ksort($files);
//            $audio=$this->mergeAudio($files);
//            //保存音频
//            $article=Article::where('id',$id)->first();
//            $article->part=json_encode($files);
//            $article->audio=$audio['file'];
//            $article->duration=$audio['duration'];
//            $article->size=$audio['size'];
//            if($volume){
//                $article->volume=$volume;
//            }
//            $article->shelves=2; //待上架
//            $article->save();
//            Redis::del($name);
//            Redis::del($name.'set');
//            Log::info('---123456--'.Redis::scard($name.'set'));
//            return $this->success($article);
//        }else{
//            return $this->success(Storage::url($file));
//        }
//    }

    //获取所有微聊

    //获取评论列表
    public function getCommentList(Request  $request)
    {
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $search_name=$request->input('search_name');
        $type=$request->input('type');
        $num=$page_size*($page_index-1);
        if($type==1){//文章
            if($search_name){
                $where=function($query)use($search_name){
                    $article_ids=Article::where('title','like','%'.$search_name.'%')->pluck('id');
                    $query->whereIn('article_id',$article_ids);
                };
            }else{
                $where=function($query){
                    $query->where('article_id','>',0);
                };
            }
        }else{
            $where=function($query){
                $query->where('article_id',0);
            };
        }
        $count=Comment::where($where)->count();
        $list=Comment::with(['article:id,title,stage','user:id,nickname'])->where($where)->orderBy('created_at','desc')->skip($num)->take($page_size)->get();

        return $this->success_list($list,'',$count);
    }

    //审核评论
    public function authComment(Request  $request)
    {
        $comment_id=$request->input('comment_id');
        $comment=Comment::where('id',$comment_id)->first();
        $comment->is_audit=$comment->is_audit?0:1;
        $res=$comment->save();
        if($res){
            return $this->success([]);
        }else {
            return $this->error();
        }
    }

    //查看单个音频评论
    public function getArticleComment(Request  $request)
    {
        $page_index=$request->input('page_index');
        $page_size=$request->input('page_size');
        $num=$page_size*($page_index-1);
        $article_id=$request->input('article_id');
        $count=Comment::where('article_id',$article_id)->count();
        $list=Comment::with('user:id,nickname,headimgurl')->where('article_id',$article_id)->orderBy('created_at','desc')->skip($num)->take($page_size)->get();
        return $this->success_list($list,'',$count);
    }

    //上传背景音乐
    public function uploadBackgroundMusic(Request $request)
    {
        $file = $request->file('music')->store('bg-music/'.date('Y-m-d'));
        if(empty($file)){
            return $this->error('450001','失败');
        }
        return $this->success(Storage::url($file));
    }

    //添加背景音乐
    public function addBackgroundMusic(Request $request)
    {
        $name=$request->input('name');
        $url=$request->input('url');
        $res=BgMusic::query()->create([
            'name'=>$name,
            'url'=>$url
        ]);
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //修改背景音乐
    public function editBackgroundMusic(Request $request)
    {
        $id=$request->input('id');
        $name=$request->input('name');
        $url=$request->input('url');
        $res=BgMusic::query()->where('id',$id)->update([
            'name'=>$name,
            'url'=>$url
        ]);
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }
    //获取工作人员接收通知手机号
    public function getAllPhone(Request $request){
        $sms=SendSms::all();
        return $this->success($sms);
    }

    //添加工作人员接收通知手机号
    public function addPhone(Request $request){
        $rules=[
            'name' => 'required',
            'phone' => 'required|unique:send_sms',
        ];
        $messages = [
            'phone.required' => '手机号为必填项.',
            'name.required' => '管理员名称为必填项.',
            'phone.unique' => '该手机号已存在.'
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if($validator->fails()){
            return $this->error('400013',$validator->errors()->first());
        }
        $phone=$request->input('phone');
        $name=$request->input('name');
        $res=SendSms::create([
            'phone'=>$phone,
            'name'=>$name,
        ]);
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //删除工作人员接收通知手机号
    public function deletePhone(Request $request){
        $id=$request->input('id');
        $res=SendSms::where('id',$id)->delete();
        if($res){
            return $this->success([]);
        }
        return $this->error();
    }

    //
    public function getData(){

//        event(new SendSmsEvent());
//return '123';
//        $code="http://fangwei.jiuweiyun.cn/a/?bid=1&f=803971935635";
//        $code="http://daweiboshi.hyxmt.cn/a?bid=1&f=803971935635";
        $code="http://daweiboshi.hyxmt.cn/a?bid=1&f=806714185720";
        $file=file_get_contents($code);
//return $this->success($file);
//        return $this->success(date("YmdHis",strtotime('+3600 second',strtotime($order->created_at))));

//        return $this->success(strpos($code,'jiuweiyun.cn'));

        preg_match_all('/<span>产品名称：<\/span>   大卫博士健康内裤（(.*)）/',$file,$result);

       return $this->success($result);

    }

    public function ddd(){

        $pcm='/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/public/storage/audio/2021-11-16/record_and_mix.pcm';
        $mp3='/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/public/storage/audio/2021-11-16/newWaiter20310723102314_f.mp3';

        exec('ffmpeg -y -f s16be -ac 1 -ar 48000 -acodec pcm_s16le -i '.$pcm.' '.$mp3);

//        exec('ffmpeg -y -ac 1 -ar 16000 -f s16le -i '.$pcm.' -c:a libmp3lame -q:a 2 '.$mp3);
return $mp3;

        $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
        ];
        $ffmpeg            = \FFMpeg\FFMpeg::create($ff_path);
        $back='/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/public/background-Yiruma (1).flac';
//        $back='/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/storage/app/public/audio/2021-07-13/W3T1L6U5eiTHfcWZns5OZOEc6ZsHrHrbw7ei9Yo8.mp3';
        $path='/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/storage/app/public/audio/2021-07-13/WINAYUPkK1MnfX7hqqMsfpnJljznIFBVc7PAcDu4.mp3';
        $filename = '/www/wwwroot/weiliao.woaidakele.cn/weiliao-weapp-api/storage/app/public/audio/'.date('Y-m-d').'/b-'.$this->getMtRandStr('28').'.mp3';


//        exec('ffmpeg -i '.$back.' -i '.$path.' -filter_complex "[0:a] [1:a]amerge=inputs=2[aout]" -map "[aout]" -ac 2 '.$filename);
        exec('ffmpeg -i '.$path.' -i '.$back.' -filter_complex amix=inputs=2:duration=first:dropout_transition=200  '.$filename);


         return $filename;
        $advancedMedia = $ffmpeg->openAdvanced(array($path));
//        $advancedMedia->filters()
//            ->sine('[a]', 5);
        $advancedMedia
            ->map(array('0:a'), new Mp3(), $filename)
            ->save();


//        $ffmpeg = $this->getFFMpeg();
//        $inputs = array(realpath(__DIR__ . '/../files/Audio.mp3'));
//        $format = new Mp3();
//        $format->setAudioKiloBitrate(30);
//        $output = __DIR__ . '/' . self::OUTPUT_PATH_PREFIX . 'audio_test.mp3';
//
//        $advancedMedia = $ffmpeg->openAdvanced($inputs);
//        $advancedMedia
//            ->map(array('0:a'), $format, $output)
//            ->save();
//
//        $this->assertFileExists($output);
//        $this->assertEquals('MP2/3 (MPEG audio layer 2/3)',
//            $ffmpeg->open($output)->getFormat()->get('format_long_name'));
//        unlink($output);



//        $ffmpeg = FFMpeg\FFMpeg::create($ff_path);
//        $audio = $ffmpeg->open($back);
//
//        $audio->filters()->addMetadata(["artwork" => $path]);
//        return 123123;
return $filename;


        $newFile  =  $path.$filename;
        $ffprobe            = \FFMpeg\FFProbe::create($ff_path);
        $duration = $ffprobe->format($newFile)->get('duration',100);
        $size = $ffprobe->format($newFile)->get('size');

        return ['file'=>$filename,'duration'=>$duration,'size'=>$size];


        $audio->filters()->addMetadata(["artwork" => "/path/to/image/file.jpg"]);
    }


}
