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

from drf_yasg.utils import swagger_auto_schema

from rest_framework.response import Response
from common.utils.views import AllowAnyApiView
from .serializers import AcrelADW300HJ4GSerializer
from common.utils.serializers import BaseResponesSerializer
from common.utils.services import monitor_service
from rest_framework.serializers import ValidationError
from common.utils.models import MonitorPoints, MonitorDevice
from common.utils.encryption import trans_vl


logger = logging.getLogger('')


class AcrelADW300HJ4GView(AllowAnyApiView):
    @swagger_auto_schema(
        operation_description="""
        ### 安科瑞 ADW300-HJ-4G 监控接口
        - md5加盐 "dgj" + sn + "cet"
        """,
        manual_parameters=[
        ],
        request_body=AcrelADW300HJ4GSerializer,
        responses={
            200: BaseResponesSerializer(),
            400: BaseResponesSerializer()
        },
        tags=['Acrel'],
    )
    def post(self, request, *args, **kwargs):
        req_dt = request.POST.get("data")
        alarm = request.POST.get("alarm")
        tm = request.POST.get("time")
        try:
            if req_dt:
                req_dt = json.loads(req_dt)
        except Exception as e:
            logger.debug(e)
            raise ValidationError
        dt = {
            "imei": request.POST.get("imei"),
            "v": request.POST.get("v"),
            "tm": tm,
        }
        if alarm:
            dt.update({"alarm": alarm})
        elif req_dt:
            dt.update({"data": req_dt})
        else:
            raise ValidationError
        serializer = AcrelADW300HJ4GSerializer(data=dt)
        serializer.is_valid(raise_exception=True)
        alarm = serializer.data.get("alarm", 0)
        imei = serializer.data["imei"]
        table, point_id, current_ratio, voltage_ratio = monitor_service.get_target_table(imei)
        monitor_service.update_by_alarm_status(alarm, imei, point_id, tm)
        monitor_service.insert_raw_or_create_tb(table, imei, point_id,
                                                serializer.data, tm,
                                                current_ratio, voltage_ratio)
        data = {"result": "ok"}
        return Response(data, status=200)


class AcrelADWView(AllowAnyApiView):
    @swagger_auto_schema(
        operation_description="""
        ### 安科瑞 ADW 监控接口
        - md5加盐 "dgj" + sn + "cet"
        """,
        manual_parameters=[
        ],
        request_body=AcrelADW300HJ4GSerializer,
        responses={
            200: BaseResponesSerializer(),
            400: BaseResponesSerializer()
        },
        tags=['Acrel'],
    )
    def post(self, request, *args, **kwargs):
        req_dts = trans_vl(request.POST.get("data"))
        alarm = request.POST.get("alarm", 0)
        iccid = request.POST.get("iccid")
        tm = request.POST.get("time")
        dt = {
            "imei": request.POST.get("imei"),
            "v": request.POST.get("v"),
            "tm": tm,
            "alarm": alarm,
            "data": req_dts,
            "iccid": iccid
        }
        serializer = AcrelADW300HJ4GSerializer(data=dt)
        serializer.is_valid(raise_exception=True)
        alarm = serializer.data.get("alarm", 0)
        iccid = serializer.data.get("iccid", None)
        imei = serializer.data["imei"]
        if iccid:
            monitor_service.update_by_iccid(imei, iccid)
            data = {"result": "ok"}
            return Response(data, status=200)
        table, point_id, current_ratio, voltage_ratio = monitor_service.get_target_table(imei)
        monitor_service.update_by_alarm_status(alarm, imei, point_id, tm)
        monitor_service.insert_raw_or_create_tb(table, imei, point_id,
                                                serializer.data, tm,
                                                current_ratio, voltage_ratio)
        # 转发到oa
        if req_dts:
            monitor_service.send_to_oa_cet_v2(serializer.data)
        data = {"result": "ok"}
        return Response(data, status=200)
