from django.db import transaction
from rest_framework.decorators import action

from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from utils.permission import IsTenantUser, permission_required
from .models import InspectionOrder
from .filters import InspectionOrderFilter
from .serializers import InspectionOrderSerializer


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

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

    @action(methods=['post'], detail=True)
    def turn_repair(self, request, pk):
        # 转报修
        try:
            if not self.request.user.has_perm('inspection_order.dturn_repair_inspection_order'):
                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('转报修完成！')
