import json
import logging
from rest_framework.exceptions import ParseError, APIException
from apps.ecm.service import dispatch_dahua_event, handle_xx_event, loc_change, rail_in, rail_out
from apps.hrm.services import HrmService
from apps.third.tapis import dhapis, xxapis, spapis
from apps.third.king.king_api import kapis
from apps.third.king.k import kingClient
from apps.third.errors import TAPI_CODE_WRONG
from apps.third.dahua import dhClient
from apps.third.xunxi import xxClient
from apps.third.speaker import spClient
from apps.utils.mixins import MyLoggingMixin
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from apps.utils.viewsets import CustomGenericViewSet
from rest_framework.mixins import CreateModelMixin
from rest_framework.decorators import action

from apps.third.serializers import PicSerializer, RequestCommonSerializer
from rest_framework import serializers
from django.conf import settings
from django.conf import settings
from django.core.cache import cache
myLogger = logging.getLogger('log')
# Create your views here.


class DahuaTestView(MyLoggingMixin, APIView):
    """大华测试接口

    大华测试接口
    """
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        # res = dhClient.face_search(path='/media/2022/07/13/three.jpg')
        # res = dhClient.snap(code='1000163$1$0$0')
        res = dhClient.get_rtsp(code='1000163$1$0$0')
        return Response(res)


class SpTestView(APIView):
    """
    音响测试接口
    """
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        """
        音响测试接口

        音响测试接口
        """
        # spClient.speak('http://1.203.161.103:2800/media/2022/07/15/alarm2.mp3', ['ls20://0201874E9530'], v_num=2)
        # return Response()
        # params = {"page": 1, "pageSize": 10000}
        # _, res = spClient.request(**spapis['device_list'], params=params)
        _, res = spClient.speak(path='http://192.168.10.249:20309/media/2022/09/01/test.mp3',
                                sns=['ls20://020277AA7D06'], v_num=5)
        return Response(res)


class SpeakerViewSet(CustomGenericViewSet):
    """喇叭视图集

    喇叭视图集
    """
    perms_map = {}
    serializer_class = serializers.Serializer

    @action(methods=['get'], detail=False,
            permission_classes=[IsAuthenticated])
    def headers(self, request, pk=None):
        """获取headers

        获取headers
        """
        return Response({'headers': spClient.headers})


class XxTestView(APIView):
    """
    寻息测试接口
    """
    permission_classes = [IsAuthenticated]

    def get(self, request, *args, **kwargs):
        json = {
            "railId": "bc0ed1151524490589a9a519685f188f",
            "type": ""
        }
        _, res = xxClient.request(**xxapis['rail_ibeacon_list'], json=json)
        return Response(res)
        # ok, res = xxClient.request(
        #     url='/api/application/build/buildListV2', json={})
        # if ok == 'success':
        #     return Response(res)
        # elif ok == 'fail':
        #     raise ParseError(**res)
        # else:
        #     raise APIException(**res)

# 寻息事件订阅


# class XxListener(stomp.ConnectionListener):
#     def on_error(self, frame):
#         print('received an error "%s"' % frame.body)

#     def on_message(self, frame):
#         data = json.loads(frame.body)
#         dispatch_xunxi_event(data)
#         print('received a message "%s"' % frame.body)


# if settings.XX_ENABLED:
#     c = stomp.Connection([(settings.XX_MQ_HOST, settings.XX_MQ_PORT)])
#     c.set_listener('', XxListener())
#     c.connect(settings.XX_USERNAME, settings.XX_LICENCE)
#     c.subscribe(settings.XX_QUEUE, id='')


