<?php
namespace common\helpers;

use Yii;

/**
 * Class TaobaoApiHelper
 * @see https://api.alidayu.com/apitools/errorCodeSearch 错误码自查工具
 * @package common\helpers
 */
class TaobaoApiHelper
{
    public $serverUrl = 'http://gw.api.taobao.com/router/rest';
    public $appKey = '24485139';
    public $appSecret = 'd25ebf9219bdfdb3619750fc2ee40153';

    public function __construct($config = [])
    {
        foreach ($config as $k => $v) {
            $this->$k = $v;
        }
    }

    /**
     * 发送短信验证码
     * 
     * 短信模板在控制台设置，当前的短信模板为
     * 【爱客】您的手机验证码为：9270，请妥善保管。感谢您对爱客的支持，老品牌，更放心。
     * 
     * 接口返回值
     * {"result":{"err_code":"0","model":"219507513930394625^0","msg":"OK","success":true},"request_id":"10wc6gxcw1abj"}
     * 
     * 当前设置每小时上限为5条，超过的话返回
     * {"code":15,"msg":"Remote service error","sub_code":"isv.BUSINESS_LIMIT_CONTROL","sub_msg":"\u89e6\u53d1\u5c0f\u65f6\u7ea7\u6d41\u63a7Permits:5","request_id":"ishbr0xnhhuk"}
     * 错误原因：触发业务流控限制
     * 解决方案：短信验证码，使用同一个签名，对同一个手机号码发送短信验证码，支持1条/分钟，5条/小时，10条/天。一个手机号码通过阿里大于平台只能收到40条/天。 短信通知，使用同一签名、同一模板，对同一手机号发送短信通知，允许每天50条（自然日）。
     * 
     * 
     * @param string $mobile
     * @param string $code
     * @return array
     * @see https://api.alidayu.com/doc2/apiDetail?apiId=25450 阿里大于API短信发送文档
     * @see https://dysms.console.aliyun.com/dysms.htm 控制台地址
     */
    public function sendSmsCode($mobile, $code)
    {
        require_once Yii::$app->getVendorPath() . '/taobao-sdk/TopSdk.php';

        $c = new \TopClient();
        $c->appkey = $this->appKey;
        $c->secretKey = $this->appSecret;
        $c->gatewayUrl = $this->serverUrl;
        $c->format = 'json';
        $c->checkRequest = false;

        $req = new \AlibabaAliqinFcSmsNumSendRequest();

        $req->setExtend("");
        $req->setSmsType("normal"); // 固定为normal
        $req->setSmsFreeSignName("爱客"); // 签名，即书名号里的文字
        $req->setSmsParam('{"number":"' . $code . '"}'); // 替换模板里的变量
        $req->setRecNum($mobile); // 手机号码
        $req->setSmsTemplateCode("SMS_73825029"); // 短信模板，在控制台申请
        $resp = $c->execute($req);

        $result = $this->getResult($resp);
        return $result;
    }
    
    /**
     * 处理结果
     * @param object $resp
     * @return array
     * 接口成功的返回值
     * {"result":{"err_code":"0","model":"219507513930394625^0","msg":"OK","success":true},"request_id":"10wc6gxcw1abj"}
     * 错误的返回值
     * {"code":15,"msg":"Remote service error","sub_code":"isv.BUSINESS_LIMIT_CONTROL","sub_msg":"\u89e6\u53d1\u5206\u949f\u7ea7\u6d41\u63a7Permits:1","request_id":"ej6jo9wcr62n"}
     */
    protected function getResult($resp)
    {
        $code = isset($resp->result->success) && $resp->result->success == true ? 1 : 0;
        $message = isset($resp->result->msg) ? $resp->result->msg : (isset($resp->sub_msg) ? $resp->sub_msg : '');

        if (!$code) {
            Yii::warning(json_encode($resp), __METHOD__);
        }
        
        return ['code' => $code, 'message' => $message];
    }
}