# encoding=utf-8
from __future__ import unicode_literals

import json
from django.db.models import Q
from rpc.cache import req_data_cache
from django.db import IntegrityError, transaction
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
from rpc.tool.queryset_tool import queryset_dec
from gm_types.gaia import ORDER_STATUS
from hera.queries.fenxiao import FenxiaoCompanyDQ, FenxiaoOrderDQ
from api.models.fenxiao import FenxiaoCompany, FenxiaoWanghong, FenxiaoOrderWanghong
from api.tasks.export_excel_task import export_channel_urls_excel, export_fenxiao_order_excel

__author__ = 'wangshengguang'

uri_pre = 'hera/fenxiao'

order_status = [ORDER_STATUS.PAID, ORDER_STATUS.USED, ORDER_STATUS.REFUNDED,
                ORDER_STATUS.SETTLED, ORDER_STATUS.WAIT_REFUNDED]


@bind_context(uri_pre + '/channel/list')
def fenxiao_select(ctx, options):
    dtobj = FenxiaoCompanyDQ()
    return dtobj.process(**options)


@bind_context(uri_pre + '/channel/get')
def channel_detail(ctx, channel_id, options=None):
    try:
        channel = FenxiaoCompany.objects.get(id=channel_id)
    except:
        raise RPCNotFoundException
    if options is None:
        options = {
            'fields': None,
            'excludes': None,
            'expands': None,
        }
    data = to_dict(channel, **options)
    data['wanghong_num'] = channel.wanghongs.count()
    return data


@transaction.atomic
@bind_context(uri_pre + '/channel/edit')
def channel_edit(ctx, channel_id=None, channel_info=None):
    res = {'channel_exist': False}
    if channel_info is None:
        return None
    wanghong_inc = channel_info.pop('wanghong_inc') or 0
    channel_info.pop('wanghong_num')
    channel_info['name'] = channel_info['name'].strip()
    if channel_id is None:
        try:
            channel = FenxiaoCompany.objects.filter(name=channel_info.get('name'))
            if channel.exists():
                res['channel_exist'] = True
                res['id'] = channel[0].id
                return res
            else:
                channel = FenxiaoCompany.objects.create(**channel_info)
        except IntegrityError:
            raise RPCIntegrityError
    else:
        try:
            channel = FenxiaoCompany.objects.get(id=channel_id)
            for k, v in channel_info.iteritems():
                setattr(channel, k, v)
            channel.save()
        except:
            info_logger.info(__import__('traceback').format_exc())
            raise RPCNotFoundException
    wanghong_info = {'company_id': channel.id}
    for _ in range(wanghong_inc):
        wanghong_info['code'] = FenxiaoWanghong.generate_code()
        FenxiaoWanghong.objects.create(**wanghong_info)
    res['id'] = channel.id
    return res


@bind_context(uri_pre + '/channel/export_excel')
def channel_export_excel(ctx, channel_id):
    user = ctx.session.user
    wanghongs = FenxiaoWanghong.objects.filter(company_id=channel_id)
    export_channel_urls_excel.delay(queryset_dec(wanghongs), user.email)


@bind_context(uri_pre + '/order/query')
def fenxiao_order_query(ctx, options):
    req_data_cache.set(ctx.session.session_key + 'fenxiao_order', json.dumps(options))
    dqobj = FenxiaoOrderDQ(init_q=Q(order__status__in=order_status))
    return dqobj.process(**options)


@bind_context(uri_pre + '/order/export_excel')
def doctor_apply_export_excel(ctx):
    user = ctx.session.user
    req_data = json.loads(req_data_cache.get(ctx.session.session_key + 'fenxiao_order'))
    req_data.pop('paging')
    req_data.pop('columns')
    dtobj = FenxiaoOrderDQ(FenxiaoOrderWanghong, init_q=Q(order__status__in=order_status))
    fenxiao_orders = dtobj.build_queryset(**req_data)
    export_fenxiao_order_excel.delay(queryset_dec(fenxiao_orders), user.email)