class XxCommonViewSet(CreateModelMixin, CustomGenericViewSet):
    perms_map = {'post': '*'}
    serializer_class = RequestCommonSerializer

    def create(self, request, *args, **kwargs):
        """
        寻息通用调用接口

        寻息通用调用接口
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        vdata = serializer.validated_data
        if vdata.get('code', ''):
            xxapi = xxapis.get(vdata['code'], None)
            if xxapi is None:
                raise ParseError(**TAPI_CODE_WRONG)
            vdata['url'] = xxapi['url']
            vdata['method'] = xxapi['method']
        _, res = xxClient.request(
            url=vdata['url'],
            method=vdata.get('method', 'post'),
            params=vdata.get('params', {}),
            json=vdata.get('json', {}))
        return Response(res)

    @action(methods=['get'], detail=False,
            permission_classes=[IsAuthenticated])
    def codes(self, request, pk=None):
        """获取请求短标识

        获取请求短标识
        """
        return Response(xxapis)

    @action(methods=['get'], detail=False,
            permission_classes=[IsAuthenticated])
    def token(self, request, pk=None):
        """获取token

        获取token
        """
        return Response({'token': cache.get('xx_token', '')})

    @action(methods=['post'], detail=False,
            permission_classes=[IsAdminUser],
            serializer_class=serializers.Serializer)
    def subscribe(self, request, pk=None):
        """寻息事件一键订阅

        寻息事件一键订阅
        """
        xxClient.subscribe('location', '/api/third/xunxi/c_location/')
        xxClient.subscribe('rail', '/api/third/xunxi/c_rail/')
        xxClient.subscribe('oneKeyAlarm', '/api/third/xunxi/c_one_key_alarm/')
        xxClient.subscribe('lowpower', '/api/third/xunxi/c_lowpower/')
        return Response()

    @action(methods=['post'], detail=False,
            permission_classes=[IsAdminUser],
            serializer_class=serializers.Serializer)
    def unsubscribe(self, request, pk=None):
        """取消订阅

        取消订阅
        """
        pass

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[], throttle_classes=[],
            serializer_class=serializers.Serializer, logging_methods=[])  # 日志
    def c_location(self, request, pk=None):
        loc_change(data=request.data['data'])
        return Response()

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[], throttle_classes=[],
            serializer_class=serializers.Serializer, logging_methods=['POST'])  # 日志
    def c_rail(self, request, pk=None):
        data = request.data
        if data['data']['type'] == 1:
            # 围栏进入
            rail_in(data=data['data'])
        elif data['data']['type'] == 2:
            # 围栏离开
            rail_out(data=data['data'])
        return Response()

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[], throttle_classes=[],
            serializer_class=serializers.Serializer, logging_methods=['POST'])  # 日志
    def c_one_key_alarm(self, request, pk=None):
        data = request.data
        if data['data']['event'] == 'alarm':
            handle_xx_event(name='one_key_alarm', data=data['data'])
        return Response()

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[], throttle_classes=[],
            serializer_class=serializers.Serializer, logging_methods=['POST'])  # 日志
    def c_lowpower(self, request, pk=None):
        data = request.data
        handle_xx_event(name='low_power', data=data['data'])
        return Response()


class KingCommonViewSet(CreateModelMixin, CustomGenericViewSet):
    perms_map = {'post': '*'}
    serializer_class = RequestCommonSerializer
    permission_classes = [IsAdminUser]

    def create(self, request, *args, **kwargs):
        """
        亚控通用调用接口

        亚控通用调用接口
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        vdata = serializer.validated_data
        if vdata.get('code', ''):
            kapi = kapis.get(vdata['code'], None)
            if kapi is None:
                raise ParseError(**TAPI_CODE_WRONG)
            vdata['url'] = kapi['url']
            vdata['method'] = kapi['method']
        _, res = kingClient.request(
            url=vdata['url'],
            method=vdata.get('method', 'post'),
            params=vdata.get('params', {}),
            json=vdata.get('json', {}))
        return Response(res)
    
