<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Modules\Camera\Entities\CameraList;
use Modules\Camera\Enum\CameraEnum;
use Modules\Camera\Services\CameraServices;
use Modules\Mine\Entities\MineListExt;

class UpdateCameraStatus extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'camera:updatestatus';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新摄像头在线状态';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

    }

    public function updateCameraStatus()
    {
        //查询海康视频服务器中的所有摄像头
        $camera_list = CameraList::join(
            'mine_list', 'camera_list.mine_id', '=', 'mine_list.id'
        )->where(
            [
                'camera_list.camera_source'  => CameraEnum::CAMERA_SOURCE_2,
                'camera_list.video_recorder' => CameraEnum::VIDEO_RECORDER_HK
            ]
        )->select(
            [
                'mine_list.degree',
                'camera_list.id'
            ]
        )->get()->toArray();

        //先将所有摄像头标记为在线状态
        CameraList::where(
            [
                'camera_source'  => CameraEnum::CAMERA_SOURCE_2,
                'video_recorder' => CameraEnum::VIDEO_RECORDER_HK,
            ]
        )->update(['camera_status' => CameraEnum::CAMERA_STATUS_ONLINE]);

        //循环取流
        $i = 0;
        foreach ($camera_list as $key => $val) {
            $degree = explode('|', $val->degree);
            $result = CameraServices::downloadCameraFiles($degree[0], $val->id);
            //取流成功，摄像头标记为在线，失败为离线
            if (!$result['status']) {
                CameraList::where('id', $val->id)->update(['camera_status' => CameraEnum::CAMERA_STATUS_OFFLINE]);
            }
            $i++;

            //每循环30个停止一次推流
            if ($i == 30) {
                $i = 0;
                //停止推流
                CameraServices::stopCameraStream();
                //创建目录
//                if (!is_dir('/www/wwwroot/video.nxjiewei.com/public/' . CameraEnum::M3U8_FILE_PATH . '/' . $path)) {
//                    mkdir('/www/wwwroot/video.nxjiewei.com/public/' . CameraEnum::M3U8_FILE_PATH . '/' . $path, 0777, true);
//                }
                //杀掉取流进程
                $exec = "kill -9 `ps -ef | grep ffmpeg|awk '{print $2}'`";
                shell_exec($exec);

            }
        }
    }
}
