<?php

namespace app\common\library;


class Getui
{
    protected  $base_uri = "https://restapi.getui.com/v2/";
    private    $appId;
    private    $appKey;
    private    $appSecret;
    private    $masterSecret;

    public function __construct()
    {
        $config = config('getui');
        $this->appId        = $config['gt_app_id'];
        $this->appKey       = $config['gt_app_key'];
        $this->appSecret    = $config['gt_app_secret'];
        $this->masterSecret = $config['gt_master_secret'];
    }

    //创建消息
    //type = 1 安卓
    //type = 2 苹果
    public function sendtoall($title,  $body, $type = 1,$platform = 'android'){
        if (!$access_token = $this->auth()) {
            return $this->error('ge tui token error');
        }

        // 通知
        $notification = [
            "notification"=> [
                "title"=> $title,
                "body" => $body,
                "click_type"=> "url",
                "url"=> "https//:xxx"
            ],
        ];

        // 透传
        $transmission = [
            'transmission' => json_encode([
                "title"=> $title,
                "body" => $body,
                "t"     => time(),
            ]),
        ];


        if ($type == 1) {
            $push_message = $notification;
        } else {
            $push_message = $transmission;
        }

        $push_channel = [];
        if ($platform == 'ios') {
            $push_channel = [
                "ios" => [
                    "type"       => "notify",
                    "payload"    => json_encode([
                        "title" => $title,
                        "body"  => $body,
                    ], JSON_UNESCAPED_UNICODE),
                    "aps"        => [
                        "alert"             => [
                            "title" => $title,
                            "body"  => $body,
                        ],
                        "content-available" => 0,
                        "sound"             => "default",
                        "category"          => "ACTIONABLE",
                    ],
                    "auto_badge" => "+1",
                ]
            ];
            $push_message = $transmission;
        }

        $data = [
            "request_id"=> createUniqueNo('PA'),
            "group_name"=> "",
            "settings"=> [
                "ttl"=> 7200000
            ],
            "audience"=> "all",
            "push_message"=> $push_message,
        ];
        if ($platform == 'ios') {
            $data['push_channel'] = $push_channel;
        }


        $response = $this->post('/push/all', $data, [
            'token:'.$access_token
        ]);

        //dump($response);
        $data = json_decode($response, true);


    }

    /**
     * 消息推送
     * @param string $cid 设备ID
     * @param string $title 消息标题
     * @param string $body 消息内容
     * @param int $type 1=通知,2=透传
     * @param string $platform 平台
     * @return bool
     */
    public function push( $cid,  $title,  $body, $ring_name, $type = 1,  $platform = 'android')
    {
        if (!$access_token = $this->auth()) {
            return $this->error('ge tui token error');
        }
        // 通知
        $notification = [
            "notification" => [
                "title"         => $title,
                "body"          => $body,
                "ring_name"     => $ring_name,
                "channel_level" => 4,
                "click_type"    => "startapp",//startapp:打开应用首页,payload:自定义消息内容启动应用,
                "payload"       => json_encode(['t' => time()])
            ],
        ];

        // 透传
        $transmission = [
            "transmission" => json_encode([
                "title" => $title,
                "body"  => $body,
                "t"     => time(),
            ], JSON_UNESCAPED_UNICODE)
        ];

        if ($type == 1) {
            $push_message = $notification;
        } else {
            $push_message = $transmission;
        }

//        if ($platform == 'android') {
//            $notify = $this->send($cid, $notification, $access_token, $push_channel ?? []);
//            $trans  = $this->send($cid, $transmission, $access_token, $push_channel ?? []);
//            if (!$notify || !$trans) {
//                return false;
//            }
//            return true;
//        }

        if ($platform == 'ios') {
            $push_channel = [
                "ios" => [
                    "type"       => "notify",
                    "payload"    => json_encode([
                        "title" => $title,
                        "body"  => $body,
                    ], JSON_UNESCAPED_UNICODE),
                    "aps"        => [
                        "alert"             => [
                            "title" => $title,
                            "body"  => $body,
                        ],
                        "content-available" => 0,
                        "sound"             => "com.gexin.ios.silence",
                        "category"          => "ACTIONABLE",
                    ],
                    "auto_badge" => "+1",
                ]
            ];
        }

        return $this->send($cid, $push_message, $access_token, $push_channel ?? []);
    }

    /**
     * 发送
     * @param $cid
     * @param $push_message
     * @param $access_token
     * @return bool
     */
    private function send($cid, $push_message, $access_token, $push_channel)
    {
        $params = [
            'request_id'   => createUniqueNo('GT'),
            'settings'     => [
                "ttl" => 7200000
            ],
            "audience"     => [
                "cid" => [
                    $cid
                ]
            ],
            "push_message" => $push_message
        ];

        if (!empty($push_channel)) {
            $params['push_channel'] = $push_channel;
        }

        $response = $this->post('/push/single/cid', $params, [
            'token:'.$access_token
        ]);
        dump($response);
        /*if ($response->getStatusCode() != 200) {
            return $this->error($response->getReasonPhrase());
        }
        $json = $response->getBody()->getContents();
        $body = json_decode($json, true);
        return $this->success('操作成功', $body);*/
    }

    /**
     * 获取token
     * @return false|mixed
     */
    public function auth()
    {
        $timestamp = $this->ms_time();
        $response  = $this->post('/auth', [
            'sign'      => hash('sha256', "{$this->appKey}{$timestamp}{$this->masterSecret}"),
            'timestamp' => $timestamp,
            'appkey'    => $this->appKey
        ]);
        $data = json_decode($response, true);

        $auth = isset($data['data']['token']) ? $data['data']['token'] : '';
        return $auth;
    }

    private function post( $uri,  $params = [],  $header = [])
    {
        $common_header = ["Content-Type:application/json;charset=UTF-8","Connection: Keep-Alive"];
        $header = array_merge($header,$common_header);

        $url = $this->base_uri.$this->appId.$uri;
        return curl_post($url,json_encode($params),$header);
    }

    private function ms_time()
    {
        list($ms, $sec) = explode(' ', microtime());
        return intval((floatval($ms) + floatval($sec)) * 1000);
    }


}