import datetime

from django.db.models import Q, Sum
from rest_framework import serializers as serializer

from console.customer.models import Customer
from console.electricityuser.models import ElectricityUser
from console.inspection.models import InspectionTask
from console.powerstation.models import PowerStation
from console.order.models import Order


class HomePageSerializer(serializer.ModelSerializer):
    operating_days = serializer.SerializerMethodField()
    total_load = serializer.SerializerMethodField()
    inspection_completed_num = serializer.SerializerMethodField()

    def get_operating_days(self, obj):
        power_station = PowerStation.objects.filter(
            Q(customer=obj)
            | Q(electricity_user__customer_id=obj.id)).order_by(
                "start_time").first()
        if not power_station:
            return 0
        if not power_station.start_time:
            power_station.start_time = datetime.datetime.now()
            power_station.save()
        days = (datetime.datetime.now().date() -
                power_station.start_time.date()).days + 1
        return days

    def get_total_load(self, obj):
        data = ElectricityUser.objects.filter(
            customer=obj,
            deleted=False).aggregate(sum=Sum("transformer_capacity"))
        return data.get("sum")

    def get_inspection_completed_num(self, obj):
        count = InspectionTask.objects.filter(
            Q(plan__station__customer=obj)
            | Q(plan__station__electricity_user__customer=obj),
            status="completed").count()

        return count

    class Meta:
        model = Customer
        fields = ("operating_days", "total_load", "inspection_completed_num")


class OrderSerializer(serializer.ModelSerializer):
    customer = serializer.SerializerMethodField()
    team = serializer.SerializerMethodField()

    def get_customer(self, obj):
        return {
            "id": obj.task.customer.id,
            "name": obj.task.customer.name
        } if obj.task.customer else None

    def get_team(self, obj):
        return {
            "id":
            obj.team.id,
            "name":
            obj.team.name,
            "team_headman":
            obj.team.team_headman.nickname if obj.team.team_headman else None
        } if obj.team else None

    class Meta:
        model = Order
        fields = ("id", "name", "customer", "type", "status", "created_time",
                  "team")
