import uuid
from django.db import models

from apps.utils.models import BaseModel


class AuditLog(models.Model):
    """TN:审计表"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    action = models.CharField('动作', max_length=20)
    model_name = models.CharField('模型名', max_length=20)
    instance_id = models.CharField('记录ID', max_length=20, editable=False)
    change_reason = models.CharField('变更原因', default='', max_length=50)
    change_user = models.ForeignKey(
        'system.user', on_delete=models.SET_NULL, verbose_name='操作人', null=True, blank=True)
    change_time = models.DateTimeField('变更时间')
    val_new = models.JSONField('变更后完整数据', default=dict)
    difference = models.JSONField('变更情况', default=list)


class DrfRequestLog(BaseModel):
    """TN:Logs Django rest framework API requests"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4)
    user = models.ForeignKey(
        'system.user',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
    )
    requested_at = models.DateTimeField(db_index=True)
    response_ms = models.PositiveIntegerField(default=0)
    path = models.CharField(
        max_length=400,
        db_index=True,
        help_text="请求地址",
    )
    view = models.CharField(
        max_length=400,
        null=True,
        blank=True,
        db_index=True,
        help_text="执行视图",
    )
    view_method = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        db_index=True,
    )
    remote_addr = models.GenericIPAddressField()
    host = models.URLField()
    method = models.CharField(max_length=10)
    query_params = models.TextField(null=True, blank=True)
    data = models.TextField(null=True, blank=True)
    response = models.TextField(null=True, blank=True)
    errors = models.TextField(null=True, blank=True)
    agent = models.TextField(null=True, blank=True)
    status_code = models.PositiveIntegerField(
        null=True, blank=True, db_index=True)

    class Meta:
        verbose_name = "DRF请求日志"

    def __str__(self):
        return "{} {}".format(self.method, self.path)
