# -*- coding: UTF-8 -*-
from django.db.models import Q

from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB
from api.models import PhoneServiceRecord, ProtectPhone, User
from gm_types.gaia import USERCALL_EVENT_TYPE, USERCALL_STATUS
from api.tool.user_tool import filter_user_nick_name


class PhoneServiceDB(DataBuilder):
    def getval_call_status(self, obj):
        if obj.call_status == 2:
            return u'接听成功'
        else:
            return u'未接听'
    
    def getval_aduit_result(self, obj):
        return USERCALL_STATUS.getDesc(obj.aduit_result)

    def getval_now_status(self, obj):
        ret = ProtectPhone.objects.filter(event_id=obj.id, event_type=USERCALL_EVENT_TYPE.COMMUNICATE_RECORT).last()
        return u'已绑定' if ret and ret.bind_time and ret.is_online else u'暂无绑定'

    def getval_is_bind(self, obj):
        ret = ProtectPhone.objects.filter(event_id=obj.id, event_type=USERCALL_EVENT_TYPE.COMMUNICATE_RECORT).last()
        return 1 if ret and ret.bind_time and ret.is_online else 0

    def getval_bind_operator(self, obj):
        ret = ProtectPhone.objects.filter(event_id=obj.id, event_type=USERCALL_EVENT_TYPE.COMMUNICATE_RECORT).last()
        user = User.objects.filter(id=ret.operator).first()
        return filter_user_nick_name(user)


@DB
class PhoneServiceDQ(DataSQLQuery):
    model = PhoneServiceRecord
    data_model = PhoneServiceDB

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

    def filter_call_phone(self, srch_key, srch_val, regex=False):
        return Q(call_phone=srch_val)

    def filter_dest_phone(self, srch_key, srch_val, regex=False):
        return Q(dest_phone=srch_val)
