# coding=utf-8

from django.db import transaction

from rest_framework.decorators import action

from utils import response_ok
from utils.custom_modelviewset import CustomModelViewSet
from apps.foundation.models import BizLog
from apps.account import tenant_log

from .filters import *
from .serializers import *
from .models import *


class ProductOrderViewSet(CustomModelViewSet):
    queryset = ProductOrder.objects.filter(delete=False)
    serializer_class = ProductOrderSerializer

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

    @action(methods=['post'], detail=True)
    def finish(self, request, pk):
        order = ProductOrder.objects.filter(id=pk).first()
        with transaction.atomic():
            if order.status == ProductOrder.WAIT_PAY:
                raise CustomError(u'订单未支付！')
            if order.status == ProductOrder.FINISHED:
                raise CustomError(u'订单已完成！')
            order.status = ProductOrder.FINISHED
            order.save()
            tenant_log(self.request.user, BizLog.UPDATE,
                       u'修改商品订单状态[%s]，id=%d' % (ProductOrder.STATUS_CHOICES[order.status - 1][1], order.id))
        return response_ok()