<?php

namespace App\Modules\Trade\Pay;

use App\Modules\User\Services\ReadRecordService;
use Hashids;
use Log;


/**
 * 充值等待
 * 
 * @property int $uid 
 * @method static string getReaderWaitUrl(int $uid, string $url) 获取支付跳转地址
 */
class PayWait
{
    private $uid;

    private static $_instatnce;

    /**
     * 
     *@param array $arguments 第一个参数默认$uid
     */
    public function __callStatic($name, $arguments)
    {
        if (!self::$_instatnce) {
            self::$_instatnce = new PayWait($arguments[0]);
        }
        array_shift($arguments);
        return self::$_instatnce->$name(...$arguments);
    }

    public function __construct(int $uid)
    {
        $this->uid = $uid;
    }

    /**
     * 获取支付跳转地址
     * @param string $url 前端传入的阅读器地址
     */
    protected function getReaderWaitUrl(string $url)
    {
        if (strpos($url, '/reader') !== false) {
            preg_match('/bid=(\w+)/', $url, $matchs);
            $bid = Hashids::decode($matchs[1])[0];
            $record =  ReadRecordService::getRecordByUidBid($this->uid, $bid);
            if ($record) {
                $cid = explode('_', $record)[0];
                $url = preg_replace('/cid=(\d+)/', 'cid=' . $cid, $url);
            } else {
                $url = preg_replace(['/bid=(\w+)/', '/\/reader\?/'], ['', '/catalog?id=' . $matchs[1] . '&'], $url);
            }
            Log::info('reader_url :' . $url);
        }
        return $url;
    }
}
