from django_filters import rest_framework as filter

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


class ElectricityUserFilter(filter.FilterSet):
    customer = filter.CharFilter(method='get_customer')
    postcode = filter.CharFilter(method='get_postcode')
    number = filter.CharFilter(method='get_number')
    province = filter.CharFilter(method='get_province')
    city = filter.CharFilter(method='get_city')
    area = filter.CharFilter(method='get_area')

    def get_province(self, queryset, name, value):
        geocodes = AmapApi().geo(address=str(value))['geocodes']
        if not len(geocodes):
            raise ValidationError('地址无效请修改')
        adcode = geocodes[0]['adcode'][0:2]
        if value:
            queryset = queryset.filter(ad_code__startswith=adcode)
        return queryset

    def get_city(self, queryset, name, value):
        if '城区' in value:
            value = value.replace('城区', '')
            geocodes = AmapApi().geo(address=str(value))['geocodes']
            if not len(geocodes):
                raise ValidationError('地址无效请修改')
            adcode = geocodes[0]['adcode'][0:2]
        else:
            geocodes = AmapApi().geo(address=str(value))['geocodes']
            if not len(geocodes):
                raise ValidationError('地址无效请修改')
            adcode = geocodes[0]['adcode'][0:4]
        if value:
            queryset = queryset.filter(ad_code__startswith=adcode)
        return queryset

    def get_area(self, queryset, name, value):
        geocodes = AmapApi().geo(address=str(value))['geocodes']
        if not len(geocodes):
            raise ValidationError('地址无效请修改')
        adcode = geocodes[0]['adcode']
        if value:
            queryset = queryset.filter(ad_code=adcode)
        return queryset

    def get_customer(self, queryset, name, value):
        if value:
            queryset = queryset.filter(customer__name__contains=value)
        return queryset

    def get_postcode(self, queryset, name, value):
        if value:
            queryset = queryset.filter(postcode__contains=value)
        return queryset

    def get_number(self, queryset, name, value):
        if value:
            queryset = queryset.filter(number__contains=value)
        return queryset
