#coding=utf-8

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, Group, PermissionsMixin
from django.utils import timezone
from django.conf import settings

from apps.exceptions import CustomError


class Branch(models.Model):
    name = models.CharField(max_length=200, verbose_name=u"名称")
    tel = models.CharField(max_length=50, verbose_name=u"电话")
    address = models.CharField(max_length=200, verbose_name=u"地址")
    enabled = models.BooleanField(verbose_name=u"在用", default=True)
    create_time = models.DateTimeField(verbose_name=u"添加时间", auto_now_add=True, editable=False)

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的门店ID')
        instance = Branch.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的门店')
        return instance

    class Meta:
        db_table = "branch"
        ordering = ['-id']
        verbose_name = u"门店管理"


class UserManager(BaseUserManager):
    def create_user(self, type, username, password=None, **extra_fields):
        if not username:
            raise ValueError(u'请输入用户名')
        user = self.model(type=type, username=username,  is_superuser=False, last_login=timezone.now(), **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, **extra_fields):
        u = self.create_user(User.EMPLOYEE, username, password, **extra_fields)
        u.is_superuser = True
        u.save(using=self._db)
        return u


class User(AbstractBaseUser, PermissionsMixin):
    EMPLOYEE = 1
    CUSTOMER = 2
    TYPE_CHOICES = (
        (EMPLOYEE, u'员工'),
        (CUSTOMER, u'客户'),
    )

    type = models.PositiveSmallIntegerField(verbose_name=u"类型", choices=TYPE_CHOICES, editable=False, default=EMPLOYEE)
    branch = models.ForeignKey(Branch, verbose_name=u"门店",  on_delete=models.PROTECT, null=True, blank=True)
    name = models.CharField(max_length=20, verbose_name=u"姓名")
    username = models.CharField(max_length=30, verbose_name=u'账号', unique=True, db_index=True,error_messages={'unique': u'已存在'})
    tel = models.CharField(max_length=15, verbose_name=u"手机号码", null=True, blank=True)
    gender = models.PositiveSmallIntegerField(choices=settings.GENDER_CHOICES, verbose_name=u"性别",null=True,blank=True)
    address = models.CharField(max_length=500, verbose_name=u"家庭住址", null=True, blank=True)
    date_joined = models.DateTimeField(verbose_name=u'注册时间', default=timezone.now, null=True)
    enabled = models.BooleanField(verbose_name=u"在用", default=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    @staticmethod
    def getById(id):
        try:
            id = int(id)
        except:
            raise CustomError(u'无效的员工ID')

        instance = User.objects.filter(pk=id).first()
        if not instance:
            raise CustomError(u'未找到相应的员工')
        return instance

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

    class Meta:
        db_table = "auth_user"
        verbose_name = u"人员管理"
        ordering = ('-id',)
