from notifications.signals import notify

from common.accounts.models import Users, UserOrganizations, Accounts, UserEnterprise
from common.notify.message import client as message_client

from console.organizations.models import Organization
from console.message.repositories import message_sql_repo

class MessageServices(object):
    def get_user_message_config(self, user_id=None):
        return message_sql_repo.get_user_message_config(user_id)

    def get_messages(self, enterprise_ids, user_id, config=None, person=False, **kwargs):
        return message_sql_repo.get_messages(enterprise_ids, user_id, config, person, **kwargs)


def send_message(**data):
    # 站内通知
    if "2" in data.get("send_type"):
        # account_ids = Users.objects.filter(
        #     id__in=data.get("reciever"),
        #     deleted=False).values_list("account").distinct()
        # param = {
        #     "recipient": Accounts.objects.filter(id__in=account_ids),
        #     "description": data.get("content"),
        #     "action_object": data.get("message"),
        #     "verb": "{}发送了一条消息通知".format(data.get("sender").username)
        # }
        enterprise = UserEnterprise.objects.filter(user_id__in=data.get("reciever", [])).first()
        # notify.send(data.get("sender"), **param)
        message_client.send_station(
            title="消息通知",
            content= data.get("content", ""),
            sender_id=1,
            receive_ids=data.get("reciever", []),
            type=1,
            enterprise_id=enterprise.id)


def get_user_by_department(id_list):
    ids = []
    for id in id_list:
        ids += get_departmrnt_id(id)
    ids = list(set(ids + id_list))
    user_id = UserOrganizations.objects.filter(
        organization_id__in=ids).values_list("user_id", flat=True)
    return user_id


def get_departmrnt_id(id):
    id_list = []
    ids = Organization.objects.filter(parent=id).values_list("id", flat=True)
    if not ids:
        return []
    for id in ids:
        get_departmrnt_id(id)
        id_list.append(id)
    return id_list


msg_service = MessageServices()
