#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import requests

from drf_yasg.utils import swagger_auto_schema
from drf_yasg import openapi
from rest_framework import status
from rest_framework.response import Response
from django.http import JsonResponse
from django.views.decorators.gzip import gzip_page
from django.utils.decorators import method_decorator

from common.utils.views import AllowAnyApiView, ManagerApiView, BaseApiView
from common.utils.serializers import serializer_assembly
from common.utils.return_structure import general_message
from common.utils.exceptions import TooManyLinesRecv

from .serializers import (CustomerSerializer, CarSerializer, SummarySerializer,
                          WeatherSerializer, StatisticsSerializer,
                          MonitorVideoSerializer)
from .services import power_oa_service, statistics_service, \
    get_all_user_history_last_location, get_all_user_recent_location, get_economic_score, get_security_score, \
    get_quality_score
from common.utils.return_structure import error_message

logger = logging.getLogger('')


@method_decorator(gzip_page, name='dispatch')
class CarInfoView(BaseApiView):
    @swagger_auto_schema(operation_description="获取大屏车辆信息",
                         tags=['dashboard'],
                         manual_parameters=[
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("parameter",
                                               openapi.IN_QUERY,
                                               description="名称，车牌号模糊查询",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("get_all",
                                               openapi.IN_QUERY,
                                               description="获取所有数据",
                                               type=openapi.TYPE_INTEGER,
                                               required=False)
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(CarSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        page = int(
            request.GET.get("page")) if request.GET.get("page") else None
        page_size = int(request.GET.get("page_size")) if request.GET.get(
            "page_size") else None
        get_all = int(request.GET.get("get_all", 0))
        if "1" not in self.enterprise_ids:
            return JsonResponse(general_message())
        if not get_all:
            if page_size:
                if page_size > 100:
                    raise TooManyLinesRecv
            parameter = request.GET.get("parameter")
            cars, count = power_oa_service.get_cars(page=page,
                                                    page_size=page_size,
                                                    parameter=parameter)
        else:
            cars, count = power_oa_service.get_cache_cars()
        data = general_message(msg_show=None,
                               list=cars,
                               page=page,
                               page_size=page_size,
                               count=count)
        return JsonResponse(data)


@method_decorator(gzip_page, name='dispatch')
class CustomerInfoView(BaseApiView):
    @swagger_auto_schema(operation_description="获取大屏客户信息",
                         tags=['dashboard'],
                         manual_parameters=[
                             openapi.Parameter("page",
                                               openapi.IN_QUERY,
                                               description="页码",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("page_size",
                                               openapi.IN_QUERY,
                                               description="每页数量",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("parameter",
                                               openapi.IN_QUERY,
                                               description="名称，户号，地址模糊查询",
                                               type=openapi.TYPE_STRING,
                                               required=False),
                             openapi.Parameter("adcode",
                                               openapi.IN_QUERY,
                                               description="地理编码模糊查询",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("longitude",
                                               openapi.IN_QUERY,
                                               description="经度范围查询",
                                               type=openapi.FORMAT_FLOAT,
                                               required=False),
                             openapi.Parameter("latitude",
                                               openapi.FORMAT_FLOAT,
                                               description="纬度范围查询",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                             openapi.Parameter("get_all",
                                               openapi.FORMAT_FLOAT,
                                               description="返回所有数据",
                                               type=openapi.TYPE_INTEGER,
                                               required=False),
                         ],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(CustomerSerializer, many=True)
                         })
    def get(self, request, *args, **kwargs):
        get_all = int(request.GET.get("get_all", 0))
        page = int(
            request.GET.get("page")) if request.GET.get("page") else None
        page_size = int(request.GET.get("page_size")) if request.GET.get(
            "page_size") else None
        if page_size:
            if page_size > 100:
                raise TooManyLinesRecv
        parameter = request.GET.get("parameter")
        adcode = request.GET.get("adcode")
        longitude = request.GET.get("longitude")
        latitude = request.GET.get("latitude")
        if get_all:
            customers, count = power_oa_service.get_cache_subscribe_customer()
        else:
            customers, count = power_oa_service.get_subscribe_customer(
                page=page,
                page_size=page_size,
                adcode=adcode,
                parameter=parameter,
                longitude=longitude,
                latitude=latitude)
        data = general_message(msg_show=None,
                               list=customers,
                               bean={
                                   "enterprises": list(self.enterprises.values("id", "name"))
                               },
                               page=page,
                               page_size=page_size,
                               count=count)
        return JsonResponse(data)


class SummaryView(BaseApiView):
    @swagger_auto_schema(
        operation_description="获取大屏汇总信息",
        tags=['dashboard'],
        responses={status.HTTP_200_OK: serializer_assembly(SummarySerializer)})
    def get(self, request, *args, **kwargs):
        join_ents = []
        query = request.GET.copy()
        enterprise_id = request.GET.get("enterprise_id")
        if not enterprise_id:
            join_ents = self.enterprise_ids
        if enterprise_id == "1001":
            join_ents = ["1001"]
        if enterprise_id == "1004":
            join_ents = ["1004"]
        summary = power_oa_service.get_summary(join_ents=join_ents, **query)
        serializer = SummarySerializer(data=summary)
        serializer.is_valid()
        data = general_message(msg_show=None, bean=serializer.data)
        return Response(data, status=200)


class WeatherInfoView(AllowAnyApiView):
    @swagger_auto_schema(
        operation_description="获取天气信息",
        manual_parameters=[
            openapi.Parameter("adcode",
                              openapi.IN_QUERY,
                              description="城市行政编码",
                              type=openapi.TYPE_STRING,
                              required=False),
        ],
        tags=['dashboard'],
        responses={status.HTTP_200_OK: serializer_assembly(SummarySerializer)})
    def get(self, request, *args, **kwargs):
        weather = power_oa_service.get_weather(request)
        serializer = WeatherSerializer(data=weather)
        serializer.is_valid()
        data = general_message(msg_show=None, bean=serializer.data)
        return Response(data, status=200)


class StatisticsView(AllowAnyApiView):
    @swagger_auto_schema(operation_description="获取大屏统计信息",
                         tags=['dashboard'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(StatisticsSerializer)
                         })
    def get(self, request, *args, **kwargs):
        statistics_data = statistics_service.get_statistics()
        data = general_message(bean=statistics_data)
        return Response(data, status=status.HTTP_200_OK)


@method_decorator(gzip_page, name='dispatch')
class CustomerDetailView(AllowAnyApiView):
    @swagger_auto_schema(operation_description="获取电站详情信息",
                         tags=['dashboard'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(StatisticsSerializer)
                         })
    def get(self, request, number_id, *args, **kwargs):
        data = statistics_service.get_number_detail(number_id)
        data = general_message(bean=data)
        return JsonResponse(data)


class MonitorLView(AllowAnyApiView):
    @swagger_auto_schema(operation_description="获取监控视频列表",
                         tags=['dashboard'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(MonitorVideoSerializer)
                         })
    def get(self, request, station_id, *args, **kwargs):
        data = statistics_service.get_station_video(station_id)
        if not data:
            dt = {
                "appKey": "eb0a94043b084a18adafe228ed5f8566",
                "appSecret": "8313bbd05dbbfe78f1c9fd4e12db4954"
            }
            rst = requests.post("https://open.ys7.com/api/lapp/token/get",
                                data=dt).json()
            accessToken = rst["data"]["accessToken"]
            data.append({
                "name": "一期配电间1号摄像头",
                "token": accessToken,
                "url": "ezopen://open.ys7.com/D70019019/1.hd.live",
                "deviceSerial": "D70019019"
            })
        data = general_message(list=data)
        return JsonResponse(data)


@method_decorator(gzip_page, name='dispatch')
class MonitorAlarmLView(BaseApiView):
    @swagger_auto_schema(operation_description="获取监控视频列表",
                         tags=['dashboard'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(MonitorVideoSerializer)
                         })
    def get(self, request, *args, **kwargs):
        if self.enterprise.id == 1001:
            dt = [
                {
                    "customer_id": 90035,
                    "customer_name": "长沙综保投资有限公司",
                    "point_name": "5号配电房-1号变压器301",
                    "device_id": "1B003A0C473831353337351F",
                    "device_type": 4,
                    "device_status": 3,
                    "alarm_type": 2,
                    "alarm_level": 2,
                    "alarm_value": 190.596,
                    "alarm_times": 1,
                    "start_time": "2021-07-09T03:30:27",
                    "last_time": "2021-07-09T03:50:27",
                    "duration": 20
                },
                {
                    "customer_id": 90035,
                    "customer_name": "长沙综保投资有限公司",
                    "point_name": "5号配电房-2号变压器401",
                    "device_id": "1B003A0C473831353337351F",
                    "device_type": 4,
                    "device_status": 3,
                    "alarm_type": 2,
                    "alarm_level": 2,
                    "alarm_value": 190.596,
                    "alarm_times": 1,
                    "start_time": "2021-07-09T10:50:27",
                    "last_time": "2021-07-09T11:05:27",
                    "duration": 15
                }
            ]
            data = general_message(list=dt, count=len(dt))
            return JsonResponse(data)
        if self.enterprise.id == 1000:
            dt = statistics_service.get_new_monitor_alarm()
            data = general_message(list=dt, count=len(dt))
            return JsonResponse(data)
        rst = statistics_service.get_monitor_alarm()
        data = general_message(list=rst, count=len(rst))
        return JsonResponse(data)


class MonitorRealDataLView(BaseApiView):
    @swagger_auto_schema(operation_description="获取监控实时数据",
                         tags=['dashboard'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(MonitorVideoSerializer)
                         })
    def get(self, request, *args, **kwargs):
        query = request.GET.copy()
        entids = self.enterprise_ids
        rst, _ = statistics_service.get_real_data(join_ents=entids, **query)
        data = general_message(list=rst)
        return JsonResponse(data)


class MonitorMonthEPLView(BaseApiView):
    @swagger_auto_schema(operation_description="获取监控月用电量",
                         tags=['dashboard'],
                         responses={
                             status.HTTP_200_OK:
                                 serializer_assembly(MonitorVideoSerializer)
                         })
    def get(self, request, *args, **kwargs):
        enterprise_id = request.GET.get("enterprise_id")
        if not enterprise_id:
            enterprise_id = self.enterprise_ids
        rst = statistics_service.get_month_ep(enterprise_id)
        data = general_message(bean={"month_ep": abs(float(rst)) if rst else rst})
        return JsonResponse(data)


class UserLocationView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        # if "1" in self.:
        return Response(general_message(bean=get_all_user_recent_location(self.enterprise_ids)))


class UserHistoryLocation(ManagerApiView):
    def get(self, request, *args, **kwargs):
        return Response(
            general_message(list=get_all_user_history_last_location()))


class ScoreView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        power_number = request.GET.get("power_number")
        if not power_number:
            return Response(error_message(code=400, msg_show="户号是必须的"))
        data = {
            "economic_score": get_economic_score(**{"power_number": power_number}),
            "security_score": get_security_score(**{"power_number": power_number}),
            "quality_score": get_quality_score(**{"power_number": power_number})
        }
        return Response(general_message(bean=data))
