# coding=utf-8
from _mysql import IntegrityError

from django.db import transaction

from api.models import OperateTeam, OperateTeamRealatedOperate, OperateTeamReleatedBusiness
from hera.queries.operateteam import OperateTeamDQ
from rpc.decorators import bind_context
from rpc.exceptions import RPCIntegrityError, RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from rpc.tool.log_tool import info_logger

uri_pre = 'hera/'


@bind_context(uri_pre + 'operateteam/get')
def operateteam_get(ctx, operateid):
    """
    获取运营商无小组的信息
    :param operateid: 小组ID
    """
    if operateid is None:
        return None
    try:
        operate = OperateTeam.objects.get(id=operateid)
    except IntegrityError:
        raise RPCIntegrityError
    operate_info = to_dict(operate)
    operates = OperateTeamRealatedOperate.objects.filter(operate__id=operateid).values_list('user__id', flat=True)
    business = OperateTeamReleatedBusiness.objects.filter(operate__id=operateid).values_list('user__id', flat=True)
    operate_info['operates'] = list(operates)
    operate_info['business'] = list(business)
    return operate_info


@bind_context(uri_pre + 'operateteam/get_byname')
def operateteam_get_byname(ctx, name, operateteam_id=None):
    """
    获取运营商无小组的信息
    :param name:小组名称
    :param operateteam_id:小组ID
    """
    if name is None:
        return None
    if operateteam_id is None:
        try:
            operate = OperateTeam.objects.filter(name=name)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            operate = OperateTeam.objects.filter(name=name).exclude(id=operateteam_id)
        except IntegrityError:
            raise RPCIntegrityError
    if operate.count() > 0:
        return True
    else:
        return False


@transaction.atomic
@bind_context(uri_pre + 'operateteam/edit')
def operateteam_edit(ctx, operate_info, operate_id=None):
    """
    编辑运营商务小组的信息
    :param operate_info: 小组信息
    :param operate_id: 小组ID
    """
    if operate_info is None:
        return None
    operates = operate_info.pop('operates')
    business = operate_info.pop('business')
    if operate_id is None:
        try:
            operate = OperateTeam.objects.create(**operate_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            operate = OperateTeam.objects.get(id=operate_id)
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
        for k, v in operate_info.iteritems():
            setattr(operate, k, v)
        operate.save()

    old_operate = set(OperateTeamRealatedOperate.objects.filter(operate__id=operate.id))
    new_operate = set(OperateTeamRealatedOperate.objects.get_or_create(operate_id=operate.id,
                                                                       user_id=user
                                                                       )[0] for user in operates)
    for item in (old_operate - new_operate):
        item.delete()

    old_business = set(OperateTeamReleatedBusiness.objects.filter(operate__id=operate.id))
    new_business = set(OperateTeamReleatedBusiness.objects.get_or_create(operate_id=operate.id,
                                                                         user_id=user
                                                                         )[0] for user in business)
    for item in (old_business - new_business):
        item.delete()

    return {"operate_id": operate.id}


@bind_context(uri_pre + 'operateteam/query')
def operateteam_query(ctx, options):
    dqobj = OperateTeamDQ()
    return dqobj.process(**options)
