from django.db import models
from django.contrib.auth.models import AbstractUser
import django.utils.timezone as timezone
from django.db.models.query import QuerySet

# 自定义软删除查询基类
class SoftDeletableQuerySetMixin(object):
    """
    QuerySet for SoftDeletableModel. Instead of removing instance sets
    its ``is_deleted`` field to True.
    """

    def delete(self, soft=True):
        """
        Soft delete objects from queryset (set their ``is_deleted``
        field to True)
        """
        if soft:
            self.update(is_delete=True)
        else:
            return super(SoftDeletableQuerySetMixin, self).delete()


class SoftDeletableQuerySet(SoftDeletableQuerySetMixin, QuerySet):
    pass


class SoftDeletableManagerMixin(object):
    """
    Manager that limits the queryset by default to show only not deleted
    instances of model.
    """
    _queryset_class = SoftDeletableQuerySet

    def get_queryset(self):
        """
        Return queryset limited to not deleted entries.
        """
        kwargs = {'model': self.model, 'using': self._db}
        if hasattr(self, '_hints'):
            kwargs['hints'] = self._hints

        return self._queryset_class(**kwargs).filter(is_delete=False)


class SoftDeletableManager(SoftDeletableManagerMixin, models.Manager):
    pass

class SoftCommonModel(models.Model):
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间', help_text='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='修改时间', help_text='修改时间')
    is_delete = models.BooleanField(default=False, verbose_name='删除标记', help_text='删除标记')

    class Meta:
        abstract = True

    objects = SoftDeletableManager()

    def delete(self, using=None, soft=True, *args, **kwargs):
        """
        这里需要真删除的话soft=False即可
        """
        if soft:
            self.is_delete = True
            self.save(using=using)
        else:

            return super(SoftCommonModel, self).delete(using=using, *args, **kwargs)

class CommonModel(models.Model):
    create_time = models.DateTimeField(default=timezone.now, verbose_name='创建时间', help_text='创建时间')
    update_time = models.DateTimeField(auto_now=True, verbose_name='修改时间', help_text='修改时间')
    is_delete = models.BooleanField(default=False, verbose_name='删除标记', help_text='删除标记')

    class Meta:
        abstract = True


class Menu(SoftCommonModel):
    """
    功能权限:目录,菜单,权限
    """
    menu_type_choices = (
        ("cata", "目录"),
        ("menu", "菜单"),
        ("api", "接口")
    )
    name = models.CharField(max_length=30, unique=True, verbose_name="名称")
    type = models.CharField(max_length=20, choices=menu_type_choices, default="cata", verbose_name="类型")
    is_frame = models.BooleanField(default=False, verbose_name="外部链接")
    sort = models.IntegerField(default=1, verbose_name="排序标记")
    pid = models.ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="父")
    method = models.CharField(max_length=50, null=True, blank=True, verbose_name="方法/代号", unique=True)
    

    def __str__(self):
        return self.name + '-' + str(self.sort)

    class Meta:
        verbose_name = '功能权限表'
        verbose_name_plural = verbose_name
        ordering = ['id']


class Role(SoftCommonModel):
    """
    角色
    """
    name = models.CharField(max_length=32, unique=True, verbose_name="角色")
    menus = models.ManyToManyField("Menu", blank=True, verbose_name="功能权限")
    desc = models.CharField(max_length=50, blank=True, null=True, verbose_name="描述")
    class Meta:
        verbose_name = "角色"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

class Organization(SoftCommonModel):
    """
    组织架构
    """
    organization_type_choices = (
        ("company", "公司"),
        ("department", "部门")
    )
    name = models.CharField(max_length=60, verbose_name="名称")
    type = models.CharField(max_length=20, choices=organization_type_choices, default="department", verbose_name="类型")
    pid = models.ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="父类组织")

    class Meta:
        verbose_name = "组织架构"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class UserProfile(AbstractUser):
    """
    用户
    """
    name = models.CharField(max_length=20, verbose_name="姓名", null=True, blank=True)
    mobile = models.CharField(max_length=11, verbose_name="手机号码", null=True, blank=True, unique=True)
    email = models.EmailField(max_length=50, verbose_name="邮箱", null=True, blank=True, unique=True)
    avatar = models.CharField(default="/media/default/avatar.png",max_length=1000, null=True, blank=True)
    department = models.ForeignKey("Organization", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="部门")
    position = models.CharField(max_length=50, null=True, blank=True, verbose_name="职位")
    superior = models.ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL, verbose_name="上级主管")
    roles = models.ManyToManyField("Role", verbose_name="角色", blank=True)
    is_delete = models.BooleanField(default=False, verbose_name='删除标记', help_text='删除标记')

    pname = models.CharField('所属省份', max_length=100, null=True, blank=True)
    bcompany = models.ForeignKey('crm.company', verbose_name='所属公司', null=True, blank=True, on_delete=models.SET_NULL)
    mpopenid = models.CharField(max_length=100, verbose_name='小程序openid', unique=True, null=True, blank=True)

    class Meta:
        verbose_name = "用户信息"
        verbose_name_plural = verbose_name
        ordering = ['id']

    def __str__(self):
        return self.username
