<?php

namespace crmeb\services\async;

use crmeb\utils\Redis;
use crmeb\services\QyWeixinService;
use think\facade\Config;

/**
 * 异步机器人通知.
 * 消息格式:
 * {"type":"type_name", "key":"1234", "desc":{}}
 * Class WechatNotify
 */
class WechatNotify
{
    public static $TYPE_ORDER = 'order';
    public static $TYPE_REFUND = 'refund';
    public static $TYPE_WITHDRAW = 'withdraw';
    public static $TYPE_MESSAGE = 'message';
    public static $TYPE_COMPLIANT = 'compliant';
    public static $TYPE_RECHARGE = 'recharge';
    public static $TYPE_COMMENT = 'comment';

    public static function push(string $type, string $key, string $desc = '')
    {
        $r = Redis::instance();
        $rk = Config::get('app.redis_robot_msg_key');
        $arr = [
            'type' => $type,
        ];
        if ($key) {
            $arr['key'] = $key;
        }
        if ($desc) {
            $arr['desc'] = $desc;
        }

        $json = json_encode($arr);

        $r->lpush($rk, $json);
    }

    /**
     * this function should be called in timer process.
     */
    public static function notify()
    {
        $r = Redis::instance();
        $k = Config::get('app.redis_robot_msg_key');
        $aristotle = Config::get('app.qy_weixin_robot_aristotle');
        $supported_types = [
            'refund' => '退款',
            'order' => '订单',
            'compliant' => '反馈建议',
            'withdraw' => '提现请求',
            'message' => '客服消息',
            'recharge' => '充值',
            'comment' => '商品评论',
        ];
        $total = $r->llen($k);
        while ($total > 0) {
            $json = $r->rpop($k);
            $arr = json_decode($json, true);
            if (!isset($arr['type']) || !is_string($arr['type'])) {
                continue;
            }
            $type = $arr['type'];
            $key = isset($arr['key']) ? $arr['key'] : '';
            if (!isset($supported_types[$type])) {
                continue;
            }
            $desc = isset($arr['desc']) ? $arr['desc'] : '';
            $msg = $supported_types[$type];
            $md = "### 新" . $msg . "\n>key: " . $key
                . "\n备注:" . $desc;
            QyWeixinService::instance()->key($aristotle)
                ->markdown($md)->post();
            $total = $r->llen($k);
        }// while
    }//
}