# -*- coding: UTF-8 -*-
from __future__ import unicode_literals, absolute_import, print_function

from django.db import models
from django.contrib.auth.models import User

from rpc.tool.dict_mixin import DictMixin
from gm_types.gaia import BUSINESS_TYPE, TaskStatusType
from gm_types.hera import CONFIG


class BackendModule(DictMixin, models.Model):

    name = models.CharField(u'模块名', max_length=100, unique=True)
    title = models.CharField(u'模块名称', max_length=100)

    def __unicode__(self):
        return u'%s(%s)' % (self.title, self.name)

    def init_perms(self):
        # init can_view, can_create, can_modify as default perms
        DEFAULT_PERMS = [
            {'name': 'can_view', 'title': u'查看'},
            {'name': 'can_create', 'title': u'新增'},
            {'name': 'can_modify', 'title': u'修改'},
        ]
        for perm in DEFAULT_PERMS:
            BackendPermission.objects.get_or_create(
                name=perm['name'],
                title=perm['title'],
                module=self,
            )


class BackendPermission(DictMixin, models.Model):
    name = models.CharField(u'权限名', max_length=100)
    title = models.CharField(u'权限名称', max_length=100)
    module = models.ForeignKey(BackendModule, verbose_name=u'所属模块')

    class Meta:
        unique_together = (('name', 'module'), )

    def __unicode__(self):
        return self.code

    @property
    def code(self):
        return '%s.%s' % (self.module.name, self.name)

    @property
    def codename(self):
        return u'%s|%s' % (self.module.title, self.title)


class BackendGroup(DictMixin, models.Model):
    name = models.CharField(u'组名', max_length=100, unique=True)
    title = models.CharField(u'组标题', max_length=100)
    leader = models.ForeignKey(User, verbose_name=u'组长', null=True, related_name='own_groups')
    members = models.ManyToManyField(User, verbose_name=u'组内成员', blank=True, related_name='belong_groups')
    permissions = models.ManyToManyField(BackendPermission, blank=True)

    def __unicode__(self):
        return self.title

    def set_leader(self, user):
        """set leader, and also put into members
        """
        self.leader = user
        if not self.id:
            self.save()
        self.members.add(user)
        return


class BackendUser(object):

    @classmethod
    def query(cls):
        return User.objects.filter(is_staff=True).exclude(groups__name=u'医生')

    @classmethod
    def check_staff(cls, user):
        user_id = user.id if isinstance(user, User) else user
        return cls.query().filter(id=user_id).exists()


class UserPerm(object):

    @classmethod
    def user_info(cls, user, session, perms=False, groups=False, mars=False):
        userinnerinfo = getattr(user, 'userinnerinfo', '')
        info = {
            'id': user.id,
            'username': user.username,
            'email': user.email,
            'name': userinnerinfo.name if userinnerinfo and userinnerinfo.name else '',
            'phone': userinnerinfo.phone if userinnerinfo and userinnerinfo.phone else '',
            'session': session,
            'is_superuser': user.is_superuser,
        }
        if perms:
            info['perms'] = cls.perms_code(user)
        if groups:
            info['groups'] = cls.groups(user)
        if mars:
            info['login_mars'] = user.userextra.login_mars if user.userextra else False
        return info

    @classmethod
    def groups(cls, user):
        groups = BackendGroup.objects.filter(members=user)
        return {
            group.name: {
                'title': group.title,
                'is_leader': bool(group.leader == user),
            } for group in groups
        }

    @classmethod
    def perms(cls, user):
        perms = set()
        if user.is_superuser:
            return BackendPermission.objects.all()

        for group in BackendGroup.objects.filter(members=user):
            perms.update(set(group.permissions.all()))

        b_role = cls.business_role(user)
        lead_perms_list = [
            'can_reset_phone',
            #  'set_online',
        ]
        ps = BackendPermission.objects.filter(name__in=lead_perms_list, module__name='doctor')
        if b_role:
            if b_role == BUSINESS_TYPE.GROUP_MEMBER:
                # 医生重置登录手机号不允许组员有权限
                perms = perms - set(ps)
            else:
                perms |= set(ps)
        return perms

    @classmethod
    def perms_code(cls, user):
        return [perm.code for perm in cls.perms(user)]

    @classmethod
    def perms_id(cls, user):
        return [perm.id for perm in cls.perms(user)]

    @classmethod
    def required_perms_code(cls, user, perm_code):
        if not perm_code:
            return []
        if not isinstance(perm_code, list):
            perm_code = [perm_code]
        return list(set(perm_code) & set(cls.perms_code(user)))

    @classmethod
    def check_perm(cls, user, perm_code):
        return bool(cls.required_perms_code(user, perm_code))

    @classmethod
    def members(cls, user):
        """获取user所负责的所有组员
        """
        groups = BackendGroup.objects.filter(members=user)
        mbs = set([user])
        for grp in groups:
            if grp.leader == user:
                # 如果是组长，获取所有组员
                mbs.update(list(grp.members.all()))
        return list(mbs)

    @classmethod
    def business_role(cls, user):
        """获取用户的商务角色
        """
        groups = cls.groups(user)
        if 'business_leader' in groups:
            # 商务Leader
            return BUSINESS_TYPE.LEADER
        if 'business' in groups:
            business_groups = BackendGroup.objects.filter(members=user)
            business_type = BUSINESS_TYPE.GROUP_MEMBER
            for bgroup in business_groups:
                if bgroup.leader == user:
                    # 如果是组长，允许查看组员的业务
                    business_type = BUSINESS_TYPE.GROUP_LEADER
            return business_type
        return None


class SendEmailTaskLog(models.Model):

    task_id = models.CharField(verbose_name=u'任务id', max_length=50)
    user_id = models.IntegerField(verbose_name=u'用户ID')
    user_name = models.CharField(verbose_name=u'用户名', max_length=100)
    send_email = models.CharField(verbose_name=u'发送邮箱', max_length=100)
    title = models.CharField(verbose_name=u'导出标题', max_length=100)
    status = models.CharField(verbose_name=u'状态', max_length=100, choices=TaskStatusType, default=TaskStatusType.PENDING)
    join_time = models.DateTimeField(verbose_name=u'加入时间', auto_now_add=True)
    start_time = models.DateTimeField(verbose_name=u'开始时间', blank=True, null=True)
    end_time = models.DateTimeField(verbose_name=u'结束时间', blank=True, null=True)
    options = models.TextField(verbose_name=u'筛选条件')
    current = models.IntegerField(verbose_name=u'位置', default=0)
    total = models.IntegerField(verbose_name=u'总数', default=0)


class Config(models.Model):
    class Meta:
        verbose_name = '配置'

    key = models.CharField(max_length=200, choices=CONFIG.choices)
    value = models.TextField()
