from apps.utils.serializers import CustomModelSerializer
from apps.utils.constants import EXCLUDE_FIELDS_BASE, EXCLUDE_FIELDS_DEPT
from .models import Drain, DrainEquip, EnvData, VehicleAccess, CarWash
from apps.em.serializers import EquipmentSerializer
from rest_framework import serializers
from django.utils import timezone
from datetime import datetime
from apps.utils.sql import query_all_dict
from apps.enp.sql import duration_hour_one_equip


class DrainSerializer(CustomModelSerializer):
    """Serializer for Drain model"""

    mgroup_name = serializers.CharField(source="mgroup.name", read_only=True)

    class Meta:
        model = Drain
        fields = "__all__"
        read_only_fields = EXCLUDE_FIELDS_DEPT

    def validate(self, attrs):
        attrs["belong_dept"] = attrs["mgroup"].belong_dept
        return super().validate(attrs)


class DrainWithEquipBaseSerializer(DrainSerializer):
    equip_data = serializers.SerializerMethodField()

    def get_equip_data(self, obj):
        equips = obj.equipments.all()
        odata = equips.values("id", "number", "name", "type", "running_state")
        return odata

class DrainWithEquipEnpSerializer(DrainSerializer):
    equip_data = serializers.SerializerMethodField()

    def get_equip_data(self, obj):
        equips = obj.equipments.all()
        now = datetime.now()
        today = str(now)[:10] + " 00:00:00"
        today_last = str(now)[:10] + " 23:59:59"
        odata = equips.values("id", "number", "name", "type", "running_state")
        for i in odata:
            i.update(
                {
                    "avg_tsp": None,
                    "duration_offline": 0,
                    "duration_run": 0,
                    "duration_stop": 0,
                }
            )
            equipment_id = i["id"]
            sql_str = duration_hour_one_equip.format(equipment_id=equipment_id, start_time=today, end_time=today_last)
            res = query_all_dict(sql_str)
            if res:
                i.update(res[0])

        return odata


class DrainEquipSerializer(CustomModelSerializer):
    equipment_type = serializers.CharField(source="equipment.type", read_only=True)
    equipment_name = serializers.CharField(source="equipment.name", read_only=True)

    class Meta:
        model = DrainEquip
        fields = "__all__"
        read_only_fields = EXCLUDE_FIELDS_BASE


class EnvDataSerializer(CustomModelSerializer):
    """Serializer for EnvData model"""

    class Meta:
        model = EnvData
        fields = "__all__"

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        for field_name in ("dust_rtd", "dust_zs", "temperature", "pressure", "speed", "humidity", "flux", "pm25", "pm10", "tsp", "wind_speed", "so2_rtd", "so2_zs", "nox_rtd", "nox_zs", "o2"):
            if representation[field_name]:
                representation[field_name] = round(representation[field_name], 4)
        return representation


class DrainEquipEnvSerializer(CustomModelSerializer):
    equipment_number = serializers.CharField(source="equipment.number", read_only=True)
    equipment_type = serializers.CharField(source="equipment.type", read_only=True)
    equipment_name = serializers.CharField(source="equipment.name", read_only=True)
    equipment_envdata = serializers.SerializerMethodField()
    equipment_ = EquipmentSerializer(source="equipment", read_only=True)
    drain_ = DrainSerializer(source="drain", read_only=True)

    def get_equipment_envdata(self, obj):
        now = timezone.now()
        now_10_before = now - timezone.timedelta(minutes=10)
        obj = EnvData.objects.filter(equipment=obj.equipment, time__gte=now_10_before, time__lte=now).order_by("-time").select_related("equipment").first()
        if obj:
            return EnvDataSerializer(instance=obj).data
        else:
            return {}

    class Meta:
        model = DrainEquip
        fields = "__all__"


class VehicleAccessSerializer(CustomModelSerializer):
    """Serializer for VehicleAccess model"""

    class Meta:
        model = VehicleAccess
        fields = "__all__"
        read_only_fields = EXCLUDE_FIELDS_BASE


class EnvDataExportSerializer(serializers.Serializer):
    time = serializers.DateTimeField(label="时间")
    type = serializers.ChoiceField(label="导出类型", choices=["hour", "day", "week", "month", "season", "year"])


class CarWashSerializer(CustomModelSerializer):
    station_name = serializers.CharField(source="station.name", read_only=True)

    class Meta:
        model = CarWash
        fields = "__all__"
