<?php
namespace Helpers;

use Api\PhpUtils\Log\Tracer;

/**
 * DingTalk 获取接口
 */
class DingTalk {

    public static function send($title, $text = '') {

        $tokens = \Yaf\Application::app()->getConfig()->get('dingTalk.tokens');
        $keys = \Yaf\Application::app()->getConfig()->get('dingTalk.keys');

        $len = count($tokens);
        $idx = rand(1, 9999) % $len;

        $hook_url = "https://oapi.dingtalk.com/robot/send?access_token=" . $tokens[$idx];
        $t = time() * 1000;
        $ts = $t."\n".$keys[$idx];

        $sig = hash_hmac('sha256', $ts, $keys[$idx], true);
        $sig = base64_encode($sig);
        $sig = urlencode($sig);

        $text = '#### **' . $title . "** \n -------- \n "
            . 'time: ' . date("Y-m-d H:i:s"). " \n -------- \n "
            . 'traceId: ' . Tracer::getTraceId() . " \n -------- \n "
            . $text;
        $data_string = json_encode([
            'msgtype' => 'markdown',
            'markdown' => [
                'title'=>$title ,
                'text' => $text]
        ]);

        $url = $hook_url.'&timestamp='.$t.'&sign='.$sig;
        $result = self::post($url, $data_string, ['Content-Type: application/json']);

        return array('code' => 0, 'msg' => 'success', 'result' => $result );
    }

    public static function post($url, $params, $headers = [], $timeout_ms = 1000) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($headers) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }

        curl_setopt($ch, CURLOPT_FAILONERROR, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TCP_NODELAY, true);
        curl_setopt($ch, CURLOPT_NOSIGNAL, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_BUFFERSIZE, 10240);
        curl_setopt($ch, CURLOPT_TIMEOUT_MS, $timeout_ms);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, $timeout_ms);
        //curl_setopt($ch, CURLOPT_HTTP_VERSION,          CURL_HTTP_VERSION_1_0);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $res = curl_exec($ch);

        $curl_errno = curl_errno($ch);
        $curl_error = curl_error($ch);

        echo $res;
        curl_close($ch);

        if (empty($curl_errno)) {
            return json_decode($res, true);
        } else {
            return ["code" => $curl_errno, "status" => "failed", "reason" => $curl_error];
        }
    }
}