<?php
/**
 * Created by PhpStorm.
 * User: chendeben
 * Date: 2017/12/6
 * Time: 11:55
 */

namespace PhpLife\Library;

class Ucm
{
    private $host = "http://10.0.11.3";
    private $token = null;

    public static $instance;

    public function __construct($is_pre = FALSE)
    {
        $this->token = self::getToken();
    }

    public static function instance()
    {
        if (!isset(self::$instance)) {
            $instance = new self();
            self::$instance = $instance;
        } else {
            $instance = self::$instance;
        }
        return $instance;
    }




    /**
     * 添加用户
     *
     * @param $data JSON    "name"：账号；<br>
    "password"：密码，需要SHA1先hash一下；<br>
    "displayName"：名字；<br>
    "email"：邮箱；<br>
    "telephone"：座机；<br>
    "cellphone"：手机；<br>
    " description ":描述信息;<br>
    " sipUserName ":SIP号码，可通过“获取空闲SIP”获取；<br>
    " sipPassword ":SIP密码;<br>
    " company ":分组id，-1表示默认分组;<br>
    " deviceType "：平台类型，目前咱们UCM2.1默认是WEB；<br>
    " status ":用户状态，0表示激活，1表示停用，2表示锁定;<br>

     * @return JSON {
    "id":132,
    "name":"lisi",
    "password":" d033e22ae348aeb5660fc2140aec35850c4da997",
    "displayName":"普通用户",
    "email":"lisi@126.com",
    "telephone":"",
    "cellphone":"13288054696",
    "description":"miaoshu",
    "sipUserName":"1040",
    "sipPassword":"182116",
    "company":-1,
    "systemManager":false,
    "status":0
    }

     */
    public function addUser($data)
    {
        $url = $this->host . '/api/rest/v2.0/users?token=' . $this->token;
        return $result = $this->post($url, $data);

    }

    /**
     *
     * 更新用户
     * @param $userid
     * @param $data JSON 参考addUser
     * @return mixed
     */
    public function updateUser($userid, $data)
    {
        $url = $this->host . '/api/rest/v2.0/users/' . $userid . '?token=' . $this->token;
        return $result = $this->put($url, $data);
    }

    /**
     * 删除用户
     * @param $userid
     * @return mixed
     */
    public function deleteUser($userid){
        $url = $this->host . '/api/rest/v2.0/users/' . $userid . '?token=' . $this->token;
        return $result = $this->delete($url);
    }

    /**
     * 获取用户列表
     * @param null $userName 不传userName则获取全部的用户
     * @return mixed
     */
    public function getUserList($userName = null)
    {
        $url = $this->host . '/api/rest/v2.0/users?token=' . $this->token;
        if ($userName) {
            $url .= "&userName=" . $userName;
        }
        return $this->get($url);
    }

    /**
     * 查看用户
     * @param $userid
     * @return mixed {
    "id":132,
    "name":"lisi",
    "password":" 7c4a8d09ca3762af61e59520943dc26494f8941b",
    "displayName":"普通用户",
    "email":"lisi@126.com",
    "telephone":"",
    "cellphone":"13288054696",
    "description":"miaoshu",
    "sipUserName":"1040",
    "sipPassword":"182116",
    "company":-1,
    "systemManager":false,
    "status":0
    }
     */
    public function getUser($userid){
        $url = $this->host . '/api/rest/v2.0/users/' . $userid . '?token=' . $this->token;
        return $result = $this->get($url);
    }
    /**
     * 添加终端
     *
     * @param $data JSON
    "systemName"：系统名称；<br>
    " endpointType "：终端型号，支持的类型：M18，M16，OTHER<br>
    "callType"：呼叫协议，支持的协议类型：SIP_URL，SIP_IP，H323_IP，H323_E164；<br>
    注意：当callType为SIP_URL时，需要输入对应的sipUrl和sipPassword的值。当callType为SIP_IP时，需要输入对应的ip的值。当callType为H323_IP时，需要输入对应的ip的值。当callType为H323_E164时，需要输入对应的e164的值。<br>
    "sipUrl"：SIP号码，可通过“获取空闲SIP”获取；<br>
    " sipPassword "：SIP密码；<br>
    " e164"：E.164号；<br>
    "ip"：IP地址；<br>
    " deviceSN "：序列号；<br>
    "description"：描述；<br>
    "callSpeed"：呼叫速率，支持0，64，96，128，192，256，320，384，512，768，832，1024，1152，1280，1472，1536，1728，1920，2048，2560，3072，3584，4096，6144；<br><br>
    " netType "：网络类型，其中intranet为内网，extranet为外网；<br>
    " cascadeRoleType "：级联，其中None表示无级联；<br>
    " dialDirection "：呼叫方向，支持的类型：Dial-in，Dial-out；<br>
     * @return JSON {
    "id":184,
    "name":"longriver",
    "endpointType":"M16",
    " callType ":" SIP_URL ",
    "sipUrl":"1020",
    "sipPassword":"124601",
    "deviceSN":"4556662112",
    "description":"00000000",
    "callSpeed":128,
    "netType":"intranet",
    "cascadeRoleType":"None",
    "dialDirection":"Dial-in"
    }


     */
    public function addEndPoints($data)
    {
        $url = $this->host . '/api/rest/v2.0/endpoints?token=' . $this->token;
        return $result = $this->post($url, $data);

    }
    /**
     *
     * 更新用户
     * @param $endpointId
     * @param $data JSON 参考addEndPoints()
     * @return mixed
     */
    public function updateEndPoints($endpointId, $data)
    {
        $url = $this->host . '/api/rest/v2.0/endpoints/' . $endpointId . '?token=' . $this->token;
        return $result = $this->put($url, $data);
    }

