import time
from datetime import datetime


class IDMan:

    def __init__(self):
        self.last_time = 0
        self.sequence = 0

    def next_id(self) -> int:
        now = int(time.time() * 1000)
        if now == self.last_time:
            self.sequence += 1
        else:
            self.last_time = now
            self.sequence = 0
        return (now << 4) | self.sequence


def explain_id(id_value: int) -> str:
    timestamp = id_value >> 4
    sequence = id_value & 0xF
    dt = datetime.fromtimestamp(timestamp / 1000)
    time_str = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    return f'ID: {id_value} (时间: {time_str}, 序列号: {sequence})'


class IDTag:

    def __init__(self, get_tag_func):
        self.get_tag_func = get_tag_func

    def __str__(self):
        return f'{self.get_tag_func()}'


class IDClass:
    id_man = IDMan()

    def __init__(self, get_tag_func=None):
        self.id = self.id_man.next_id()
        self.base_tag = f'{self.__class__.__name__}/{self.id}'
        if hasattr(self, '_get_tag'):
            self.tag = IDTag(self._get_tag)
        else:
            self.tag = self.base_tag

    def explain_id(self):
        return explain_id(self.id)
