<?php
/**
 * Created by PhpStorm.
 * User: rlgyzhcn
 * Date: 18-6-27
 * Time: 下午12:04
 */

namespace common\business;

use common\models\pwallet\Coin;
use common\service\exchange\ExchangeFactory;
use common\service\coin\CoinFactory;

/**
 * Class ExchangeBusiness
 * 各大交易所交易所api逻辑层
 * @package common\business
 */
class ExchangeBusiness
{
    /**支持的交易所
     * @var array
     */
    private static $exchanges = [
        0 => 'HuoBi',
        1 => 'Hadax',
        2 => 'Bitfinex',
        3 => 'Bittrex',
        4 => 'Zb',
    ];

    /**
     * 获取行情
     * @param string $tag 目标币种
     * @param string $aim 计数币种
     * @return array|bool
     */
    public static function getquatation($tag = 'btc', $aim = '')
    {
        $f         = false;
        $quotation = [];
        foreach (self::$exchanges as $exchange) {
            /**
             * @var $exchange \common\service\exchange\Exchange
             */
            $exchange = ExchangeFactory::createExchange($exchange);
            if ($exchange->symbolExists($tag)) {
                $quotation = $exchange->getTicker($tag);
                $f         = true;
                break;
            }
        }
        if (!$f) {
            //所有交易所都不能直接获取交易对的行情就通过BTC去转换
            //获取BTC_USD
            $btc_usd = ExchangeFactory::createExchange(self::$exchanges[0])->getTicker('btc');
            foreach (self::$exchanges as $exchange) {
                /**
                 * @var $exchange \common\service\exchange\Exchange
                 */
                $exchange = ExchangeFactory::createExchange($exchange);
                if ($exchange->symbolExists($tag, 'btc')) {
                    $price_btc = $exchange->getTicker($tag, 'btc');
                    //获取btcusdt
                    $result    = array_map(function ($a, $b) {
                        return $a * $b;
                    }, $price_btc, $btc_usd);
                    $quotation = ['low' => $result[0], 'high' => $result[1], 'last' => $result[2]];
                    $f         = true;
                    break;
                }
            }
        }
        if (!$f || empty($quotation)) {
            return false;
        }
        //格式化行情数据
        foreach ($quotation as $key => $item) {
            $quotation[$key] = (float)sprintf("%0.4f", (double)$item);
        }
        $quotation['rmb'] = (float)sprintf("%0.2f", 6.6 * $quotation['last']);
        return $quotation;
    }

    /**
     * 保存各个交易所支持的交易对到redis,定时用crontab更新
     * @return void
     */
    public static function setSupportedSymbol()
    {
        foreach (self::$exchanges as $exchange) {
            /**
             * @var $exchange \common\service\exchange\ExchangeInterface
             */
            $exchange = ExchangeFactory::createExchange($exchange);
            $exchange->setSupportedSymbol();
        }
    }

    /**
     * 更新交易所的行情数据保存到redis,定时更新
     * @return void
     */
    public static function setQuotation()
    {
        foreach (self::$exchanges as $exchange) {
            /**
             * @var $exchange \common\service\exchange\ExchangeInterface
             */
            $exchange = ExchangeFactory::createExchange($exchange);
            $exchange->setQuotation();
        }
    }

    /**
     * 根据name返回币种信息
     * @param array $condition 需要的币种sid列表
     * @return array
     */
    public static function getApiListForIndex($page = 1, $limit = 999, $condition = [])
    {
        $rows  = Coin::getSelectList($page, $limit, ['id', 'sid', 'icon', 'name', 'nickname', 'platform', 'chain'], $condition);
        $count = 0;
        if (!empty($rows) && is_array($rows) && array_key_exists('count', $rows)) {
            $count = $rows['count'];
        }
        if ($rows['count'] > 0) {
            $rows = $rows['data'];
            foreach ($rows as $key => $row) {
                $rows[$key]['sid'] = ucfirst($rows[$key]['sid']);
                $quotation         = self::getquatation($row['name']);
                if (!$quotation) {
                    $quotation = [];
                    //使用Coin服务
                    try {
                        $coinServer        = CoinFactory::createCoin($row['name'], $row['id'], $row['sid']);
                        $rows[$key]['sid'] = ucfirst($rows[$key]['sid']);
                        $rows[$key]['rmb']  = $coinServer->getPrice();
                        $rows[$key]['last'] = $coinServer->getDollar();
                        $rows[$key]['low']  = $coinServer->getLow();
                        $rows[$key]['high'] = $coinServer->getHigh();
                        $coinServer->__destruct();
                    } catch (\Exception $exception) {
                        $rows[$key]['rmb']  = 0;
                        $rows[$key]['last'] = 0;
                        $rows[$key]['low']  = 0;
                        $rows[$key]['high'] = 0;
                        \Yii::error($exception->getMessage());
                    }
                }
                $rows[$key] = array_merge($rows[$key], $quotation);
            }
            return ['code' => 0, 'count' => $count, 'data' => $rows];
        }
        return [];
    }

    /**
     * 根据名称搜索
     * @param int $page
     * @param int $limit
     * @param array $condition
     * @return array|\yii\db\ActiveRecord|\yii\db\ActiveRecord[]
     */
    public static function SearchByName($page = 1, $limit = 10, $condition = [])
    {
        $rows = Coin::getSelectList($page, $limit, ['id', 'sid', 'icon', 'name', 'nickname', 'platform', 'chain'], $condition);
        if ($rows['count'] > 0) {
            $rows = $rows['data'];
            foreach ($rows as $key => $row) {
                $rows[$key]['sid'] = ucfirst($rows[$key]['sid']);
            }
            return $rows;
        }
        return [];
    }
}