from rest_framework import serializers
from rest_framework.serializers import ModelSerializer, PrimaryKeyRelatedField

from common.third_party_api.amap.openapi import AmapApi
from common.utils.exceptions import ValidationError

from console.electricityuser.models import ElectricityUser
from console.customer.models import Customer
from console.powerstation.models import Transformer


class ElectricityUserSerializer(ModelSerializer):
    customer = PrimaryKeyRelatedField(queryset=Customer.objects.all())

    def to_representation(self, instance):
        customer_obj = instance.customer
        if not customer_obj:
            raise ValidationError("没有关联客户")
        else:
            ret = super(ElectricityUserSerializer,
                        self).to_representation(instance)
            ret["customer"] = customer_obj.id
            return ret

    class Meta:
        model = ElectricityUser
        fields = ('id', 'number', 'customer', 'addr', 'postcode',
                  'transformer_capacity', 'real_capacity', 'voltage_level',
                  'ep_factor', 'type', 'trusteeship_num', 'billing_method',
                  'householder', 'phone', 'is_md')

    def validate(self, attrs):
        addr = attrs['addr']
        if not addr:
            raise ValidationError('请输入地址')
        geocodes = AmapApi().geo(address=str(addr))['geocodes']
        if not len(geocodes):
            raise ValidationError('地址无效请修改')
        else:
            attrs['ad_code'] = geocodes[0]['adcode']
        return attrs


class ElectricityUserUpdateSerializer(serializers.Serializer):
    number = serializers.CharField(required=True, allow_blank=False, allow_null=False)
    customer = serializers.CharField(required=True, allow_null=False, allow_blank=False)
    addr = serializers.CharField(required=False, allow_null=True, allow_blank=True)
    postcode = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    transformer_capacity = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    real_capacity = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    voltage_level = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    ep_factor = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    trusteeship_num = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    type = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    billing_method = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    householder = serializers.CharField(required=False, allow_blank=True, allow_null=True)
    phone = serializers.CharField(required=False, allow_blank=True, allow_null=True)

    def update(self, instance, validated_data):
        instance.number = validated_data.get("number")
        instance.customer_id = validated_data.get("customer")
        instance.addr = validated_data.get("addr")
        instance.postcode = validated_data.get("postcode")
        instance.transformer_capacity = validated_data.get("transformer_capacity")
        instance.real_capacity = validated_data.get("real_capacity")
        instance.voltage_level = validated_data.get("voltage_level")
        instance.ep_factor = validated_data.get("ep_factor")
        instance.trusteeship_num = validated_data.get("trusteeship_num")
        instance.type = validated_data.get("type")
        instance.billing_method = validated_data.get("billing_method")
        instance.householder = validated_data.get("householder")
        instance.phone = validated_data.get("phone")
        instance.save()
        return instance


class ElectricityUserListSerializer(ModelSerializer):
    customer = serializers.SerializerMethodField()

    # real_capacity = serializers.SerializerMethodField()
    # transformer_capacity = serializers.SerializerMethodField()

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

    class Meta:
        model = ElectricityUser
        fields = ('id', 'customer', 'number', 'addr', 'type',
                  'trusteeship_num', 'created_time', "real_capacity",
                  "transformer_capacity")


class ElectricityUserDetailSerializer(ModelSerializer):
    customer = PrimaryKeyRelatedField(queryset=Customer.objects.all())
    province = serializers.CharField()
    city = serializers.CharField()
    area = serializers.CharField()

    def to_representation(self, instance):
        # if not Customer.objects.filter(id=instance.customer_id).exists():
        #     raise ValidationError("户号 %s 绑定的客户不存在" % instance.number)
        # geocodes = AmapApi.geo(address=str(instance.addr))['geocodes']
        # if not len(geocodes):
        #     raise ValidationError('地址无效请修改')
        # province = geocodes[0]['province']
        # city = geocodes[0]['city']
        # area = geocodes[0]['district']
        # location = geocodes[0]['location'].split(",", 1)
        # if instance.ad_code is None:
        #     instance.ad_code = geocodes[0]['adcode']
        #     instance.save()

        # 获取户号下面的所有变压器
        transfer = Transformer.objects.filter(ele_number=instance.number)
        # 获取户号下面所有的电站的变压器装机容量
        transformer_capacity = transfer.values_list("capacity", flat=True)
        transformer_capacity = sum(transformer_capacity)
        # 获取户号下面所有电站的变压器实际容量
        real_capacity = transfer.values_list("real_capacity", flat=True)
        real_capacity = sum(real_capacity)
        # 更新户号的变压器装机容量和实际容量
        instance.transformer_capacity = transformer_capacity
        instance.real_capacity = real_capacity
        instance.save()
        return {
            'id': instance.id,
            'customer': {
                "id": instance.customer.id,
                "name": instance.customer.name
            },
            'number': instance.number,
            # 'city_code': instance.city_code,

            # "province": instance.province,
            # "city": instance.city,
            # "area": instance.area,
            "addr": instance.addr,
            "postcode": instance.postcode,
            "transformer_capacity": instance.transformer_capacity,
            "real_capacity": instance.real_capacity,
            "voltage_level": instance.voltage_level,
            # "power_number": instance.power_number,
            "ep_factor": instance.ep_factor,
            "type": instance.type,
            "trusteeship_num": instance.trusteeship_num,
            'billing_method': instance.billing_method,
            # "station_num": instance.station_num,

            # "longitude": location[0],
            "longitude": instance.longitude,
            # "latitude": location[1],
            "latitude": instance.latitude,
            "householder": instance.householder,
            "phone": instance.phone,
            "is_md": instance.is_md,
            "transformer_count": transfer.count()
        }

    class Meta:
        model = ElectricityUser
        fields = ('id', 'number', 'customer', 'addr', 'province', 'city',
                  'area', 'transformer_capacity', 'real_capacity',
                  'billing_method', 'voltage_level', 'ep_factor', 'type',
                  'postcode', 'trusteeship_num', 'longitude', 'latitude',
                  'householder', 'phone', 'is_md', "transformer_count")
