# coding=utf-8

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, Group
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, Group, AbstractUser
from django.utils import timezone
from rest_framework.utils import model_meta
from utils.exceptions import CustomError
from django.conf import settings
from apps.agent.models import Store, Agent

class UserManager(BaseUserManager):

    def create_user(self, type, username, password=None, **extra_fields):
        if not username:
            raise CustomError(u'请输入账号！')
        count = User.objects.filter(username=username).count()
        if count > 0:
            raise CustomError(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

class User(AbstractBaseUser, PermissionsMixin):

    WAITING_JOIN = 1
    INSERVICE = 2
    DIMISSION = 3

    STATUS_CHOICES = (
        (WAITING_JOIN, u'待入职'),
        (INSERVICE, u'在职'),
        (DIMISSION, u'离职'),
    )
    username = models.CharField(verbose_name=u'用户名', max_length=30, unique=True, db_index=True,
                                help_text=u'不多于20个字符。只能用字母、数字和字符。')
    password = models.CharField(u'密码', max_length=128, blank=True)

    is_active = models.BooleanField(verbose_name=u'是否可用', default=True, editable=False)
    date_joined = models.DateTimeField(verbose_name=u'注册时间', auto_now_add=True, editable=False)

    name = models.CharField(max_length=20, verbose_name=u"姓名")
    gender = models.PositiveSmallIntegerField(choices=settings.GENDER_CHOICES, verbose_name=u"性别")
    ID_card = models.CharField(max_length=18, verbose_name=u"身份证号", null=True, blank=True)
    address = models.CharField(max_length=100, verbose_name=u"家庭住址", null=True, blank=True)
    tel = models.CharField(max_length=15, verbose_name=u"手机")
    agent = models.ForeignKey(Agent, verbose_name=u"代理商", null=True, blank=True, on_delete=models.PROTECT)
    store = models.ForeignKey(Store, verbose_name=u"所属门店", null=True, blank=True, on_delete=models.PROTECT)
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, verbose_name=u"是否在职", default=INSERVICE)
    check_user = models.ForeignKey('User', verbose_name=u'审核人', related_name='user_check_user', null=True,
                                   on_delete=models.PROTECT)
    check_time = models.DateTimeField(verbose_name=u'审核时间', editable=False, null=True)
    create_user = models.ForeignKey('self', verbose_name='创建者', blank=True, on_delete=models.PROTECT)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = []

    class Meta:
        db_table = "auth_user"
        verbose_name = u"人员管理"
        unique_together = [
            ('username')
        ]
        ordering = ['-id']
        default_permissions = ()
        permissions = [
            ('browse_user', u'查看'),
            ('add_user', u'添加'),
            ('delete_user', u'删除'),
            ('check_user', u'入职审核'),
            ('manager_store', u'管理门店'),
        ]

    def __unicode__(self):
        return self.username

    def get_manager_range(self):
        stores = []
        if self.is_superuser:
            rows = Store.objects.filter(enable=True).values('id')
            return [row['id'] for row in rows]

        rows = ManageStoreUser.objects.filter(manage_user=self).values('store_id')
        for row in rows:
            stores.append(row['store_id'])

        create_stores = Store.objects.filter(create_user=self).values('id')
        for create_store in create_stores:
            stores.append(create_store['id'])

        return list(set(stores))

    def change_password(self, new_password, confirm_password, old_password):
        if new_password != confirm_password:
            raise CustomError(u'两次输入的密码不一致， 请检查')
        if not self.check_password(old_password):
            raise CustomError(u'原密码输入错误， 请检查')
        self.set_password(new_password)

    def update_item(self, validated_data):
        def update():
            info = model_meta.get_field_info(self)
            for attr, value in validated_data.items():
                if attr in info.relations and info.relations[attr].to_many:
                    field = getattr(self, attr)
                    field.set(value)
                else:
                    setattr(self, attr, value)

        if not 'username' in validated_data:
            raise CustomError(u'账号不能为空！')
        count = User.objects.filter(username=validated_data['username']).exclude(id=self.id).count()
        if count > 0:
            raise CustomError(u'该账号已存在！')

        if not 'password' in validated_data or not validated_data['password']:
            validated_data['password'] = self.password
            update()
        else:
            update()
            self.set_password(validated_data['password'])
        self.save()
        return self

class ManageStoreUser(models.Model):

    store = models.ForeignKey(Store, verbose_name=u"门店", null=True, blank=True, on_delete=models.PROTECT)
    manage_user = models.ForeignKey(User, verbose_name=u"管理人员",related_name='manger_user_ref_user', on_delete=models.PROTECT)

    class Meta:
        db_table = "auth_user_manage_store"
        verbose_name = u"权限管理" #用户管理范围
        default_permissions = ()
        permissions = [
            ('manager_permissions', u'管理'),
        ]

Group.add_to_class('create_user', models.ForeignKey(User, verbose_name=u"创建人", on_delete=models.PROTECT, editable=False))
