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

from rest_framework.response import Response
from rest_framework.serializers import ValidationError
from drf_yasg.utils import swagger_auto_schema

from common.utils.views import AllowAnyApiView
from common.utils.serializers import BaseResponesSerializer
from common.utils.services import monitor_service

from .serializers import CET350BSerializer

from common.utils.encryption import trans_vl

logger = logging.getLogger('')


class zhongDianView(AllowAnyApiView):
    def post(self, request, *args, **kwargs):
        data = {"result": "ok"}
        return Response(data, status=200)


class CET350BView(AllowAnyApiView):
    @swagger_auto_schema(
        operation_description="""
        ### 安科瑞 ADW 监控接口
        - md5加盐 "dgj" + sn + "cet"
        """,
        manual_parameters=[
        ],
        request_body=CET350BSerializer,
        responses={
            200: BaseResponesSerializer(),
            400: BaseResponesSerializer()
        },
        tags=['Acrel'],
    )
    def post(self, request, *args, **kwargs):
        logger.debug(request.body)
        json_dt = json.loads(request.body)
        print(type(json_dt))

        tm = json_dt.get("time")
        req_dts = trans_vl(json_dt.get("data"))
        alarm = json_dt.get("alarm", 0)
        iccid = json_dt.get("iccid")
        dt = {
            "imei": json_dt.get("imei"),
            "v": json_dt.get("v"),
            "tm": tm,
            "alarm": alarm,
            "data": req_dts,
            "iccid": iccid
        }
        logger.debug(dt)
        serializer = CET350BSerializer(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)
