<?php
namespace common\helpers;

use Yii;
use yii\httpclient\Client;
use yii\redis\Connection;

class RateHelper
{
    const RATE_URL = 'http://web.juhe.cn:8080/finance/exchange/rmbquot?key=05806e7b15ebbab91c1babceed3b468a';
    const RATE_CACHE_KEY = 'usdRate';

    /**
     * 获取入金 出金汇率
     * @param bool $refresh
     * @return mixed
     */
    public static function getRate($refresh = false)
    {
        $usdRate = Yii::$app->getCache()->get(self::RATE_CACHE_KEY);
        if ($usdRate == false || $refresh == true) {
            $client = new Client();
            $success = false;
            for ($i = 0; $i < 2; $i++) {
                $response = $client->get(self::RATE_URL, [], ['Referer' => 'web.juhe.cn'])->send();
                if ($response->getIsOk()) {
                    $json = $response->getContent();
                    $jsonArr = @json_decode($json, true);
                    if ($jsonArr['error_code'] == 0 && !empty($jsonArr['result'][0])) {
                        foreach ((array)$jsonArr['result'][0] as $dataKey => $dataRow) {
                            if ($dataRow['name'] == '美元') {
                                $usdRate['buyRate'] = number_format(round($dataRow['fBuyPri'] / 100, 3), 3, '.', '');
                                $usdRate['sellRate'] = number_format(round($dataRow['fSellPri'] / 100, 3), 3, '.', '');
                                Yii::$app->getCache()->set(self::RATE_CACHE_KEY, $usdRate, 3600);
                                $success = true;
                                break;
                            }
                        }
                    }
                }
                if ($success == true) {
                    break;
                }
                usleep(50000); // sleep 50ms
            }
        }
        return $usdRate;
    }

    /**
     * @return null|Connection
     */
    protected static function getRedis()
    {
        return Yii::$app->get('redis');
    }
}