# -*- coding=utf-8 -*-
from rest_framework.serializers import (ModelSerializer, Serializer,
                                        ValidationError, SerializerMethodField)
from rest_framework import serializers as serializer
from common.utils.service_code import PARAMETER_ERROR

from console.equipment.models import Equipment

from console.electricityuser.models import ElectricityUser
from console.powerstation.models import PowerStation


class EquipmentSerializer(ModelSerializer):
    electricity_user = SerializerMethodField()

    def get_electricity_user(self, obj):
        return {
            "id":
                obj.electricity_user.id,
            "number":
                obj.electricity_user.number,
            "customer":
                obj.electricity_user.customer.name
                if obj.electricity_user.customer else None
        } if obj.electricity_user else None

    class Meta:
        model = Equipment
        fields = ('id', 'name', "electricity_user")


class EquipmentDeleteSerializer(Serializer):
    def validate(self, attrs):
        if not isinstance(attrs, list):
            raise ValidationError("参数数据类型不对，应为list", code=PARAMETER_ERROR)
        return attrs


class EquipmentUpdateSerializer(Serializer):
    code = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)
    electricity = serializer.CharField(required=False,
                                       allow_blank=True,
                                       allow_null=True)
    electricity_user = serializer.CharField(required=False,
                                            allow_blank=True,
                                            allow_null=True)
    factory = serializer.CharField(required=False,
                                   allow_blank=True,
                                   allow_null=True)
    file = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)
    line_type = serializer.CharField(required=False,
                                     allow_blank=True,
                                     allow_null=True)

    model = serializer.CharField(required=False,
                                 allow_blank=True,
                                 allow_null=True)
    name = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)
    operation_date = serializer.CharField(required=False,
                                          allow_blank=True,
                                          allow_null=True)
    parent_id = serializer.IntegerField(required=False, allow_null=True)
    price = serializer.CharField(required=False,
                                 allow_blank=True,
                                 allow_null=True)
    production_code = serializer.CharField(required=False,
                                           allow_blank=True,
                                           allow_null=True)
    production_date = serializer.CharField(required=False,
                                           allow_blank=True,
                                           allow_null=True)
    station = serializer.CharField(required=False,
                                   allow_blank=True,
                                   allow_null=True)
    status = serializer.BooleanField(required=False, allow_null=True)
    transformer_capacity = serializer.CharField(required=False,
                                                allow_blank=True,
                                                allow_null=True)
    type = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)
    voltage = serializer.CharField(required=False,
                                   allow_blank=True,
                                   allow_null=True)

    def validate(self, attrs):
        if attrs.get("station"):
            station = PowerStation.objects.filter(
                id=attrs.get("station")).first()
            if not station:
                raise serializer.ValidationError("电站%s不存在" %
                                                 attrs.get("station"))
        if attrs.get("electricity_user"):
            ele_user = ElectricityUser.objects.filter(
                id=attrs.get("electricity_user")).first()
            if not ele_user:
                raise serializer.ValidationError("户号%s不存在" %
                                                 attrs.get("electricity_user"))
        return attrs

    def update(self, instance, validated_data):
        instance.code = validated_data.get("code")
        instance.electricity = validated_data.get("electricity")
        instance.electricity_user_id = validated_data.get("electricity_user")
        instance.factory = validated_data.get("factory")
        instance.file = validated_data.get("file")
        instance.line_type = validated_data.get("line_type")
        instance.model = validated_data.get("model")
        instance.name = validated_data.get("name")
        instance.operation_date = validated_data.get("operation_date")
        instance.parent_id = validated_data.get("parent_id")
        instance.price = validated_data.get("price")
        instance.production_code = validated_data.get("production_code")
        instance.production_date = validated_data.get("production_date")
        instance.station_id = validated_data.get("station")
        instance.status = validated_data.get("status")
        instance.transformer_capacity = validated_data.get(
            "transformer_capacity")
        instance.type = validated_data.get("type")
        instance.voltage = validated_data.get("voltage")
        instance.save()
        return instance


