# -*- encoding: utf-8 -*-
"""
@File    : EquipmentMessagePush.py
@Time    : 2022/5/16 11:46
@Author  : stephen
@Email   : zhangdongming@asj6.wecom.work
@Software: PyCharm
"""

import logging
import time

from django.db import transaction
from django.views.generic.base import View

from Model.models import AiService, UidSetModel, Device_Info
from Object.ResponseObject import ResponseObject
from Object.TokenObject import TokenObject
from Service.CommonService import CommonService


# 设备消息推送视图
class EquipmentMessagePushView(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, request, operation)

    def post(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.POST, request, operation)

    def validation(self, request_dict, request, operation):
        token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
        lang = request_dict.get('lang', None)
        logger = logging.getLogger('info')
        logger.info("传参语言{}".format(lang))
        lang = lang if lang else token.lang
        response = ResponseObject(lang)
        if token.code != 0:
            return response.json(token.code)
        if operation is None:
            return response.json(444, 'error path')
        elif operation == 'update':
            return self.do_change_status_all(request_dict, response)
        elif operation == 'query':
            return self.do_uid_set_query(request_dict, response)

    @classmethod
    def do_uid_set_query(cls, request_dict, response):

        logger = logging.getLogger('info')
        uid = request_dict.get('uid', None)
        logger.info("----查询状态打印uid{}".format(uid))
        if not uid:
            return response.json(444, 'uid')
        uid_set_qs = UidSetModel.objects.filter(uid=uid).order_by('-updTime')
        if uid_set_qs.exists():
            uid_set = uid_set_qs.first()
            data = {
                'status': uid_set.is_notification,
                'interval': uid_set.new_detect_interval
            }
            return response.json(0, res=data)
        return response.json(0)

    @classmethod
    def do_change_status_all(cls, request_dict, response):
        logger = logging.getLogger('info')
        status = request_dict.get('status', None)
        uid = request_dict.get('uid', None)
        interval = request_dict.get('interval', None)
        if not status:
            return response.json(444, 'status')
        if not uid:
            return response.json(444, 'uid')
        try:
            with transaction.atomic():
                n_time = int(time.time())
                status = int(status)
                uid_set_qs = UidSetModel.objects.filter(uid=uid)
                device_qs = Device_Info.objects.filter(UID=uid)
                if not uid_set_qs.exists():
                    qs_data = {
                        'uid': uid,
                        'addTime': n_time,
                        'updTime': n_time,
                        'device_type': device_qs[0].Type if device_qs.exists() else 0
                    }
                    if interval:
                        qs_data['new_detect_interval'] = int(interval)
                        qs_data['is_notification'] = status
                    UidSetModel.objects.create(**qs_data)
                if status == 1:
                    if uid_set_qs.exists():
                        qs_data = {
                            'updTime': n_time,
                        }
                        if interval:
                            qs_data['new_detect_interval'] = int(interval)
                        qs_data['is_notification'] = status
                        uid_set_qs.update(**qs_data)
                if status == 0:
                    ai_service_qs = AiService.objects.filter(uid=uid, use_status=1)
                    if ai_service_qs.exists():
                        qs_data = {'uid': uid, 'updTime': n_time, 'detect_status': status}
                        ai_service_qs.update(**qs_data)
                        topic_name = 'ansjer/generic/{}'.format(uid)
                        # mqtt通知设备关闭AI识别功能
                        msg = {'commandType': 'AIDisable'}
                        req_success = CommonService.req_publish_mqtt_msg(uid, topic_name, msg)
                        logger.info("推送>>>> mqtt回调:{}".format(req_success))
                    if uid_set_qs.exists():
                        uid_set_data = {'updTime': n_time, 'uid': uid, 'new_detect_interval': int(interval),
                                        'detect_status': int(interval), 'is_notification': status}
                        uid_set_qs.update(**uid_set_data)
            return response.json(0)
        except Exception as e:
            print(e)
            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
