# coding=utf-8
from django.db import transaction
from rest_framework import generics
from rest_framework.decorators import action
from utils import response_ok, response_error
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from utils.permission import IsTenantUser, isLogin
from apps.tenant.inspection_order.models import InspectionOrder
from apps.tenant.inspection_order.filters import InspectionOrderFilter
from apps.upload.models import Upload
from .serializers import InspectionOrderSerializer, InspectionOrderListSerializer, InspectionOrderDetailSerializer
from apps.log.models import BizLog
from apps.tenant import tenant_log
from utils.permission import IsTenantUser, permission_required


class InspectionOrderDetailView(generics.RetrieveAPIView):
    permission_classes = [isLogin, ]
    queryset = InspectionOrder.objects.filter(status=InspectionOrder.NOT_REPAIR)
    serializer_class = InspectionOrderDetailSerializer

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return response_ok(serializer.data)


class InspectionOrderAllView(generics.ListAPIView):
    permission_classes = [isLogin, ]
    queryset = InspectionOrder.objects.filter(status=InspectionOrder.NOT_REPAIR)
    serializer_class = InspectionOrderListSerializer

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


class InspectionOrderViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = InspectionOrder.objects.filter()
    serializer_class = InspectionOrderSerializer

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

    def perform_create(self, serializer):
        super(InspectionOrderViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(self.request.user.employee, BizLog.INSERT, u'添加巡检[%s]，id=%d' % (instance.no, instance.id),
                   validated_data)

    @action(methods=['get'], detail=True)
    def turn_repair(self, request, pk):
        # 转报修
        try:
            if not self.request.user.is_employee():
                raise CustomError(u"权限不足，禁止操作！")
            with transaction.atomic():
                user = self.request.user
                instance = InspectionOrder.get_instance_by_id(pk, user.employee.tenant)
                instance.turn_repair(user)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('转报修完成！')

    @action(methods=['post'], detail=False)
    def upload_image(self, request):
        file = self.request.FILES.get('file')
        user = self.request.user
        upload = Upload.objects._addnew(user.employee.tenant, user, Upload.INSPECTION_IMAGE, file)
        if upload:
            return response_ok(upload.id)
        return response_error('上传失败，请重新上传！')
