# coding=utf-8
from django.db import transaction
from django.db.models import Q
from django.conf import settings
from gm_types.gaia import TOPIC_TYPE

from rpc.decorators import bind_context
from rpc.exceptions import RPCNotFoundException
from rpc.tool.dict_mixin import to_dict
from talos.models.topic import Problem, PgcClassify
from hera.queries.talos.pgccontent import ProblemDQ, PgcClassifyDQ
from hera.utils import get_choices, model_edit


uri_pre = 'hera/pgccontent'


def remote_choices(model, qry_item, fetch_seleted=False, page=1, num=30, src_map=None):
    if fetch_seleted:
        # get initial options
        if isinstance(qry_item['val'], (list, tuple)):
            qs = {'{}__in'.format(qry_item['key']): qry_item['val']}
        else:
            qs = {qry_item['key']: qry_item['val']}
    else:
        qs = {'{}__contains'.format(qry_item['key']): qry_item['val']}
    query = model.objects.filter(**qs).filter(is_online=True)
    return get_choices(query, page, num, src_map)


@bind_context(uri_pre + '/choices')
def pgc_choices(ctx, q='', page=1, num=30, initial=None):
    src_map = {'id': 'id', 'text': 'name'}
    if initial is None:
        qry_item = {'key': 'name', 'val': q}
        fetch_seleted = False
    else:
        qry_item = {'key': 'id', 'val': initial}
        fetch_seleted = True
    return remote_choices(PgcClassify, qry_item, fetch_seleted, page, num, src_map)


@bind_context(uri_pre + '/query')
def pgccontent_query(ctx, options):
    init_q = Q(user_id='22') | Q(topic_type=TOPIC_TYPE.WEIXIN_NUM)
    dqobj = ProblemDQ(init_q=init_q)
    return dqobj.process(**options)


@bind_context(uri_pre + '/edit')
@transaction.atomic
def pgccontent_edit(ctx, pgccontent_id=None, pgccontent_info=None, urls=None):
    if pgccontent_info is None:
        return None
    tags = pgccontent_info.pop('tags', [])
    pgccontent_info['pgc_classfy_id'] = pgccontent_info.pop('pgc_classfy', None)
    if pgccontent_id is None:
        return None
    topic = model_edit(Problem, pgccontent_id, pgccontent_info)

    if tags:
        topic.upd_tags(tags)
    return topic.id


@bind_context(uri_pre + '/get')
def pgccontent_get(ctx, pgccontent_id):
    """
    获取pgc帖子内容根据id
    """
    if pgccontent_id is None:
        return None
    try:
        topic = Problem.objects.get(id=pgccontent_id)
    except:
        raise RPCNotFoundException
    pgc_data = to_dict(topic)
    pgc_data['tags'] = topic.tag_ids
    return pgc_data


@bind_context(uri_pre + '/pgcclassfy/query')
def ppgcclassfy_query(ctx, options):
    dqobj = PgcClassifyDQ()
    return dqobj.process(**options)


@bind_context(uri_pre + '/pgcclassfy/edit')
@transaction.atomic
def pgcclassfy_edit(ctx, pgcclassfy_id=None, pgcclassfy_info=None):
    if pgcclassfy_info is None:
        return None
    classify_name = pgcclassfy_info['name']
    duplicate_name = PgcClassify.objects.filter(name=classify_name).exclude(id=pgcclassfy_id)
    if duplicate_name:
        return -1
    pgcclassfy = model_edit(PgcClassify, pgcclassfy_id, pgcclassfy_info)
    if not pgcclassfy_info.get('is_online', True):
        topics = pgcclassfy.topics.all()
        topics.update(is_online=False)
    return pgcclassfy.id


@bind_context(uri_pre + '/pgcclassfy/get')
def pgcclassfy_get(ctx, pgcclassfy_id):
    """
    获取pgc分类内容根据id
    """
    if pgcclassfy_id is None:
        return None
    try:
        pgcclassfy = PgcClassify.objects.get(id=pgcclassfy_id)
    except:
        raise RPCNotFoundException
    pgc_data = to_dict(pgcclassfy)
    return pgc_data