class DhCommonViewSet(CreateModelMixin, CustomGenericViewSet):
    perms_map = {'post': '*'}
    serializer_class = RequestCommonSerializer

    def create(self, request, *args, **kwargs):
        """
        大华通用调用接口

        大华通用调用接口
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        vdata = serializer.validated_data
        if vdata.get('code', ''):
            xxapi = dhapis.get(vdata['code'], None)
            if xxapi is None:
                raise ParseError(**TAPI_CODE_WRONG)
            vdata['url'] = xxapi['url']
            vdata['method'] = xxapi['method']
        _, res = dhClient.request(
            url=vdata['url'],
            method=vdata.get('method', 'post'),
            params=vdata.get('params', {}),
            json=vdata.get('json', {}))
        return Response(res)

    @action(methods=['get'], detail=False,
            permission_classes=[IsAuthenticated])
    def codes(self, request, pk=None):
        """获取请求短标识

        获取请求短标识
        """
        return Response(dhapis)

    @action(methods=['get'], detail=False,
            permission_classes=[IsAuthenticated])
    def token(self, request, pk=None):
        """获取token

        获取token
        """
        ret = {
            "current": cache.get('dh_token', ''),
        }
        dhClient._get_token()
        ret["new"] = cache.get('dh_token', '')
        return Response(ret)

    @action(methods=['post'], detail=False,
            permission_classes=[IsAuthenticated],
            serializer_class=PicSerializer)
    def full_pic(self, request, pk=None):
        """获取完整图片地址

        获取完整图片地址
        """
        return Response({'url': dhClient.get_full_pic(path=request.data.get('path'))})

    @action(methods=['post'], detail=False,
            permission_classes=[IsAdminUser],
            serializer_class=serializers.Serializer)
    def subscribe(self, request, pk=None):
        """事件订阅

        事件订阅
        """
        json_data = {
            "param": {
                "monitors": [
                    {
                        "monitor": settings.BASE_URL + '/api/third/dahua/c_swip/',
                        "monitorType": "url",
                        "events": [
                            {
                                "category": "alarm",
                                "subscribeAll": 1,
                                "domainSubscribe": 2,
                                "authorities": [
                                    {
                                        "types": ["42", "43", "44", "45", "46", "48", "49", "51", "52", "53",
                                                  "54", "55", "56", "57", "61", "62", "1420", "1425", "1430",
                                                  "1433", "1434", "1435", "1436", "1437", "1438",
                                                  "1439", "1441", "1442", "1443", "1448", "1449",
                                                  "1450", "1455", "1456", "1461", "1462", "1463",
                                                  "1464", "1467", "1468", "1469", "1470", "1471",
                                                  "1472", "1473", "1474", "1475", "1476", "1487",
                                                  "1488", "1489", "1490", "1491", "1492", "1493",
                                                  "1494", "1667", "4603", "4604", "4626", "4627",
                                                  "4632", "4633"]
                                    }
                                ]
                            },
                        ]
                    },
                    {
                        "monitor": settings.BASE_URL + '/api/third/dahua/c_monitor/',
                        "monitorType": "url",
                        "events": [
                            {
                                "category": "alarm",
                                "subscribeAll": 1,
                                "domainSubscribe": 2,
                                "authorities": [
                                    {
                                        "types": ["3", "302", "303", "305", "306", "307", "309", "311", "313", "314", "316",
                                                  "319", "326", "564", "574", "575", "577",
                                                  "578", "586", "587", "594", "596", "597",
                                                  "613", "614", "639", "665", "672", "675",
                                                  "819", "822", "823", "824", "826", "828",
                                                  "861", "873", "881", "882", "888", "962",
                                                  "963", "964", "965", "972", "973", "974",
                                                  "980", "981", "989", "1001000", "1001001",
                                                  "1001003", "1001004", "1001005", "1001006", "1001007", "1001008"]
                                    }
                                ]
                            },
                        ]
                    },
                    {
                        "monitor": settings.BASE_URL + '/api/third/dahua/c_swip/',
                        "monitorType": "url",
                        "events": [
                            {
                                "category": "business",
                                "subscribeAll": 1,
                                "domainSubscribe": 2,
                                "authorities": [
                                    {
                                        "types": ["cardRecord.offline"]
                                    }
                                ]
                            },
                        ]
                    }
                ],
                "subsystem": {
                    "subsystemType": 0,
                    "name": settings.DAHUA_SUBSCRIBE,
                    "magic": settings.DAHUA_SUBSCRIBE
                }
            }
        }
        dhClient.request(**dhapis['mq_subscribe'], json=json_data)
        return Response()

    @action(methods=['delete'], detail=False,
            permission_classes=[IsAdminUser],
            serializer_class=serializers.Serializer)
    def unsubscribe(self, request, pk=None):
        """取消事件订阅

        取消事件订阅
        """
        dhClient.request(**dhapis['mq_unsubscribe'],
                         params={'name': settings.DAHUA_SUBSCRIBE})
        return Response()

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[], throttle_classes=[],
            serializer_class=serializers.Serializer, logging_methods=['POST'])  # 日志
    def c_swip(self, request, pk=None):
        """门禁事件

        门禁事件
        """
        data = request.data
        method = data['method']
        subsystem = data.get('subsystem', None)
        if method == 'alarm.msg' and subsystem == 'evo-accesscontrol':
            HrmService.swipe(data=data)
        elif method == 'cardRecord.offline' and subsystem == 'evo-accesscontrol':
            HrmService.swipe_offline(data=data)
        return Response()

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[], throttle_classes=[],
            serializer_class=serializers.Serializer, logging_methods=['POST'])  # 日志
    def c_monitor(self, request, pk=None):
        """监控事件

        监控事件
        """
        data = request.data
        dispatch_dahua_event(data=data)
        return Response()

    @action(methods=['post'], detail=False,
            authentication_classes=[], permission_classes=[],
            serializer_class=serializers.Serializer, logging_methods=[])  # 日志
    def face_deploy(self, request, pk=None):
        """人脸库同步到所有智能设备

        人脸库同步到所有智能设备
        """
        dhClient.face_deploy(request.data.get('minSim', 90))
        return Response()
