# coding=utf-8

import json
import ast
from django.db import transaction
from rest_framework.decorators import action
from rest_framework.views import APIView
from django.db.models import Q
from utils import response_ok
from utils.permission import permission_required, isLogin
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from apps.images.models import Images
from apps.vehicle.models import Brand, Series, Model, VehicleImg
from apps.vehicle.filters import BrandFilter, SeriesFilter, ModelFilter, VehicleImgFilter
from .serializers import BrandSerializer, SeriesSerializer, ModelSerializer, VehicleImgSerializer
from apps.account import tenant_log
from apps.foundation.models import BizLog

class DictView(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        ret = {
            'brand': BrandSerializer(Brand.objects.filter(delete=False, enabled=True, ), many=True).data,
            'series': SeriesSerializer(Series.objects.filter(delete=False, enabled=True, ), many=True).data
        }
        return response_ok(ret)

class VehicleBrandViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Brand.objects.filter(delete=False)
    serializer_class = BrandSerializer

    def filter_queryset(self, queryset):
        # queryset = queryset.filter(tenant=self.request.user.employee.tenant)
        f = BrandFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(VehicleBrandViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加整车品牌[%s]，id=%d' % (instance.name, instance.id),validated_data)

    def perform_update(self, serializer):
        super(VehicleBrandViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.UPDATE, u'修改整车品牌[%s]，id=%d' % (instance.name, instance.id), validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            tenant_log(self.request.user, BizLog.DELETE, u'删除整车品牌[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()


class VehicleSeriesViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Series.objects.filter(delete=False, brand__delete=False)
    serializer_class = SeriesSerializer

    def filter_queryset(self, queryset):
        # queryset = queryset.filter(tenant=self.request.user.employee.tenant)
        f = SeriesFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(VehicleSeriesViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加整车车系[%s]，id=%d' % (instance.name, instance.id),validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            tenant_log(self.request.user, BizLog.DELETE, u'删除整车车系[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()

    @action(methods=['post'], detail=True)
    def update_series(self, request, pk):
        file = request.FILES.get('image', None)
        user = request.user
        instance = self.get_object()
        if instance.delete:
            raise CustomError(u'该车系已删除，禁止操作！')

        with transaction.atomic():
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)

            tenant_log(user, BizLog.UPDATE, u'修改车系[%s], id=%d' % (instance.name, instance.id), request.data)

            if file:
                old_thumbnail = instance.thumbnail
                thumbnail = Images.objects.employee_addnew(user, Images.VEHICLE_SERIES_THUMBNAIL, file)
                instance.thumbnail = thumbnail
                instance.save()
                if old_thumbnail:
                    old_thumbnail.del_images()
        return response_ok()


class VehicleModelViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Model.objects.filter(delete=False, series__delete=False, series__brand__delete=False)
    serializer_class = ModelSerializer

    def filter_queryset(self, queryset):
        # queryset = queryset.filter(tenant=self.request.user.employee.tenant)
        f = ModelFilter(self.request.GET, queryset=queryset)
        return f.qs

    def perform_create(self, serializer):
        super(VehicleModelViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user, BizLog.INSERT, u'添加整车型号[%s]，id=%d' % (instance.name, instance.id),validated_data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            instance.delete = True
            instance.save()
            tenant_log(self.request.user, BizLog.DELETE, u'删除整车型号[%s]，id=%d' % (instance.name, instance.id))
        return response_ok()

    @action(methods=['post'], detail=True)
    def update_model(self, request, pk):
        instance = self.get_object()
        user = request.user
        thumbnail = request.FILES.get('image', None)

        if instance.delete:
            raise CustomError(u'该车型已被删除，禁止操作！')

        with transaction.atomic():
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_update(serializer)

            tenant_log(self.request.user, BizLog.UPDATE, u'修改整车型号[%s]，id=%d' % (instance.name, instance.id), request.data)

            if thumbnail:
                old_thumbnail = instance.thumbnail
                thumbnail = Images.objects.employee_addnew(user, Images.VEHICLE_MODEL_THUMBNAIL, thumbnail)
                instance.thumbnail = thumbnail
                instance.save()
                if old_thumbnail:
                    old_thumbnail.del_images()

        return response_ok()

    @action(methods=['post'], detail=True)
    def upload_playbill(self, request, pk):
        # 整车上传海报
        if not self.request.user.has_perm('vehicle_model.edit_vehicle_model'):
            raise CustomError(u"您没有[车型管理-修改]权限，无法执行该操作，请联系管理员分配权限！")
        playbill = request.FILES.get('image', None)
        user = request.user
        vehicle_model = self.get_object()

        if vehicle_model.delete:
            raise CustomError(u'该整车型号已删除，禁止操作！')
        if not playbill:
            raise CustomError(u'未找到上传文件！')

        with transaction.atomic():
            tenant_log(user, BizLog.UPDATE, u'车型[%s]上传海报, id=%d' % (vehicle_model.name, vehicle_model.id))
            old_playbill = vehicle_model.playbill
            playbill = Images.objects.employee_addnew(user, Images.VEHICLE_MODEL_PLAYBILL, playbill)
            vehicle_model.playbill = playbill
            vehicle_model.save()
            if old_playbill:
                old_playbill.del_images()

        return response_ok()

    @action(methods=['post'], detail=True)
    def set_vehicle_img(self, request, pk):
        # 设置整车图片
        image = request.FILES.get('images', None)
        vehicle_model = self.get_object()

        if vehicle_model.delete:
            raise CustomError(u'该整车型号已删除，禁止操作！')
        if not image:
            raise CustomError(u'未找到上传文件！')

        with transaction.atomic():
            image = Images.objects.employee_addnew(request.user, Images.VEHICLE_MODEL_THUMBNAIL, image)
            VehicleImg.objects.create(vehicle_model=vehicle_model, img=image)
            tenant_log(request.user, BizLog.DELETE, u'车型[%s]上传整车图片儿，id=%d' % (vehicle_model.name, vehicle_model.id))

        return response_ok()

    @action(methods=['post'], detail=True)
    def set_model_img(self, request, pk):
        if not self.request.user.has_perm('vehicle_model.edit_vehicle_model'):
            raise CustomError(u"您没有[车型管理-修改]权限，无法执行该操作，请联系管理员分配权限！")
        image = request.FILES.get('images', None)
        type_id = request.POST.get('type')
        user = request.user
        vehicle_model = self.get_object()

        if vehicle_model.delete:
            raise CustomError(u'该整车型号已删除，禁止操作！')
        if not image:
            raise CustomError(u'未找到上传文件！')

        with transaction.atomic():
            img = Images.objects.employee_addnew(user, Images.VEHICLE_MODEL_IMAGES, image)
            VehicleModelImg.objects.create(vehicle_model=vehicle_model, img=img)
            tenant_log(request.user, BizLog.INSERT, u'车型[%s]上传车型分类图片儿，id=%d' % (vehicle_model.name, vehicle_model.id))
        return response_ok()


class VehicleImageViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = VehicleImg.objects.filter()
    serializer_class = VehicleImgSerializer

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

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)

    def destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            tenant_log(self.request.user, BizLog.DELETE, u'删除车型[%s]整车图片，id=%d' % (instance.vehicle_model.name, instance.vehicle_model.id))
            img = instance.img
            instance.delete()
            img.del_images()
        return response_ok()


class VehicleBrandSearch(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        keyword = request.GET.get('keyword')
        rows = Brand.objects.filter(delete=False, enabled=True)
        if keyword:
            rows = rows.filter(
                Q(name__icontains=keyword) |
                Q(brand__name__icontains=keyword)
            )

        data = []
        for row in rows:
            item = {
                'value': row.id,
                'id': row.id,
                'name': row.name,
                'notes': row.notes
            }
            data.append(item)

        return response_ok(data)

class VehicleSeriesSearch(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        keyword = request.GET.get('keywords')
        rows = Series.objects.filter(delete=False, enabled=True, brand__delete=False, brand__enabled=True)
        if keyword:
            rows = rows.filter(
                Q(name__icontains=keyword) |
                Q(brand__name__icontains=keyword)
            )
        serializer = SeriesSerializer(rows, many=True)
        return response_ok(serializer.data)


class VehicleModelSearch(APIView):
    permission_classes = [isLogin, ]

    def get(self, request):
        keyword = request.GET.get('keyword')
        rows = Model.objects.filter(
            delete=False, enabled=True, series__delete=False, series__enabled=True, series__brand__delete=False,
            series__brand__enabled=True,
        )
        if keyword:
            rows = rows.filter(
                Q(name__icontains=keyword) |
                Q(series__brand__name__icontains=keyword)|
                Q(series__name__icontains=keyword)
            )
        serializer = ModelSerializer(rows, many=True)
        return response_ok(serializer.data)

