from common.utils.return_structure import general_message, error_message
from common.utils.service_code import PARAMETER_ERROR
from common.utils.views import BaseApiView
from console.video_management.models import Device
from console.video_management.serializers import VideoSystemCreateSerializer, \
    DeviceSerializer
from rest_framework.response import Response

from console.video_management.models import VideoSystem

from common.third_party_api.surveillance.imou import APIClient

from common.third_party_api.surveillance.ys7 import YSCloudClient

from console.video_management.services import ys_cloud_device_list, \
    imou_cloud_device_list

from console.video_management.serializers import DeviceBindSerializer

from console.video_management.filters import DeviceFilter

from console.video_management.serializers import DeviceBindUserSerializer
from console.video_management.services import check_permission_of_device

from console.video_management.filters import VideoSystemFilter
from console.video_management.serializers import VideoSystemSerializer

from console.video_management.serializers import DeviceUpdateSerializer

from console.video_management.services import zyrh_device_list

SYSTEM_MAP = {"1": APIClient, "2": YSCloudClient}


class CreateVideoSystemView(BaseApiView):
    serializer_class = VideoSystemCreateSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("成功添加视频平台"))
        return Response(
            error_message(code=PARAMETER_ERROR, msg_show=serializer.errors))


class CreateDeviceView(BaseApiView):
    serializer_class = DeviceSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("添加设备成功"))
        return Response(
            error_message(code=PARAMETER_ERROR, msg_show=serializer.errors))


class DeviceListView(BaseApiView):
    queryset = Device.objects.filter().prefetch_related("customer", "station", "user",
                                                        "system__customer", "system",
                                                        "system__customer__service_enterprise")
    serializer_class = DeviceSerializer
    filter_class = DeviceFilter

    def get(self, request, *args, **kwargs):
        queryset = self.filter_queryset(
            self.get_queryset()).filter(system__customer__service_enterprise_id__in=self.enterprise_ids)
        serializer = self.get_serializer(queryset, many=True)
        return Response(general_message(list=serializer.data))


class VideoUrlView(BaseApiView):
    def post(self, request, *args, **kwargs):
        try:
            device = Device.objects.filter(id=kwargs.get("id")).first()
            if not device:
                return Response(
                    error_message(code=PARAMETER_ERROR,
                                  msg_show="设备{}不存在".format(kwargs.get("id"))))
            if device.system.system == "3":
                url = "http://{}:23505/live/video.flv?devid={}&channel=1&devline=0".format(
                    device.system.home_url.rstrip("/"), device.deviceSerial)
                data = [{"token": None, "url": url}]
                return Response(general_message(list=data))
            else:
                config = SYSTEM_MAP.get(device.system.system)(device.system)
                param = {
                    "deviceSerial": device.deviceSerial,
                    "channelNo": device.channal,
                    "code": device.deviceType,
                    "protocol": request.data.get("protocol"),
                    "quality": request.data.get("quality"),
                    "startTime": request.data.get("startTime"),
                    "stopTime": request.data.get("stopTime"),
                    "type": request.data.get("type"),
                }

                data = config.get_video_url(**param)
                return Response(general_message(list=data))
        except Exception as e:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="获取视频地址失败"))


class BindDeviceView(BaseApiView):
    serializer_class = DeviceBindSerializer

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("新增成功"))
        return Response(error_message(code=PARAMETER_ERROR, mag_show="新增失败", msg=serializer.errors))


class DeviceEntityListView(BaseApiView):
    def get(self, request, *args, **kwargs):
        data = []
        system = VideoSystem.objects.filter(id=request.GET.get("system_id")).first()
        if not system:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="视频管理后台不存在"))
        try:
            if system.system == "2":
                data = ys_cloud_device_list(**{
                    "client": SYSTEM_MAP.get(request.GET.get("system")),
                    "pageStart": request.GET.get("pageStart"),
                    "pageSize": request.GET.get("pageSize", 50),
                    "system": system,
                    "customer_id": request.GET.get("customer_id")
                })
            elif system.system == "1":
                data = imou_cloud_device_list(**{
                    "client": SYSTEM_MAP.get(request.GET.get("system")),
                    "pageStart": request.GET.get("pageStart"),
                    "pageSize": request.GET.get("pageSize", 50),
                    "system": system,
                    "customer_id": request.GET.get("customer_id")
                })
            elif system.system == "3":
                data = zyrh_device_list(**{
                    "host": "{}:81".format(system.home_url.rstrip("/")),
                    "data": {
                        "userName": system.app_key,
                        "userPwd": system.app_secret
                    }
                })
            return Response(general_message(list=data))
        except Exception as e:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="获取摄像头失败"))