class EquipmentCreateSerializer(Serializer):
    station_id = serializer.CharField(required=False,
                                      allow_blank=True,
                                      allow_null=True)
    electricity_user = serializer.CharField(required=False,
                                            allow_blank=True,
                                            allow_null=True)
    name = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)
    code = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)
    production_code = serializer.CharField(required=False,
                                           allow_blank=True,
                                           allow_null=True)
    production_date = serializer.CharField(required=False,
                                           allow_blank=True,
                                           allow_null=True)
    operation_date = serializer.CharField(required=False,
                                          allow_blank=True,
                                          allow_null=True)
    file = serializer.CharField(required=False,
                                allow_blank=True,
                                allow_null=True)

    def create(self, validated_data):
        instance = Equipment.objects.create(
            station_id=validated_data.get("station_id"),
            electricity_user_id=validated_data.get("electricity_user"),
            name=validated_data.get("name"),
            code=validated_data.get("code"),
            production_code=validated_data.get("production_code"),
            production_date=validated_data.get("production_date"),
            operation_date=validated_data.get("operation_date"),
            file=validated_data.get("file"),
        )
        return instance


class EquipmentDataMetaCSerializer(Serializer):
    modular = serializer.IntegerField(required=False, help_text="根设备类型")
    type = serializer.IntegerField(help_text="设备类型")
    manufacturer = serializer.CharField(max_length=128,
                                        default="NA",
                                        help_text="厂商")
    model = serializer.CharField(max_length=128, default="NA", help_text="型号")
    production_date = serializer.DateField(allow_null=True, help_text="生产日期")
    operation_date = serializer.DateField(allow_null=True, help_text="投运日期")
    service_life = serializer.CharField(max_length=16,
                                        allow_null=True,
                                        help_text="使用年限")
    production_code = serializer.CharField(max_length=32,
                                           allow_null=True,
                                           help_text="出厂编号")
    current = serializer.CharField(max_length=32,
                                   allow_null=True,
                                   help_text="电流")
    voltage = serializer.CharField(max_length=32,
                                   allow_null=True,
                                   help_text="电压")
    capacity = serializer.CharField(max_length=16,
                                    allow_null=True,
                                    help_text="额定容量")
    real_capacity = serializer.CharField(required=False,
                                         max_length=16,
                                         allow_null=True,
                                         help_text="实际使用容量")
    img = serializer.CharField(required=False,
                               max_length=256,
                               allow_null=True,
                               help_text="图片")
    status = serializer.BooleanField(default=0,
                                     allow_null=True,
                                     help_text="状态")
    extra_data = serializer.JSONField(required=False,
                                      allow_null=True,
                                      help_text="额外数据")
    comments = serializer.CharField(required=False,
                                    max_length=256,
                                    allow_null=True,
                                    allow_blank=True,
                                    help_text="备注")


class EquipmentCSerializer(Serializer):
    customer_id = serializer.IntegerField(help_text="客户id")
    electricity_user_id = serializer.IntegerField(help_text="户号id")
    name = serializer.CharField(max_length=64, help_text="名称")
    pid = serializer.IntegerField(default=0, help_text="父节点id")
    data = EquipmentDataMetaCSerializer(required=False, help_text="设备详情")


class EquipmentUSerializer(EquipmentCSerializer):
    id = serializer.IntegerField(help_text="id")
    # update = EquipmentMetaUSerializer(many=True)
    # add = EquipmentMetaCSerializer(many=True)
    # delete = serializer.ListField(allow_empty=True, default=())


class EquimentInfoSerializer(serializer.ModelSerializer):
    customer_name = serializer.SerializerMethodField()
    code = serializer.SerializerMethodField()
    type = serializer.SerializerMethodField()
    model = serializer.SerializerMethodField()
    capacity = serializer.SerializerMethodField()
    manufacturer = serializer.SerializerMethodField()

    def get_customer_name(self, obj):
        return obj.customer.name if obj.customer else None

    def get_code(self, obj):
        return obj.electricity_user.number if obj.electricity_user else None

    def get_type(self, obj):
        return obj.equipment_data.type if obj.equipment_data else None

    def get_model(self, obj):
        return obj.equipment_data.model if obj.equipment_data else None

    def get_capacity(self, obj):
        return obj.equipment_data.capacity if obj.equipment_data else None

    def get_manufacturer(self, obj):
        return obj.equipment_data.manufacturer if obj.equipment_data else None

    class Meta:
        model = Equipment
        fields = ("id", "customer_name", "code", "name", "type", "model",
                  "capacity", "manufacturer")
