#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
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

        # 去掉下属创建权限组中的权限
        #if old_permissions:
        #    new_permissions = [p.id for p in group.permissions.all()]
        #    diff = list(set(old_permissions).difference(set(new_permissions)))

        #    users = User.objects.filter(groups=group)
        #    groups = Group.objects.filter(create_user__in=users,permissions__id__in=diff)
        #    for g in groups:
        #        for pk in diff:
        #            g.permissions.remove(pk)

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)
    gender = models.PositiveSmallIntegerField(choices=settings.GENDER_CHOICES, verbose_name=u"性别",null=True,blank=True)
    ID_card = models.CharField(max_length=18, verbose_name=u"身份证号", null=True, blank=True)
    address = models.CharField(max_length=500, verbose_name=u"家庭住址", null=True, blank=True)
    department = models.ForeignKey('Department', verbose_name=u"所属部门", null=True, blank=True, on_delete=models.PROTECT)
    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 removeSubs(self):
        SubDepartment.objects.filter(user=self).delete()
        SubEmployee.objects.filter(user=self).delete()

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

    def getSubDepartmentIds(self):
        ids = []
        sub_ids = SubDepartment.objects.filter(user=self).values_list('department_id', flat=True)
        departments = Department.objects.filter(id__in=sub_ids)

        for dept in departments:
            rows = Department.objects.filter(lft__gte=dept.lft, rgt__lte=dept.rgt)
            for row in rows:
                if row.id not in ids:
                    ids.append(row.id)
        return ids

    def getSubEmployeeIds(self):
        return SubEmployee.objects.filter(user=self).values_list('employee_id', flat=True)

    class Meta:
        db_table = "auth_user"
        verbose_name = u"人员管理"
        ordering = ('-id',)
        default_permissions = ()
        permissions = (
            ("view_user", u"浏览"),
            ("add_user", u"添加"),
            ("delete_user", u"删除"),
        )

class SubDepartment(models.Model):
    user = models.ForeignKey(User, verbose_name=u"用户", on_delete=models.PROTECT)
    department = models.ForeignKey('Department', verbose_name=u"管辖部门", on_delete=models.PROTECT)

    class Meta:
        db_table = "sub_department"
        verbose_name = u"退货查询"
        default_permissions = ()
        permissions = ( # 管辖部门
            ("view_material_godownentry_return_query", u"浏览"),
            ("export_material_godownentry_return_query", u"导出"),
            ("print_material_godownentry_return_query", u"打印"),
        )


class SubEmployee(models.Model):
    user = models.ForeignKey(User, verbose_name=u"用户", related_name='sub_employee_ref_user', on_delete=models.PROTECT)
    employee = models.ForeignKey(User, verbose_name=u"员工", related_name='sub_employee_ref_employee', on_delete=models.PROTECT)

    class Meta:
        db_table = "sub_employee"
        verbose_name = u"退货查询"
        default_permissions = ()
        permissions = (  # 管辖员工
            ("view_consumable_godownentry_return_query", u"浏览"),
            ("export_consumable_godownentry_return_query", u"导出"),
            ("print_consumable_godownentry_return_query", u"打印"),
        )

class Department(models.Model):
    MATERIAL = 1
    CONSUMABLE = 2
    ALLPRODUCT = 3
    PRODUCT_RANGE_CHOICES = (
        (MATERIAL, u'原料'),
        (CONSUMABLE, u'耗材'),
        (ALLPRODUCT, u'全部'),
    )

    name = models.CharField(max_length=100, verbose_name=u"名称")
    notes = models.CharField(max_length=500, verbose_name=u"备注",blank=True,null=True)
    parent_id = models.IntegerField(verbose_name=u"父部门",null=True,blank=True)
    company = models.ForeignKey('Department', verbose_name=u"公司节点")
    product_range = models.IntegerField(verbose_name=u"产品范围",null=True,blank=True)
    lft = models.IntegerField(verbose_name=u"左值")
    rgt = models.IntegerField(verbose_name=u"右值")

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

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

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

    def getCompany(self):
        instance = Department.objects.filter(parent_id__isnull=True, lft__lte=self.lft, rgt__gte=self.rgt).first()
        if not instance:
            raise CustomError(u'未找到部门所属的公司')
        return instance

    @staticmethod
    def getLft(instance):
        if instance:
            return instance.lft
        return 1

    class Meta:
        db_table = "department"
        verbose_name = u"组织结构管理"
        ordering = ["parent_id", 'id']
        default_permissions = ()
        permissions = (
            ("view_department", u"浏览"),
            ("add_department", u"添加"),
            ("delete_department", u"删除"),
        )
