<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Input;
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\Enum\MineEnum;
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);
        }

        //同步天地伟业矿区区域
        $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',MineEnum::IS_HAK_TD)
            ->where('mine_list_ext.ip','!=','')
            ->where('mine_list_ext.port','!=','')
            ->where('mine_list_ext.key','!=','')
            ->where('mine_list_ext.secret','!=','')
            ->where('mine_list_ext.deleted_at',null)->get();

        if(sizeof($mine_list_ext)>0){
            for($i=0;$i<sizeof($mine_list_ext);$i++){//循环同步所有天地伟业矿区

                Input::replace(
                    [
                        'parentOrgIds'   => $mine_list_ext[$i]->sOrgId,
                        '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',
                    ]
                );
                $tdwy = new TdwyController();
                $region = $tdwy->getRegionByOrgId();
                $mine_id = $mine_list_ext[$i]->mine_id;
                //更新区域
                $result['data']['list'] = $tdwy->saveTrees($region, $mine_id);
                //dd($result['data']['list']);
            }
        }

    }

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

        //去掉洗选
//        foreach($index_code_list as $k=>$v){
//            $degree = explode('|',$v->degree);
//            if($degree[0] == 66){
//                unset($index_code_list[$k]);
//            }
//        }

        //天地伟业矿区
        $mine_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',MineEnum::IS_HAK_TD)
            ->where('mine_list_ext.ip','!=','')
            ->where('mine_list_ext.port','!=','')
            ->where('mine_list_ext.key','!=','')
            ->where('mine_list_ext.secret','!=','')
            ->where('mine_list_ext.deleted_at',null)->get();

        $mine_id_list = [];
        foreach($mine_ext as $k=>$v){
            $mine_id_list[$k] = $v->mine_id;
        }
        //清除天地伟业的区域
        if(count($mine_id_list) > 0){
            foreach($index_code_list as $k=>$v){
                if(in_array(explode('|',$v->degree)[0],$mine_id_list)){
                    unset($index_code_list[$k]);
                }
            }
        }

        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',MineEnum::IS_HAK_TD)
            ->where('mine_list_ext.ip','!=','')
            ->where('mine_list_ext.port','!=','')
            ->where('mine_list_ext.key','!=','')
            ->where('mine_list_ext.secret','!=','')
            ->where('mine_list_ext.deleted_at',null)->get();

        if(sizeof($mine_list_ext)>0){
            for($i=0;$i<sizeof($mine_list_ext);$i++){//循环同步所有天地伟业矿区
                //矿区下所有区域
                $mine_list = DB::table('mine_list')
                    ->where('degree','like',$mine_list_ext[$i]->mine_id.'|%')
                    ->where('index_code','!=',null)->get();
                foreach($mine_list as $k=>$v){
                    $mine_id = $v->id;
                    Input::replace(
                        [
                            'parentOrgIds'   => $v->index_code,
                            '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',
                        ]
                    );
                    //获取区域下的子区域
                    $tdwy = new TdwyController();
                    $region = $tdwy->getRegionByOrgId();

                    //获取最底层区域摄像头列表
                    if (empty($region['content'])) {
                        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'   => $v->index_code,
                                'ip'       => $mine_list_ext[$i]->ip,
                                'port'     => $mine_list_ext[$i]->port,
                            ]
                        );
                        //获取设备列表
                        $tdwy = new TdwyController();
                        $device_list = $tdwy->queryDeviceList();
                        $device_index_code = [];
                        //删除区域下所有摄像头
//                        DB::table('camera_list')->where('mine_id',$v->id)->delete();
                        if(isset($device_list['content']) && 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'       => $v->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);
                                }
                                $device_index_code[$j] = $device_list['content'][$j]['sId'];
                            }
                        }
                        //删除不存在的摄像头
                        CameraList::where('mine_id', $mine_id)->where('index_code', '!=', NULL)->whereNotIn('index_code', $device_index_code)->delete();
                    }
                }
            }
        }
    }

    //转义摄像头名称中的特殊字符
    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;
    }
}
