<?php

namespace Heanup\Frame\Library;

/**
 * 发号器类
 */
class Ticket extends \Heanup\Frame\Library
{
    const TICKET_START_TIME = 1262275200; // 2010-1-1 00:00:00
    const DEFAULT_SERVER_ID = 9; //使用微秒发出去的id编号
    const TICKET_KEY_PREFIX = 'id_';

    /**
     * 获取发号
     * @param $businessId
     * @return mixed
     * @throws \Exception
     */
    public static function getTicket($businessId = 0)
    {
//         for ($i = 0; $i < 10; $i++) {
//             $result = self::getFromRemote($businessId);
//             if ($result) {
//                 return $result;
//             }
//         }
//         \Heanup\Frame\Logger::crit('ticket error', 'ticket');
        $result = self::getTicketFromTimestamp();
        return $result;
    }

    /**
     * 从发号器获取号码
     * @param $businessId
     * @return mixed
     */
    protected static function getFromRemote($businessId = 0)
    {
        $configClass = 'Memcache\\Ticket';
        $memcached = new Memcache($configClass);
        $connection = $memcached->getConnection();
        $key = self::TICKET_KEY_PREFIX . intval($businessId);
        $result = $connection->get($key);
        return $result;
    }

    /**
     * 获取发号
     * @return int
     */
    protected static function getTicketFromTimestamp()
    {
        $time = self::getTimestamp();
        $time[0] = $time[0] - self::TICKET_START_TIME;
        $time = implode('', $time);
        $rand = sprintf('%03d', rand(0, 999));
        $code = $time . $rand . self::DEFAULT_SERVER_ID;
        return $code;
    }

    /**
     * 获取时间戳信息，
     * 返回值分别是秒，毫秒，微秒
     * @return array
     */
    protected static function getTimestamp()
    {
        list($microTime, $seconds) = explode(" ", microtime());
        $microTime = intval($microTime * 1000000);
        $timeStamp = array(
            0 => $seconds,
            1 => substr($microTime, 0, 3),
            2 => substr($microTime, 3, 3),
        );
        return $timeStamp;
    }

}
