import time
from django.db import models
from django.db.models import QuerySet


class BasicModel(models.Model):
    create_ts = models.DateTimeField(auto_now_add=True)
    update_ts = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class TsSoftDeleteQuerySet(QuerySet):
    def delete(self):
        return super().update(delete_ts=int(time.time() * 1000))

    def hard_delete(self):
        return super().delete()


class TsSoftDeleteManager(models.Manager):
    def get_queryset(self):
        qs = super().get_queryset().filter(delete_ts=0)
        if not issubclass(qs.__class__, TsSoftDeleteQuerySet):
            qs.__class__ = TsSoftDeleteQuerySet
        return qs


class TsSoftDeleteModel(models.Model):
    """
    使用delete_ts的软删除模型
    """
    create_ts = models.DateTimeField(auto_now_add=True)
    update_ts = models.DateTimeField(auto_now=True)
    delete_ts = models.BigIntegerField(default=0)

    objects = TsSoftDeleteManager()
    all_objects = models.Manager()

    def delete(self, using=None, keep_parents=False):
        self.delete_ts = int(time.time() * 1000)
        self.save(update_fields=["delete_ts"])

    class Meta:
        abstract = True
        # 抽象模型，意思是：Django不会在数据库中创建BasicModel表,
        # 它只是一个父类，供其他模型继承字段和方法子类会继承create_ts和update_ts字段