# -*- coding: UTF-8 -*-
import time

from django.conf import settings
from django.db.models import Q
from gm_types.gaia import HERA_OPERATE_LOG_PACKAGE, HERA_OPERATE_LOG_ACTION

from api.models import SimpleActionLog
from api.tool.user_tool import get_user_from_context
from hera.queries.log import LogDQ
from ..models import UserPerm
from rpc.decorators import bind_context


uri_pre = 'hera/log'


@bind_context(uri_pre+'/service_list')
def service_datatable(ctx, options):
    user = get_user_from_context(ctx)
    q = Q(package_new=HERA_OPERATE_LOG_PACKAGE.SERVICE)

    if not user.is_superuser:
        members = UserPerm.members(user)
        q &= Q(user_id__in=[item.id for item in members])

    dtobj = LogDQ(init_q=q)
    return dtobj.process(**options)


@bind_context(uri_pre+'/order_list')
def order_datatable(ctx, options):
    user = get_user_from_context(ctx)
    q = Q(package_new=HERA_OPERATE_LOG_PACKAGE.ORDER_MANAGEMENT)
    if not user.is_superuser:
        members = UserPerm.members(user)
        q &= Q(user__in=members)
    dtobj = LogDQ(init_q=q)
    return dtobj.process(**options)


@bind_context(uri_pre + '/action_list')
def diary_query(ctx, options):
    dqobj = LogDQ(using=settings.LARGE_RECORD_DB_NAME)
    return dqobj.process(**options)


@bind_context(uri_pre + '/grey_control_list')
def grey_control_query(ctx, grey_control_id, offset=0, count=10):
    if not grey_control_id:
        return []
    qs = SimpleActionLog.objects.filter(
        package_new=HERA_OPERATE_LOG_PACKAGE.GREY_CONTROL, object_id_json=grey_control_id
    )
    info_list = qs[offset: count]
    HERA_OPERATE_LOG_PACKAGE.getDesc(HERA_OPERATE_LOG_PACKAGE.USER_CANCELLATION)
    items = [{
        'id': item.id,
        'action_time': time.mktime(item.action_time.timetuple()),
        'nickname': item.user.last_name or item.user.username,
        'action_new': HERA_OPERATE_LOG_ACTION.getDesc(item.action_new),
        'message': item.message,
    } for item in info_list]
    total = qs.count()

    return {'items': items, 'total': total}
