#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__: vv
# Date: 2019/8/30

from datetime import datetime
from gm_dataquery.db import DB
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery

from api.models import ProtectPhone, ProtectPhoneLog, Order, PhoneServiceRecord
from api.tool.log_tool import info_logger
from gm_types.gaia import USERCALL_EVENT_TYPE


class ProtectPhoneDB(DataBuilder):
    def getval_username(self, obj):
        from api.models import User
        if obj.operator:
            u = User.objects.filter(id=obj.operator).first()
            if u:
                return u.username
        else:
            return ''

    def getval_isbind(self, obj):
        return False if obj and obj.is_online and obj.bind_time else True

    def getval_wechat(self, obj):
        if obj.wechat:
            return obj.wechat
        else:
            return "-"


@DB
class ProtectPhoneDQ(DataSQLQuery):
    model = ProtectPhone
    data_model = ProtectPhoneDB

    def create(self, data, **kwargs):
        info_logger.info({'data': data})
        obj = ProtectPhone()
        obj.favor = data.pop('favor', '')
        obj.city_id = data.pop('city_id', '')
        obj.operator = data.pop('operator')
        obj.user_id = data.pop('user_id')
        obj.wechat = data.pop('wechat', None)
        obj.is_get_wechat = data.pop('is_get_wechat', '')
        obj.bind_time = datetime.now()
        obj.subscriptionid = data.pop('subscriptionId')
        obj.call_status = data.pop('call_status', 1)
        obj.event_id = data.pop('event_id')
        obj.event_type = data.pop('event_type')

        obj.save()

        ProtectPhoneLog.objects.create(
            a_user_id=obj.operator,
            b_user_id=obj.user_id,
            subscriptionid=obj.subscriptionid,
            x_phone_num=data.pop('relationNum', None),
            is_delete=False,
            event_type=obj.event_type,
            protect_phone_id=obj.id,
        )
        return {'id': obj.id}

    def update(self, updates, **kwargs):
        info_logger.info({'updates': updates, 'kwargs': kwargs})
        action = updates.pop('action', '')
        subscriptionId = updates.pop('subscriptionId', None)
        relationNum = updates.pop('relationNum', None)
        current_user_id = updates.pop('current_user_id', None)
        is_get_wechat = updates.pop('is_get_wechat', False)
        call_status = updates.pop('call_status', 1)
        wechat = updates.pop('wechat', None)
        event_type = kwargs.pop('event_type', None)
        event_id = kwargs.pop('event_id', None)

        ids = kwargs.pop('ids', [])
        if ids:
            ProtectPhone.objects.filter(id__in=ids).update(is_online=False)
            return
        if action == "mark":
            pro = ProtectPhone.objects.filter(event_id=event_id, event_type=event_type).last()
        else:
            pro = ProtectPhone.objects.filter(event_id=event_id, event_type=event_type).last()

        if action == "unbind":
            pro.unbind_time = datetime.now()
            pro.is_online = False
        if action == "mark":
            pro.is_get_wechat = bool(int(is_get_wechat))
            pro.call_status = call_status
            pro.wechat = wechat

            if event_type:
                event_type = int(event_type)
                if event_type == USERCALL_EVENT_TYPE.ORDER_CHECK:
                    Order.objects.filter(pk=event_id).update(call_result=call_status)
                elif event_type == USERCALL_EVENT_TYPE.COMMUNICATE_RECORT:
                    PhoneServiceRecord.objects.filter(pk=event_id).update(aduit_result=call_status)

        pro.save()
        if action == 'unbind':
            ProtectPhoneLog.objects.create(
                a_user_id=current_user_id,
                b_user_id=pro.user_id,
                subscriptionid=subscriptionId,
                x_phone_num=relationNum,
                is_delete=True,
                event_type=event_type,
                protect_phone_id=pro.id,
            )

        return {'id': pro.id}
