#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 utils.exceptions import CustomError
from apps.foundation.consts import CONTENT_TYPE_SORTING, MENU_TO_MODEL

from apps.foundation.models import BizLog

class UserManager(BaseUserManager):
    def sort_perms(self, perms):
        def get_index(app_label, model):
            try:
                return CONTENT_TYPE_SORTING.index('{}-{}'.format(app_label, model))
            except:
                return 9999

        perms = perms.order_by('content_type__model', 'id')
        perms = sorted(perms, key=lambda n: get_index(n.content_type.app_label, n.content_type.model))
        return perms

    def get_menuname_of_contenttype(self, app_label, model):
        for menu in MENU_TO_MODEL:
            val = '{}-{}'.format(app_label, model)
            if val in menu[1]:
                return menu[0]
        return u'未分类'

    def save_group(self, id, name, permissions, user):
        name = name.strip(u' ')
        #old_permissions = None
        if id == None or id == '':
            is_exist = Group.objects.filter(name=name).first()
            if is_exist:
                raise CustomError(u'名称为[%s]的权限组已存在' % name)
            group = Group.objects.create(name=name)
            BizLog.objects.addnew(user, BizLog.INSERT, u"添加权限组[%s],id=%d" % (group.name, group.id))
        else:
            is_exist = Group.objects.filter(name=name).exclude(pk=id).first()
            if is_exist:
                raise CustomError(u'名称为[%s]的权限组已存在' % name)
            group = Group.objects.filter(pk=id).first()
            if not group:
                raise CustomError(u'未找到相应的权限组')
            group.name = name
            group.save()
        #    old_permissions = [p.id for p in group.permissions.all()]
            BizLog.objects.addnew(user, BizLog.UPDATE, u"修改权限组[%s],id=%d" % (group.name, group.id))
        group.permissions = permissions

    def _create_user(self, username,  password, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        if not username:
            raise ValueError('The given username must be set')
        username = self.model.normalize_username(username)
        user = self.model(username=username, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username,  password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(username,  password, **extra_fields)

class User(AbstractBaseUser, PermissionsMixin):
    DIMISSION = 0
    INSERVICE = 1
    STATUS_CHOICES = (
        (DIMISSION, u'离职'),
        (INSERVICE, u'在职'),
    )
    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'已存在'})
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name=u"是否在职", default=INSERVICE)
    tel = models.CharField(max_length=15, verbose_name=u"手机号码", null=True, blank=True)
    address = models.CharField(max_length=500, verbose_name=u"家庭住址", null=True, blank=True)
    title = models.CharField(max_length=20, verbose_name=u"工作岗位", null=True, blank=True)
    date_joined = models.DateTimeField(verbose_name=u'注册时间', default=timezone.now, null=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.username

    def __unicode__(self):
        return self.username

    class Meta:
        db_table = "auth_user"
        verbose_name = u"人员管理"
        ordering = ('-id',)
        default_permissions = ()
        permissions = [
            ('browse_group', u'查看'),
            ('add_group', u'添加'),
            ('edit_group', u'修改'),
            ('delete_group', u'删除'),
        ]
