# coding=utf-8
from django.db.models import Q
from django.utils.html import escape
from gm_types.gaia import TAG_TYPE, HERA_OPERATE_LOG_PACKAGE, HERA_OPERATE_LOG_ACTION

from api.models import ItemWiki, SimpleActionLog
from hera.models import SendEmailTaskLog
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB


class LogDB(DataBuilder):
    """
    操作日志返回数据格式
    """

    def getval_nickname(self, obj):
        user = obj.user
        if not user:
            return u''
        if user.last_name:
            return user.last_name
        else:
            return user.username

    def getval_object(self, obj):
        return obj.object_id_json

    def getval_package(self, obj):
        return HERA_OPERATE_LOG_PACKAGE.getDesc(obj.package_new)

    def getval_action(self, obj):
        return HERA_OPERATE_LOG_ACTION.getDesc(obj.action_new)

    def getval_message_info(self, obj):
        if obj.message:
            message = obj.message[:560] + '...' if len(obj.message) > 560 else obj.message
            return message
        else:
            return u''


@DB
class LogDQ(DataSQLQuery):
    """
    操作日志实体查询过滤
    """
    model = SimpleActionLog
    data_model = LogDB

    def filter_action_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)

    def filter_nickname(self, srch_key, srch_val, regex=False):
        return Q(user__username__contains=srch_val) | Q(user__last_name__contains=srch_val)

    def filter_message(self, srch_key, srch_val, regex=False):
        return Q(message=srch_val)

    def filter_object_id_json(self, srch_key, srch_val, regex=False):
        return Q(object_id_json=srch_val)

    def filter_package_new(self, srch_key, srch_val, regex=False):
        return Q(package_new__in=srch_val)


@DB
class SendEmailTaskLogDQ(DataSQLQuery):
    model = SendEmailTaskLog
    data_model = DataBuilder

    def filter_join_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)
