# coding=utf8
from django.db import models

from django.contrib.auth.models import User
from gm_types.gaia import TEAM_TYPE


class Team(models.Model):
    name = models.CharField('组名', max_length=128, unique=True)
    team_type = models.CharField('组织类型', max_length=8, choices=TEAM_TYPE, default=TEAM_TYPE.OPERATION)
    parent_team = models.ForeignKey('self', verbose_name='上级组织', null=True, related_name='subteams')
    team_user = models.ManyToManyField(User, db_table='themis_teamuser', related_name='teams')

    @property
    def parents(self):
        parents = []
        parent = self.parent_team
        while parent:
            parents.insert(0, parent)
            parent = parent.parent_team
        return parents

    @property
    def all_children_team(self):
        all_children_team = []
        children = self.subteams.all()
        while children:
            all_children_team += children
            children = sum([list(x.subteams.all()) for x in children], [])
        return all_children_team

    @property
    def all_children_user(self):
        return sum([list(x.team_user.all()) for x in self.all_children_team], [])

    @property
    def all_leaf_children(self):
        leaf_children = []
        children = self.subteams.all()
        while children:
            sub_children = []
            for child in children:
                grand_children = child.subteams.all()
                if not grand_children:
                    leaf_children.append(child)
                else:
                    sub_children += grand_children
            children = sub_children
        return leaf_children
