from django.db import models

# Create your models here.
import base64

from Crypto.Cipher import AES
from django.conf import settings
from django.db import models
from django.utils.translation import gettext_lazy as _

class BaseModel(models.Model):
    """基类模型"""
    create_time = models.DateTimeField(auto_now_add=True, verbose_name=_("创建时间"))
    update_time = models.DateTimeField(auto_now=True, verbose_name=_("更新时间"))

    class Meta:
        abstract = True  # 抽象模型类, 用于继承使用


class BasePasswordModels(models.Model):
    """需要密码加解密的基类模型"""

    class Meta:
        abstract = True

    @staticmethod
    def encrypt(row_password: str):
        """
        AES 加密登录密码
        :param row_password: 原明文密码
        :return: AES加密后密码
        """
        aes = AES.new(str.encode(settings.SECRET_KEY[4:20]), AES.MODE_ECB)
        bytes_row_password = str.encode(row_password)
        while len(bytes_row_password) % 16 != 0:
            bytes_row_password = bytes_row_password + b'\0'
        return str(base64.encodebytes(aes.encrypt(bytes_row_password)), encoding='utf8').replace('\n', '')

    def set_password(self, field_name, field_value):
        """加密密码并保存实例"""
        self.__setattr__(field_name, self.encrypt(field_value))

    def get_password_display(self, field_name):
        """
        AES 解密登录密码
        :return: 原明文密码
        """
        aes = AES.new(str.encode(settings.SECRET_KEY[4:20]), AES.MODE_ECB)
        return str(aes.decrypt(base64.decodebytes(bytes(str(self.__getattribute__(field_name)), encoding='utf8'))).rstrip(b'\0').decode("utf8"))



#2022-03-10
class PermCategory(models.Model):
    name=models.CharField(_('类别名称'),max_length=50,unique=True)
    remark=models.CharField(_('备注说明 '),max_length=50,blank=True,null=True)

    class Meta:
        verbose_name = _('权限分类')
        verbose_name_plural = _('权限分类')
        



method_choices = (
    (u'POST', u'增'),
    (u'DELETE', u'删'),
    (u'PUT', u'改'),
    (u'PATCH', u'局部改'),
    (u'GET', u'查')
)
class Permission(models.Model):
    """
    权限
    """    
    category=models.ForeignKey(PermCategory,verbose_name=_('权限分类'), on_delete=models.CASCADE)
    pid = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE, verbose_name='父权限')
    content_type_id=models.IntegerField(_('Django content id'),blank=True,null=True)
    name = models.CharField(max_length=30, verbose_name='权限名')  
    method = models.CharField(max_length=8, blank=True, null=True, choices=method_choices, verbose_name='方法')
    path = models.CharField(max_length=200, blank=True, null=True, verbose_name='请求路径正则')    
    desc = models.CharField(max_length=30, blank=True, null=True, verbose_name='权限描述')   

    def __str__(self):
        return self.name

    class Meta:
        #db_table = 'system_permissions'
        verbose_name = '权限'
        verbose_name_plural = verbose_name
        ordering = ['id']
        unique_together = ('content_type_id', 'method')
