<?php

namespace crmeb\services\async\task;

use crmeb\services\QyWeixinService;
use think\facade\Log;

/**
 * 异步机器人通知.
 * Class WechatNotify
 */
class WechatNotify extends Task
{
    const TYPE_ORDER        = 'order';
    const TYPE_REFUND       = 'refund';
    const TYPE_WITHDRAW     = 'withdraw';
    const TYPE_MESSAGE      = 'message';
    const TYPE_COMPLIANT    = 'compliant';
    const TYPE_RECHARGE     = 'recharge';
    const TYPE_COMMENT      = 'comment';
    const TYPE_ERROR        = 'error';

    public static function push(string $type, string $key, string $desc = '')
    {
        $inst = new self();
        return $inst->put([
            'type' => $type,
            'key'  => $key,
            'desc' => $desc,
        ]);
    }

    public function getCmd():string
    {
        return 'wechat';
    }

    /**
     * Pop task body from beanstalk and deliver to wechat robot.
     * @task: array
     * @return boolean
     */
    protected function _exec(array $params)
    {
        $supported_types = [
            self::TYPE_REFUND       => '退款',
            self::TYPE_ORDER        => '订单',
            self::TYPE_COMPLIANT    => '反馈建议',
            self::TYPE_WITHDRAW     => '提现请求',
            self::TYPE_MESSAGE      => '客服消息',
            self::TYPE_RECHARGE     => '充值',
            self::TYPE_COMMENT      => '商品评论',
            self::TYPE_ERROR        => '故障',
        ];
        if (!isset($params['type']) || !is_string($params['type'])) {
            Log::error('invalid type: bad format.');
            return false;
        }
        $type = $params['type'];
        $key = isset($params['key']) ? $params['key'] : '';
        if (!isset($supported_types[$type])) {
            Log::error('unsupported type:' . $type);
            return false;
        }
        $desc = isset($params['desc']) ? $params['desc'] : '';
        $msg = $supported_types[$type];
        $md = "### 新" . $msg . "\n "
            . "> 描述:" . $desc;
        QyWeixinService::instance()->key($key)
            ->markdown($md)->post();
            
        return true;
    }//
}