<?php
/**
 * Created by PhpStorm.
 * User: qiuzijian
 * Date: 3/17/22
 * Time: 7:01 PM
 */

namespace Modules\Camera\Http\Controllers\Api;

use App\Http\Controllers\Api\BaseController;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Input;
use Modules\Camera\Enum\CameraEnum;
use Modules\Mine\Entities\MineList;
use Modules\Mine\Services\MineServices;


class TdwyController extends BaseController
{
    protected $pre_url;   // 请求地址
    protected $username;  // 请求username
    protected $password;  // 请求password
    protected $sysId;     // 请求sysId
    protected $token;     // 请求sysId

    public function __construct()
    {
        $this->pre_url  = Input::get('url');
        $this->username = Input::get('username');
        $this->password = Input::get('password');
        $this->sysId    = Input::get('sysId');

        //先获取token
        $this->token = $this->loginUser();
    }

    //登录获取token
    protected function loginUser()
    {
        $url = '/pangu/sdkServer/user/loginUser';

        $params = [
            'username' => $this->username,
            'password' => $this->password,
            'sysId'    => $this->sysId,
        ];

        $result = $this->curlPost($this->pre_url . $url, json_encode($params));

        $result = json_decode($result, true);

        $token = '';
        if (Cache::has(CameraEnum::TDWY_TOKEN_CACHE)) {
            $token = Cache::get(CameraEnum::TDWY_TOKEN_CACHE);
            return $token;
        }

        if ($result['statusCode'] == CameraEnum::TDWY_API_STATUS_CODE_SUCCSS && $result['content']) {
            $token = $result['content']['token'];
            Cache::put(CameraEnum::TDWY_TOKEN_CACHE, $token, 1440);
        }

        return $token;
    }

    //查询设备列表
    public function queryDeviceList()
    {
        $url = '/pangu/sdkServer/device/queryDeviceList';

        $sOrgId       = Input::get('sOrgId', '');
        $iDeviceTypes = Input::get('iDeviceTypes', [5]);
        $rootCodes    = Input::get('rootCodes', ["BH-0001"]);
        $isOrgTree    = Input::get('isOrgTree', true);
        $orgTypeIds   = Input::get('orgTypeIds', []);
        $needPage     = Input::get('needPage', true);
        $pageSize     = Input::get('pageSize', 50);
        $currentPage  = Input::get('currentPage', 1);

        $params = [
            'sOrgId'       => $sOrgId,
            'iDeviceTypes' => $iDeviceTypes,
            'rootCodes'    => $rootCodes,
            'isOrgTree'    => $isOrgTree,
            'orgTypeIds'   => $orgTypeIds,
            'needPage'     => $needPage,
            'pageSize'     => $pageSize,
            'currentPage'  => $currentPage,
        ];

        $result = $this->curlPost($this->pre_url . $url, json_encode($params));

        $result = json_decode($result, true);

        return $result;
    }

    //查询设备rtsp流
    public function getRtspById()
    {
        $url = '/pangu/sdkServer/videoStreaming/getRtspById';

        $sId  = Input::get('sId', []);
        $ip   = Input::get('ip', '');
        $port = Input::get('port', '');
        $type = Input::get('type', 0);

        $params = [
            'sId'  => $sId,
            'ip'   => $ip,
            'port' => $port,
            'type' => $type
        ];

        $result = $this->curlPost($this->pre_url . $url, json_encode($params));

        $result = json_decode($result, true);

        return $result;
    }

    //查询区域列表
    public function getRegionByOrgId(){
        $url = '/pangu/sdkServer/OrgManager/queryOrgList';
        $parentOrgIds  = Input::get('parentOrgIds', []);
        $params = [
            'querySingleType'  => true,
            'needPage'  => false,
            'currentPage'  => 1,
            'pageSize'  => 10,
            'parentOrgIds'  => $parentOrgIds,
            'queryType'   => 0,
        ];
        $result = $this->curlPost($this->pre_url . $url, json_encode($params));
        $result = json_decode($result, true);
        return $result;
    }

    //天地伟业获取区域列表
    public function saveTrees($regions, $parent_id)
    {
        $arr = [];
        if (empty($regions['content'])) {
            return [];
        }

        $mineService = new MineServices();
        $mineService->initMineList();

        $arr_count = $regions['count'];

        foreach ($regions['content'][0]['data'] as $key => $value) {

            $arr[$key]['parentOrgId']       = $value['parentOrgId'];
            $arr[$key]['orgId']             = $value['orgId'];
            $arr[$key]['name']              = str_replace('#', '号', $value['orgName']);

            $id      = MineList::where('index_code', $value['orgId'])->value('id');

            $params  = [
                'id'         => $id,
                'parent_id'  => $parent_id,
                'title'      => $value['orgName'],
                'sort'       => $arr_count - $key,
                'index_code' => $value['orgId'],
            ];

            $result  = $mineService->add($params);

            $mine_id = $result->id;

            Input::replace(
                [
                    'parentOrgIds'   => $value['orgId'],
                    'url'      => Input::get('url', ''),
                    'username' => Input::get('username', ''),
                    'password' => Input::get('password', ''),
                    'sysId'     => 'PG',

                ]
            );

            $region_child = $this->getRegionByOrgId();

            $arr[$key]['children'] = self::saveTrees($region_child, $mine_id);
            if (count($arr[$key]['children']) == 0) {
                unset($arr[$key]['children']);
            }

        }

        return array_values($arr);
    }

    /**
     * 发送请求
     * @param string $url
     * @param string $postData
     * @return bool|string
     */
    public function curlPost($url = '', $postData = '')
    {
        if (is_array($postData)) {
            $postData = http_build_query($postData);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //设置cURL允许执行的最长秒数

        curl_setopt_array($ch, array(
            CURLOPT_HTTPHEADER => array(
                "Accept:" . '*/*',
                "Content-Type:" . 'application/json',
                "token:" . $this->token,
            )
        ));

        //https请求 不验证证书和host
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
}