from rest_framework.response import Response

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.customer_system.services import get_customer_power_data, \
    get_customer_power_statistic, get_customer_recent_month_power_data, \
    get_customer_recent_month_activate_power, get_customer_recent_month_power, \
    get_customer_power_factor, get_10_day_power

from console.customer_system.serializers import PowerInfoSerializer
from console.electricityuser.models import ElectricityUser

from console.customer_system.services import get_6_month_power


class CustomerPowerView(BaseApiView):
    def get(self, request, *args, **kwargs):
        data = get_customer_power_data(**{"customer_id": self.customer.id})
        return Response(general_message(bean=data))


class StatisticView(BaseApiView):

    def get(self, request, *args, **kwargs):
        data = get_customer_power_statistic(customer_id=self.customer.id)
        return Response(general_message(bean=data))


class RecentMonthPowerView(BaseApiView):
    def get(self, request, *args, **kwargs):
        customer_id = self.customer.id
        type = request.GET.get("type")
        if not customer_id or not type:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="参数传递错误"))
        METHOD_MAP = {
            "power_data": get_customer_recent_month_power_data,
            "power": get_customer_recent_month_activate_power,
            "active_power": get_customer_recent_month_power,
            "power_factor": get_customer_power_factor
        }
        data = METHOD_MAP.get(type)(customer_id=customer_id)
        return Response(general_message(bean=data))


class RecentTenDayPowerView(BaseApiView):
    def get(self, request, *args, **kwargs):
        customer_id = self.customer.id
        if not customer_id:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="客户id是必须的"))
        data = get_10_day_power(customer_id=customer_id)
        return Response(general_message(bean=data))


class PowerInfoView(BaseApiView):
    queryset = ElectricityUser.objects.filter(deleted=False)
    serializer_class = PowerInfoSerializer

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(number=request.GET.get("ele_number")).first()
        serializer = self.get_serializer(queryset)
        return Response(general_message(bean=serializer.data))


class RecentSixMonthPowerView(BaseApiView):
    def get(self, request, *args, **kwargs):
        customer_id = self.customer.id
        if not customer_id:
            return Response(error_message(code=PARAMETER_ERROR, msg_show="客户id是必须的"))
        data = get_6_month_power(customer_id=customer_id)
        return Response(general_message(bean=data))