class DeviceView(BaseApiView):
    queryset = Device.objects.filter()
    serializer_class = DeviceSerializer

    def get(self, request, *args, **kwargs):
        if not check_permission_of_device(**{
            "id": kwargs.get("id"),
            "user": request.user
        }):
            return Response(error_message(code=PARAMETER_ERROR,
                                          msg_show="您无权限查看该设备信息"))
        return self.get_info(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        if not check_permission_of_device(**{
            "id": kwargs.get("id"),
            "user": request.user
        }):
            return Response(error_message(code=PARAMETER_ERROR,
                                          msg_show="您无权限操作该设备"))
        instance = self.get_queryset().filter(id=kwargs.get("id")).first()
        request.data.update({"id": kwargs.get("id")})
        serializer = DeviceUpdateSerializer(instance, data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("修改成功"))
        return Response(error_message(code=PARAMETER_ERROR,
                                      msg=serializer.errors,
                                      msg_show="修改失败"))

    def delete(self, request, *args, **kwargs):
        if not check_permission_of_device(**{
            "id": kwargs.get("id"),
            "user": request.user
        }):
            return Response(error_message(code=PARAMETER_ERROR,
                                          msg_show="您无权限操作该设备"))
        instance = self.get_queryset().filter(id=kwargs.get("id")).first()
        instance.delete()
        return Response(general_message("删除成功"))


class DeviceBindUser(BaseApiView):
    queryset = Device.objects.filter()
    serializer_class = DeviceBindUserSerializer

    def put(self, request, *args, **kwargs):
        if not check_permission_of_device(**{
            "id": kwargs.get("id"),
            "user": request.user
        }):
            return Response(error_message(code=PARAMETER_ERROR,
                                          msg_show="您无权限操作该设备"))
        instance = self.get_queryset().filter(id=kwargs.get("id")).first()
        serializer = self.get_serializer(instance, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("绑定成功"))
        return Response(error_message(code=PARAMETER_ERROR,
                                      msg_show="绑定失败",
                                      msg=serializer.errors))


class VideoSystemListView(BaseApiView):
    queryset = VideoSystem.objects.filter()
    serializer_class = VideoSystemSerializer
    filter_class = VideoSystemFilter

    def get(self, request, *args, **kwargs):
        return self.get_list(request, *args, **kwargs)


class VideoSystemView(BaseApiView):
    queryset = VideoSystem.objects.filter()
    serializer_class = VideoSystemSerializer

    def get(self, request, *args, **kwargs):
        return self.get_info(request, *args, **kwargs)

    def put(self, request, *args, **kwargs):
        instance = self.get_queryset().filter(id=kwargs.get("id")).first()
        if not instance:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="视频管理平台不存在"))
        request.data.update({"id": kwargs.get("id")})
        serializer = VideoSystemCreateSerializer(instance, data=request.data, context={"request": request})
        if serializer.is_valid():
            serializer.save()
            return Response(general_message("修改成功"))
        return Response(error_message(code=PARAMETER_ERROR, msg=serializer.errors, msg_show="修改失败"))

    def delete(self, request, *args, **kwargs):
        Device.objects.filter(system_id=kwargs.get("id")).delete()
        self.get_queryset().filter(id=kwargs.get("id")).delete()
        return Response(general_message("删除成功"))


class EntityVideoUrlView(BaseApiView):
    def post(self, request, *args, **kwargs):
        try:
            system = VideoSystem.objects.filter(id=request.data.get("system_id")).first()
            deviceSerial = request.data.get("deviceSerial")
            if system.system == "3":
                url = "http://{}:23505/live/video.flv?devid={}&channel=1&devline=0".format(
                    system.home_url.rstrip("/"), deviceSerial)
                data = [{"token": None, "url": url}]
                return Response(general_message(list=data))
            else:
                config = SYSTEM_MAP.get(system.system)(system)
                param = {
                    "deviceSerial": deviceSerial,
                    "channelNo": request.data.get("channel"),
                    "type": request.data.get("type", "1"),
                }

                data = config.get_video_url(**param)
                return Response(general_message(list=data))
        except Exception as e:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="获取视频地址失败"))


class UserVideoUrlView(BaseApiView):
    def post(self, request, *args, **kwargs):
        try:
            device = Device.objects.filter(user_id=kwargs.get("user_id")).first()
            if not device:
                return Response(
                    error_message(code=PARAMETER_ERROR,
                                  msg_show="员工{}未绑定摄像头".format(kwargs.get("user_id"))))
            if device.system.system == "3":
                url = "http://{}:23505/live/video.flv?devid={}&channel=1&devline=0".format(
                    device.system.home_url.rstrip("/"), device.deviceSerial)
                data = [{"token": None, "url": url}]
                return Response(general_message(list=data))
            else:
                config = SYSTEM_MAP.get(device.system.system)(device.system)
                param = {
                    "deviceSerial": device.deviceSerial,
                    "channelNo": device.channal,
                    "code": device.deviceType,
                    "protocol": request.data.get("protocol"),
                    "quality": request.data.get("quality"),
                    "startTime": request.data.get("startTime"),
                    "stopTime": request.data.get("stopTime"),
                    "type": request.data.get("type"),
                }

                data = config.get_video_url(**param)
                return Response(general_message(list=data))
        except Exception as e:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="获取视频地址失败"))
