# -*- coding: utf-8 -*-
"""
@Author ： Rocky
@Time ： 2022/5/9 10:51
@File ：gatewayController.py
"""
import logging
import time

from django.views.generic.base import View

from AnsjerPush.Config.gatewaySensorConfig import SENSOR_TYPE, EVENT_TYPE
from Model.models import SensorRecord, GatewaySubDevice, GatewayPush, Device_Info, SceneLog, SmartScene
from Object.ResponseObject import ResponseObject
from Object.utils import LocalDateTimeUtil
from Service.CommonService import CommonService
from Service.EquipmentInfoService import EquipmentInfoService
from Service.GatewayService import GatewayPushService


class GatewayView(View):
    def get(self, request, *args, **kwargs):
        request.encoding = 'utf-8'
        operation = kwargs.get('operation')
        return self.validation(request.GET, operation)

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

    def validation(self, request_dict, operation):
        response = ResponseObject()
        if operation == 'gatewayPush':  # 网关推送
            return self.gateway_push(request_dict, response)
        elif operation == 'sceneLogPush':  # 网关推送
            return self.scene_log_push(request_dict, response)
        else:
            return response.json(414)

    @staticmethod
    def gateway_push(request_dict, response):
        """
        网关推送
        @param request_dict: 请求参数
        @request_dict serial_number: 序列号
        @request_dict ieee_addr: 长地址
        @request_dict src_addr: 短地址
        @request_dict sensor_type: 传感器类型
        @request_dict event_type: 事件类型
        @request_dict alarm: 消息内容
        @request_dict defense: 防御状态,0:撤防,1:防御
        @request_dict sensor_status: 拆动状态,拆动时传参
        @request_dict sensor_low_power: 低电量
        @param response: 响应对象
        @return: response
        """
        logger = logging.getLogger('info')
        serial_number = request_dict.get('serial_number', None)
        ieee_addr = request_dict.get('ieee_addr', None)
        src_addr = request_dict.get('src_addr', None)
        sensor_type = int(request_dict.get('sensor_type', None))
        event_type = int(request_dict.get('event_type', None))
        alarm = request_dict.get('alarm', None)
        defense = int(request_dict.get('defense', None))
        sensor_status = request_dict.get('sensor_status', None)
        logger.info('---调用网关推送接口--- request_dict:{}'.format(request_dict))
        if not all([serial_number, ieee_addr, src_addr, sensor_type, event_type, alarm]):
            return response.json(444)

        n_time = int(time.time())

        try:
            nickname = serial_number
            # 查询子设备表id
            gateway_sub_device_qs = GatewaySubDevice.objects.filter(device__serial_number=serial_number,
                                                                    device_type=sensor_type, ieee_addr=ieee_addr,
                                                                    src_addr=src_addr).values('id', 'nickname')
            if gateway_sub_device_qs.exists():
                gateway_sub_device_id = gateway_sub_device_qs[0]['id']
                nickname = gateway_sub_device_qs[0]['nickname']
                sensor_record_dict = {
                    'gateway_sub_device_id': gateway_sub_device_id,
                    'alarm': alarm,
                    'event_type': event_type,
                    'created_time': n_time,
                }
                # 处理温湿度,不推送
                if sensor_type == SENSOR_TYPE['tem_hum_sensor'] and (
                        event_type == EVENT_TYPE['temperature'] or event_type == EVENT_TYPE['humidity']):
                    num = request_dict.get('num', None)
                    num = str(int(num) / 100)
                    sensor_record_dict['alarm'] = num
                    SensorRecord.objects.create(**sensor_record_dict)
                    return response.json(0)

                SensorRecord.objects.create(**sensor_record_dict)

                # (门磁,烟雾,人体)传感器被拆动/拆动恢复,修改拆动状态
                if sensor_status:
                    gateway_sub_device_qs.update(is_tampered=1)
                elif sensor_type == SENSOR_TYPE['door_magnet'] or sensor_type == SENSOR_TYPE['smoke_sensor'] or \
                        sensor_type == SENSOR_TYPE['body_sensor']:
                    gateway_sub_device_qs.update(is_tampered=0)

            # 撤防状态不推送
            if defense == 0:
                return response.json(0)

            device_info_qs = Device_Info.objects.filter(serial_number=serial_number).values('userID_id')
            if not device_info_qs.exists():
                return response.json(173)

            equipment_info_list = []

            for device_info in device_info_qs:
                user_id = device_info['userID_id']

                # 组织存储数据
                local_date_time = CommonService.get_now_time_str(n_time=n_time, tz=0, lang='cn')[:10]
                equipment_info_list.append(EquipmentInfoService.get_equipment_info_obj(
                    local_date_time,
                    add_time=n_time,
                    event_time=n_time,
                    receive_time=n_time,
                    device_uid=serial_number,
                    device_nick_name=nickname,
                    alarm=alarm,
                    event_type=event_type,
                    device_user_id=user_id,
                ))
                if equipment_info_list:
                    # 根据日期获得星期几
                    week = LocalDateTimeUtil.date_to_week(local_date_time)
                    EquipmentInfoService.equipment_info_bulk_create(week, equipment_info_list)

                # 查询推送配置数据
                gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
                    values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
                           'tz')
                if not gateway_push_qs.exists():
                    continue

                kwargs = {
                    'n_time': n_time,
                    'event_type': event_type,
                    'nickname': nickname,
                }

                # 推送到每台登录账号的手机
                for gateway_push in gateway_push_qs:
                    app_bundle_id = gateway_push['app_bundle_id']
                    push_type = gateway_push['push_type']
                    token_val = gateway_push['token_val']
                    lang = gateway_push['lang']
                    tz = gateway_push['tz'] if gateway_push['tz'] else 0

                    # 获取推送所需数据
                    msg_title = GatewayPushService.get_msg_title(app_bundle_id, nickname)
                    msg_text = GatewayPushService.get_msg_text(n_time, tz, lang, alarm)

                    kwargs['msg_title'] = msg_title
                    kwargs['msg_text'] = msg_text
                    kwargs['app_bundle_id'] = app_bundle_id
                    kwargs['token_val'] = token_val

                    try:
                        # 推送消息
                        if push_type == 0:  # ios apns
                            kwargs['launch_image'] = 'https://d2cjxvw3tr9apc.cloudfront.net/app/push_images/智能按钮.228.png'
                            GatewayPushService.ios_apns_push(**kwargs)
                        elif push_type == 1:  # android gcm
                            GatewayPushService.android_fcm_push(**kwargs)
                        elif push_type == 2:  # android 极光推送
                            GatewayPushService.android_jpush(**kwargs)
                    except Exception as e:
                        logger.info('网关推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
                        continue

            return response.json(0)
        except Exception as e:
            logger.info('---网关推送接口异常--- {}'.format(repr(e)))
            return response.json(500, repr(e))

    @staticmethod
    def scene_log_push(request_dict, response):
        """
        网关推送
        @param request_dict: 请求参数
        @request_dict serial_number: 序列号
        @request_dict ieee_addr: 长地址
        @request_dict src_addr: 短地址
        @request_dict sensor_type: 传感器类型
        @request_dict event_type: 事件类型
        @request_dict alarm: 消息内容
        @param response: 响应对象
        @return: response
        """
        logger = logging.getLogger('info')
        scene_id = request_dict.get('sceneId', None)
        status = request_dict.get('status', None)
        logger.info('---场景日志推送接口--- request_dict:{}'.format(request_dict))
        if not all([scene_id, status]):
            return response.json(444)

        smart_scene_qs = SmartScene.objects.filter(id=scene_id).values('scene_name', 'conditions', 'tasks', 'device_id',
                                                                       'sub_device_id', 'user_id')
        if not smart_scene_qs.exists():
            return response.json(174)

        nickname = ''
        scene_name = smart_scene_qs[0]['scene_name']
        tasks = smart_scene_qs[0]['tasks']
        device_id = smart_scene_qs[0]['device_id']
        sub_device_id = smart_scene_qs[0]['sub_device_id']
        n_time = int(time.time())
        user_id = smart_scene_qs[0]['user_id']
        log_dict = {
            'scene_id': scene_id,
            'scene_name': scene_name,
            'tasks': tasks,
            'status': status,
            'device_id': device_id,
            'sub_device_id': sub_device_id,
            'created_time': n_time,
        }
        tasks = eval(tasks)

        # if sub_device_id:
        #     sub_device_info_qs = GatewaySubDevice.objects.filter(id=sub_device_id).values('device_id', 'nickname')
        #     nickname = sub_device_info_qs[0]['nickname']
        #     device_id = sub_device_info_qs[0]['device_id']
        #
        # device_info_qs = Device_Info.objects.filter(id=device_id).values('userID_id', 'NickName')
        # if not device_info_qs.exists():
        #     return response.json(173)
        # if not nickname:
        #     nickname = device_info_qs[0]['NickName']
        #
        # user_id = device_info_qs[0]['userID_id']

        try:
            # 存储日志
            # scene_log = {
            #     'conditions': conditions,
            #     'tasks': tasks
            # }
            # log_dict['scene_log'] = json.dumps(scene_log)
            SceneLog.objects.create(**log_dict)

            # 推送日志
            gateway_push_qs = GatewayPush.objects.filter(user_id=user_id, logout=False). \
                values('user_id', 'app_bundle_id', 'app_type', 'push_type', 'token_val', 'm_code', 'lang', 'm_code',
                       'tz')
            if not gateway_push_qs.exists():
                return response.json(174)
            for task in tasks:
                event_type = task['event_type']
                if event_type == '1001':
                    kwargs = {
                        'n_time': n_time,
                        'event_type': event_type,
                        'nickname': nickname,
                    }
                    event_info = task['value']
                    # 推送到每台登录账号的手机
                    for gateway_push in gateway_push_qs:
                        app_bundle_id = gateway_push['app_bundle_id']
                        push_type = gateway_push['push_type']
                        token_val = gateway_push['token_val']
                        lang = gateway_push['lang']
                        tz = gateway_push['tz'] if gateway_push['tz'] else 0

                        # 获取推送所需数据
                        # msg_title = GatewayPushService.get_msg_title(app_bundle_id, nickname)
                        # msg_text = GatewayPushService.get_msg_text(n_time, tz, lang, event_info)

                        kwargs['msg_title'] = nickname
                        kwargs['msg_text'] = event_info
                        kwargs['app_bundle_id'] = app_bundle_id
                        kwargs['token_val'] = token_val

                        try:
                            # 推送消息
                            if push_type == 0:  # ios apns
                                GatewayPushService.ios_apns_push(**kwargs)
                            elif push_type == 1:  # android gcm
                                GatewayPushService.android_fcm_push(**kwargs)
                            elif push_type == 2:  # android 极光推送
                                GatewayPushService.android_jpush(**kwargs)
                        except Exception as e:
                            logger.info('场景日志推送消息异常,errLine:{}, errMsg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
                            continue
            return response.json(0)
        except Exception as e:
            logger.info('---场景日志推送接口异常--- {}'.format(repr(e)))
            return response.json(500, repr(e))
