<?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\Camera\Http\Controllers\Api\TdwyController;
use Modules\Mine\Entities\MineList;
use Modules\Mine\Entities\MineListExt;
use Modules\Mine\Services\MineServices;
use Illuminate\Support\Facades\DB;

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

    /**
     * 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()
    {
        $this->updateAreaList();
        $this->updateCameraList();
    }

    //同步区域列表
    public function updateAreaList()
    {
        //查询使用海康服务器的矿区id
        $mine_id_list = MineListExt::where('is_hak', 1)->pluck('mine_id')->all();

        foreach ($mine_id_list as $key => $val) {
            MineServices::getHaiKangArea($val, CameraEnum::REQUEST_TYPE_LOCAL);
        }
    }

    public function updateCameraList()
    {
        //海康
        //查询存在index_code列表
        $index_code_list = MineList::where('index_code', '!=', null)->get();

        foreach ($index_code_list as $key => $val) {
            $degree       = explode('|', $val->degree);
//            $trans_result = CameraServices::getHaiKangTransList($degree[0]);
            $result       = CameraServices::getHaiKangCamera($degree[0], $val->index_code, CameraEnum::CAMERA_TYPE_ALL);

            if ($result['status']) {
                $trans_arr = [];
//                foreach ($trans_result['data'] as $tk => $tv) {
//                    $trans_arr[$tv['indexCode']]['ip'] = $tv['ip'];
//                }

                $index_code_arr = [];
                $arr_count = count($result['data']);
                foreach ($result['data'] as $k => $v) {
                    $ip         = '';
                    $port       = '';
                    $com_number = '';
//                    if (isset($trans_arr[$v['trans_code']])) {
//                        $ip         = $trans_arr[$v['trans_code']]['ip'];
//                        $port       = CameraEnum::HAK_DEFAULT_PORT;
//                        $com_number = $v['com_number'];
//                    }

                    //当前摄像头index_code数组
                    $index_code_arr[$k] = $v['camera_id'];

                    $params = [
                        'mine_id'       => $val->id,
                        'camera_name'   => $this->transformCameraName($v['camera_name']),
                        'index_code'    => $v['camera_id'],
                        'revert_id'     => CameraEnum::CAMERA_DEFAULT_REVERT_ID,
                        'camera_source' => CameraEnum::CAMERA_SOURCE_2,
                        'ip'            => $ip,
                        'port'          => $port,
                        'com_number'    => $com_number,
                        'sort'          => $arr_count - $k,
                    ];
                    CameraList::updateOrCreate(['index_code' => $v['camera_id']], $params);
                }

                //删除不存在的摄像头
                CameraList::where('mine_id', $val->id)->where('index_code', '!=', NULL)->whereNotIn('index_code', $index_code_arr)->delete();
            }
        }
        //同步天地伟业摄像头
        //需要同步的矿区
        $mine_list_ext = DB::table('mine_list_ext')
            ->select('mine_list_ext.*','mine_list.parent_id')
            ->leftJoin('mine_list','mine_list.id','=','mine_list_ext.mine_id')
            ->where('mine_list.parent_id',0)
            ->where('mine_list_ext.is_hak',2)
            ->where('mine_list_ext.ip','!=','')
            ->where('mine_list_ext.port','!=','')
            ->where('mine_list_ext.key','!=','')
            ->where('mine_list_ext.secret','!=','')->get();
        if(sizeof($mine_list_ext)>0){
            for($i=0;$i<sizeof($mine_list_ext);$i++){//循环同步所有天地伟业矿区
                Input::replace(
                    [
                        'url'      => $mine_list_ext[$i]->ip.":".$mine_list_ext[$i]->port,
                        'username' => $mine_list_ext[$i]->key,
                        'password' => $mine_list_ext[$i]->secret,
                        'sysId'     => 'PG',
                        'sOrgId'   => "21dsec1d-4a27-48d1-we4c5-e44fcc23110",
                        'ip'       => $mine_list_ext[$i]->ip,
                        'port'     => $mine_list_ext[$i]->port,
                    ]
                );
                //获取设备列表
                $tdwy = new TdwyController();
                $device_list = $tdwy->queryDeviceList();
                //获取需要同步到的区域
                $mine_id = DB::table('mine_list')->where('parent_id',$mine_list_ext[$i]->mine_id)->where('deleted_at',null)->orderBy('sort','desc')->first()->id;
                //先删除需要同步区域下的所有摄像头
                DB::table('camera_list')->where('mine_id',$mine_id)->delete();
                if(sizeof($device_list['content'])>0){
                    for($j=0;$j<sizeof($device_list['content']);$j++){//循环添加所有摄像头
                        if(isset($device_list['content'][$j]['sId'])){//筛选有sId的摄像头
                            $params = [
                                'mine_id'       => $mine_id,
                                'ip'            => $mine_list_ext[$i]->ip,
                                'port'          => 1554,
                                'revert_id'     => CameraEnum::CAMERA_DEFAULT_REVERT_ID,
                                'sort'          => sizeof($device_list['content']) - $j,
                                'camera_name'   => $device_list['content'][$j]['sName'],
                                'camera_source' => CameraEnum::CAMERA_SOURCE_2,
                                'index_code'    => $device_list['content'][$j]['sId'],
                                'video_recorder'=> CameraEnum::VIDEO_RECORDER_TD,
                            ];
                            CameraList::updateOrCreate(['index_code' => $device_list['content'][$j]['sId']], $params);
                        }
                    }
                }
            }
        }
    }

    //转义摄像头名称中的特殊字符
    public function transformCameraName($camera_name)
    {
        $camera_name = trim($camera_name);
        $camera_name = str_replace('#', '号', $camera_name);
        $camera_name = str_replace(' ', '-', $camera_name);
        $camera_name = str_replace('+', '', $camera_name);
        return $camera_name;
    }
}
