<?php

namespace common\helpers;

class DingTalk
{
    private static $webhook = 'https://oapi.dingtalk.com/robot/send?access_token=';

    private static function request_by_curl($post_string)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, self::$webhook . \Yii::$app->params['DingTalk']['accessToken']);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array ('Content-Type: application/json;charset=utf-8'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
         curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
         curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);

        return json_decode($data, true);
    }

    public static function sendNotice($message)
    {
        $message['server-ip'] = $_SERVER['HTTP_HOST'];
        $data = [
            'msgtype' => 'text',
            'text' => ['content' => $message],
            "at" => [
                'atMobiles' => \Yii::$app->params['DingTalk']['atMobiles'],
                'atUserIds' => \Yii::$app->params['DingTalk']['atUserIds'],
                'isAtAll'   => false,
            ]
        ];

        // 正式环境才发送
        if (in_array($_SERVER['HTTP_HOST'], ['ng-frontend-api.elken.com', 'ng-backend-api.elken.com'])) {
            $result = self::request_by_curl(json_encode($data));
            if ($result['errcode'] > 0) {
                // 重新推送一次,如果失败,写错误日志
                $result = self::request_by_curl(json_encode($data));
                if (!$result['errcode']) {
                    LoggerTool::error([$result, $message]);
                }
            }
        }
    }
}