from django.db.models import Q
from rest_framework.response import Response

from common.accounts.models import Users
from common.utils.return_structure import general_message
from common.utils.service_code import PARAMETER_ERROR
from common.utils.return_structure import error_message
from common.utils.pagination import CustomPageNumberPagination
from common.utils.exceptions import ValidationError
from common.utils.views import AllowAnyApiView, BaseApiView, ManagerApiView

from console.home_page.serializers import HomePageSerializer
from console.customer.models import CustomerAdmin
from console.home_page.services import get_station_ep
from console.powerstation.models import PowerStation
from console.home_page.services import get_monitor_data
from console.home_page.services import web_homepage_statistic
from console.home_page.services import order_status, inspection_task_data
from console.inspection.models import InspectionTask
from console.inspection.serializers import InspectionTaskSerializer
from console.order.models import Order
from console.home_page.serializers import OrderSerializer
from console.home_page.services import temperature_humidity
from console.team.models import Team


class HomePageStatisticView(BaseApiView):
    def get(self, request, *args, **kwargs):
        user = Users.objects.filter(account=request.user,
                                    deleted=False).first()
        customer_account = CustomerAdmin.objects.filter(user=user).first()
        if not customer_account:
            raise ValidationError("当前用户是非客户账号！")
        serializer = HomePageSerializer(customer_account.customer)
        return Response(general_message(bean=serializer.data))


class StationEPView(BaseApiView):
    def get(self, request, *args, **kwargs):
        station = PowerStation.objects.filter(
            id=request.GET.get("station_id")).first()
        if not station:
            return Response(
                error_message(code=PARAMETER_ERROR,
                              msg_show="电站%s不存在" %
                                       request.GET.get("station_id")))
        type = request.GET.get("type")
        start_time = request.GET.get("start_time")
        end_time = request.GET.get("end_time")
        if type not in ["day", "week", "month", "year"]:
            raise ValidationError("日期筛选参数不合法")
        data = {
            "station": station,
            "type": type,
            "start_time": start_time,
            "end_time": end_time
        }
        return Response(general_message(bean=get_station_ep(**data)))


class MonitorTestData(AllowAnyApiView):
    def get(self, request, *args, **kwargs):
        return Response(general_message(list=get_monitor_data()))


class WebHomePageStatisticView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        return Response(
            general_message(bean=web_homepage_statistic(request.user, self.enterprise_ids)))


class OrderStatusView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        param = {
            "type": request.GET.get("type"),
            "start_time": request.GET.get("start_time"),
            "end_time": request.GET.get("end_time"),
            "enterprise_ids": self.enterprise_ids
        }
        return Response(general_message(bean=order_status(**param)))


class InspectionTaskStatusView(ManagerApiView):
    def get(self, request, *args, **kwargs):
        param = {
            "type": request.GET.get("type"),
            "start_time": request.GET.get("start_time"),
            "end_time": request.GET.get("end_time"),
            "enterprise_ids": self.enterprise_ids
        }
        return Response(general_message(bean=inspection_task_data(**param)))


class InspectionTaskListView(ManagerApiView):
    queryset = InspectionTask.objects.exclude(
        status="completed").prefetch_related(
        'team', "plan", "plan__station", "plan__leader",
        "plan__station__customer", "plan__station__electricity_user",
        "plan__station__electricity_user__customer").order_by("-work_date")
    serializer_class = InspectionTaskSerializer
    pagination_class = CustomPageNumberPagination

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        user = Users.objects.filter(account=request.user).first()
        team = Team.objects.filter(Q(team_headman=user) | Q(member=user),
                                   deleted=False).first()
        if self.is_manager:
            queryset = self.get_queryset().filter(
                plan__station__customer__service_enterprise_id__in=self.enterprise_ids)
        else:
            queryset = self.get_queryset().filter(plan__station__customer_id__in=[self.customer.id])
        if team and team.type in ["2", "3"]:
            queryset = queryset.filter(team=team)

        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            general_message(list=serializer.data, count=queryset.count()))


class OrderListView(ManagerApiView):
    queryset = Order.objects.exclude(status="completed").prefetch_related(
        'team', "task", "task__customer")
    serializer_class = OrderSerializer
    pagination_class = CustomPageNumberPagination

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(task__customer__service_enterprise_id__in=self.enterprise_ids)
        user = Users.objects.filter(account=request.user).first()
        team = Team.objects.filter(Q(team_headman=user) | Q(member=user),
                                   deleted=False).first()
        if team and team.type in ["2", "3"]:
            queryset = queryset.filter(team=team)
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return Response(
            general_message(list=serializer.data, count=queryset.count()))


class TemperatureHumidityView(BaseApiView):
    def get(self, request, *args, **kwargs):
        return Response(general_message(bean=temperature_humidity()))
