# coding=utf-8

from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.exceptions import NotFound
from utils.permission import IsCustomerUser

from utils import response_ok
from utils.exceptions import CustomError

from apps.usedvehicle.filters import UsedVehicleFilter
from apps.foundation.models import Option
from apps.usedvehicle.models import UsedVehicle

from .serializers import UsedVehicleSerializer, UsedVehicleDetailSerializer


class UsedVehicleListView(generics.ListAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = UsedVehicle.objects.filter(delete=False,status=UsedVehicle.STOCK)
    serializer_class = UsedVehicleSerializer

    def filter_queryset(self, queryset):
        f = UsedVehicleFilter(self.request.GET, queryset=queryset)
        return f.qs

    def list(self, request, *args, **kwargs):
        try:
            data = super(UsedVehicleListView, self).list(request)
        except NotFound:
            return response_ok([])
        return data


class OptionTypesView(APIView):
    def get(self, request):
        rows = Option.objects.filter(delete=False, enable=True).order_by('type')
        data = {
            'brands': rows.filter(type=Option.USED_VEHICLE_BRAND).values('id', 'name'), #品牌
            'gearboxs': rows.filter(type=Option.VEHICLE_GEARBOX).values('id', 'name'), #汽车变速箱
            'colors': rows.filter(type=Option.VEHICLE_COLOR).values('id', 'name'),#颜色
            'displacements': rows.filter(type=Option.VEHICLE_DISPLACEMENT).values('id', 'name'), #排量
            'emissions': rows.filter(type=Option.VEHICLE_EMISSION).values('id', 'name'),#排放标准
            'seat_counts': rows.filter(type=Option.VEHICLE_SEAT_COUNT).values('id', 'name'),#座位数
            'oil_types': rows.filter(type=Option.VEHICLE_OIL).values('id', 'name'),#燃油类型
        }
        return response_ok(data)

class UsedVehicleDetailView(generics.RetrieveAPIView):
    # permission_classes = [IsCustomerUser, ]
    queryset = UsedVehicle.objects.filter(delete=False,status=UsedVehicle.STOCK)
    serializer_class = UsedVehicleDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        id = request.GET.get('id')
        instance = self.queryset.filter(id=id).first()
        if not instance:
            raise CustomError(u'未找到相应的车辆！')
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)