    /**
     * 删除用户
     * @param $endpointId
     * @return mixed
     */
    public function deleteEndPoints($endpointId){
        $url = $this->host . '/api/rest/v2.0/endpoints/' . $endpointId . '?token=' . $this->token;
        return $result = $this->delete($url);
    }


    /**
     * 获取终端列表
     * @param $query array 查询条件，不指定条件则获取所有<br>
     * token	已登陆令牌<br>
    startTime	时间段起点，取值0即可。<br>
    endTime	时间段终点，系统当前时间即可。<br>
    isIncludeViseeTerminal	结果里是否包含app注册的终端，web端默认是true<br>
    endpointStatue	指定终端的状态（0：离线，1：在线，5：通话）<br>
    endpointType	指定终端类型（M18，M16，OTHER，HEXMEET）<br>
    endpointText	根据终端名称，序列号，IP地址，SIP号码或E.164查询匹配终端<br>

     * @return mixed
     */
    public function getEndPointsList($query=array())
    {
        $url = $this->host . '/api/rest/v2.0/endpoints?token=' . $this->token;
        if ($query) {
            $url .= '&'.http_build_query($query);
        }
        return $this->get($url);
    }

    /**
     * 查看用户
     * @param $endpointId
     * @return mixed {
    "id":184,
    "name":"longriver",
    "endpointType":"M16",
    " callType ":" SIP_URL ",
    "sipUrl":"1020",
    "sipPassword":"124601",
    "deviceSN":"4556662112",
    "description":"0000000012",
    "callSpeed":128,
    "netType":"intranet",
    "cascadeRoleType":"None",
    "dialDirection":"Dial-in",
    " available ":"true
    }
     */
    public function getEndPoints($endpointId){
        $url = $this->host . '/api/rest/v2.0/endpoints/' . $endpointId . '?token=' . $this->token;
        return $result = $this->get($url);
    }

    /**
     *
     * 预约会议
     * @param $data String "startTime"：会议开始时间，从1970-01-01 00:00:00开始的毫秒数；<br>
    "duration"：以毫秒计数的会议时长；<br>
    " name ":会议名称；<br>
    " confPassword ":会议密码；<br>
    "confDefinition":会议类型，支持FHD，HD，SD，HDRECORDING，WEBCAST，BROADCAST；<br>
    " remarks ":备注信息；<br>
    "layout"：会议分屏，可以为：0X0，1x1，1x2，2x1，2x2，1and5，3x3，1x2Ver，1x2Hor，1and2Hor，1and2Ver，1and3Hor，1and3Ver，1and4Hor，1and4Ver，1and8Central，1and8Upper，1and2HorUpper，1and3HorUpper，1and4HorUpper，1and8Lower，1and7，1x1Qcif，4x4，2and8，1and12；<br><br>
    " userIds ":预约用户列表；<br>
    " confType ":入会方式，ucm2.1默认与会方式TRADITIONAL；<br>
    " maxBandwidth ":最大宽带；<br>
    " autoRedialing ":自动重拨，true和false；<br>
    " endpointIds ":预约终端列表信息，可由获取终端列表获取。<br>
    " masterEndpointId ":主会场；<br>

     * @return mixed
     */
    public function meetings($data){
        $url = $this->host . '/api/rest/v2.0/meetings?token=' . $this->token;
        if (is_array($data)){
            $data=json_encode($data);
        }
        return $this->post($url, $data);
    }
    /**
     * 获取空闲sip号码
     * @return bool|string
     */
    public function getFreeSip()
    {
        $url = $this->host . '/api/rest/v2.0/idleSipNumber?token=' . $this->token;
        $result = $this->get($url);
        return $result['sipUrl'];

    }

    /**
     * 获取token
     * @return string
     */
    private function getToken()
    {
        $url = $this->host . "/api/rest/v2.0/login";
        $data['account'] = "admin";
        $data['password'] = sha1("meitutestCOM");
        $data['deviceType'] = "WEB";
        $post = json_encode($data);
        $result = $this->put($url, $post);
        return $result['token'];

    }

    /**
     * put
     * @param $url
     * @param $data
     * @return mixed
     */
    private function put($url, $data)
    {
        if (is_array($data)){
            $data=json_encode($data);
        }
        $ch = curl_init(); //初始化CURL句柄
        curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //设为TRUE把curl_exec()结果转化为字串，而不是直接输出
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT"); //设置请求方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }

    /**
     *
     * post
     * @param $url
     * @param $data
     * @return mixed
     */
    private function post($url, $data)
    {
        if (is_array($data)){
            $data=json_encode($data);
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($ch, CURLOPT_URL, $url); // 设置链接
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置是否返回信息
        curl_setopt($ch, CURLOPT_POST, 1); // 设置为POST方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $response = curl_exec($ch); // 接收返回信息
        $error = curl_error($ch);
        if ($error) {
            print_r($error);
        }
        $result = json_decode($response, true);
        curl_close($ch);

        return $result;
    }

    /**
     * @param $url
     * @return mixed
     */
    private function get($url)
    {
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }

    /**
     * delete
     * @param $url
     * @return mixed
     */
    private function delete($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }
}