from django.conf import settings
from django.db.models import Q
from gm_types.mimas import FAKE_REPLY_BAND_TYPE

from communal.models.fake_reply import FakeReplyConfig, FakeReplyConfigMapReply, FakeReplyPool
from talos.rpc import bind


@bind('mimas/fake_reply/config/get')
def get_config(config_id=None):
    if not config_id:
        return {}

    try:
        config = FakeReplyConfig.objects.get(id=config_id)
    except FakeReplyConfig.DoesNotExist:
        return {}

    reply_ids = list(FakeReplyConfigMapReply.objects.using(settings.SLAVE_DB_NAME).filter(
        config_id=config.id, is_online=True
    ).values_list('reply_id', flat=True))
    replies = FakeReplyPool.objects.using(settings.SLAVE_DB_NAME).filter(
        id__in=reply_ids, is_online=True
    ).values('id', 'content')

    return {
        'band_type': config.band_type,
        'tag_id': config.tag_id,
        'tag_attr_id': config.tag_attr_id,
        'tag_group_id': config.tag_group_id,
        'is_online': config.is_online,
        'replies': [{
            'id': item['id'],
            'content': item['content'],
        } for item in replies],
    }


@bind('mimas/fake_reply/config/edit')
def config_edit(data, config_id=None):
    result = {
        'data': config_id,
        'error': 0,
        'message': 'success'
    }
    if not any([data, config_id]):
        return result

    obj = {
        'band_type': int(data.get('band_type')),
        'tag_id': data.get('tag_id') or 0,
        'tag_group_id': data.get('tag_group_id') or 0,
        'tag_attr_id': data.get('tag_attr_id') or 0,
        'is_online': data.get('is_online', False),
    }
    # 判断是否被关联过
    if obj['band_type'] == FAKE_REPLY_BAND_TYPE.TAG:
        query = Q(tag_id=int(data.get('tag_id')), band_type=FAKE_REPLY_BAND_TYPE.TAG)
    elif obj['band_type'] == FAKE_REPLY_BAND_TYPE.TAG_GROUP:
        query = Q(tag_group_id=int(data.get('tag_group_id') or 0), band_type=FAKE_REPLY_BAND_TYPE.TAG_GROUP)
    else:
        query = Q(tag_attr_id=int(data.get('tag_attr_id') or 0), band_type=FAKE_REPLY_BAND_TYPE.TAG_ATTR)

    if FakeReplyConfig.objects.filter(query).exclude(id=config_id).exists():
        result['error'] = 1
        return result

    if not config_id:
        config = FakeReplyConfig.objects.create(**obj)
    else:
        config = FakeReplyConfig.objects.get(id=config_id)
        for k, v in obj.items():
            setattr(config, k, v)
        config.save()

    result['data'] = config.id
    return result


@bind('mimas/reply_config/add_reply')
def add_new_relation(reply_id, config_id):
    result = {
        'error': 0,
        'message': 'success',
        'data': ''
    }
    if not all([reply_id, config_id]):
        return result

    FakeReplyConfigMapReply.objects.get_or_create(
        config_id=config_id, reply_id=reply_id
    )

    return result


@bind('mimas/reply_config/del_reply')
def del_config_relation(reply_id, config_id):
    result = {
        'error': 0,
        'message': 'success',
        'data': ''
    }
    if not all([reply_id, config_id]):
        return result

    FakeReplyConfigMapReply.objects.filter(
        config_id=config_id, reply_id=reply_id
    ).delete()

    return result


@bind('mimas/reply_config/bulk_del_reply')
def bulk_del_config_relation(reply_id, config_id):
    result = {
        'error': 0,
        'message': 'success',
        'data': ''
    }
    if not all([reply_id, config_id]):
        return result
    reply_ids = list(map(int, reply_id))
    FakeReplyConfigMapReply.objects.filter(
        config_id=config_id, reply_id__in=reply_ids
    ).delete()

    return result
