<?php
namespace crmeb\services;

/**
 * 使用
 *      $key = Config::get('app.qy_weixin_robot_aristotle');
 *      $svc = QyWeixinService::instance();
 *      $svc->key($key)->markdown("### good\n>hhhh")->post();
 *
 * Class QyWeixinService
 * @package crmeb\services
 */
class QyWeixinService {
    // api addr
    protected $addr = 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=';

    // robot key
    protected $key = '';
    protected $content = '';
    protected $msgtype = 'text';

    protected static $inst = null;

    public static function instance()
    {
        if (is_null(self::$inst)) {
            self::$inst = new self();
        }
        return self::$inst;
    }

    /**
     * 指定 key, 一个 key 对应一个机器人
     */
    public function key(string $key)
    {
        $this->key = $key;
        return $this;
    }

    /**
     * 发送文本消息
     */
    public function text(string $text)
    {
        $this->msgtype = 'text';
        $this->content = $text;
        return $this;
    }

    /**
     * # title
     * ###### title6
     * **bold**
     * [link](url)
     * `code`
     * > refer
     * <font color="info"/"comment"/"warning">words</font>
     * @param string $md markdown text
     * @return $this
     */
    public function markdown(string $md)
    {
        $this->msgtype = 'markdown';
        $this->content = $md;
        return $this;
    }

    public function post()
    {
        $data = [
            'msgtype' => $this->msgtype,
            $this->msgtype => [
                'content' => $this->content,
            ],
        ];
        $url = $this->addr . $this->key;
        $ret = json_decode(self::post_json($url, $data), true);
        //$ret = json_decode(HttpService::postRequest($url, $data), true);
        return isset($ret['errcode']) && $ret['errcode'] == 0;
    }

    public static function post_json(string $url, array $data, array $headers=[], int $timeout=15)
    {
        $h = curl_init();
        curl_setopt($h, CURLOPT_URL, $url);
        curl_setopt($h, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($h, CURLOPT_POST, true);
        if ($headers && count($headers) > 0) {
            curl_setopt($h, CURLOPT_HTTPHEADER, $headers);
        }
        if ($timeout > 0) {
            curl_setopt($h, CURLOPT_CONNECTTIMEOUT, $timeout);
            curl_setopt($h, CURLOPT_TIMEOUT, $timeout);
        }
        $js = json_encode($data);
        curl_setopt($h, CURLOPT_POSTFIELDS, $js);
        $ret = curl_exec($h);
        curl_close($h);
        return $ret;
    }
}
