# coding=utf-8

from django.db import transaction
from django.utils import timezone

from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework import generics

from utils import response_ok
from utils.permission import IsEmployee
from utils.exceptions import CustomError
from utils.custom_modelviewset import CustomModelViewSet

from apps.log.models import BizLog
from apps.images.models import Images
from apps.order.models import *
from apps.order.filters import *
from apps.order.serializers import *
from apps.option.models import Option
from apps.base import Formater


class OrderDict(APIView):
    permission_classes = [IsEmployee, ]

    def get(self, request):
        rows = Option.objects.filter(type=Option.EXPRESS_COMPANY, enable=True, delete=False).order_by('sort').values('id', 'name')
        data = [{'value': row['id'], 'name': row['name']} for row in rows]
        ret = {
            'express_company': data
        }
        return response_ok(ret)


class OrderViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = Order.objects.filter()
    serializer_class = OrderSerializer

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

    @action(methods=['get'], detail=True)
    def get_details(self, request, pk):
        '''
        获取详细订单
        :param request:
        :param pk:
        :return:
        '''
        order = self.get_object()
        details = OrderDetails.objects.filter(order=order).order_by('-id')
        data = OrderDetailsSerializer(details, many=True).data
        return response_ok(data)

    @action(methods=['post'], detail=True)
    def submit_express(self, request, pk):
        '''
        快递信息添加/修改
        :param request:
        :param pk:
        :return:
        '''
        order = self.get_object()
        express_no =request.POST.get('express_no')
        express_company = request.POST.get('express_company')
        if order.status != Order.WAIT_DISPATCH:
            raise CustomError(u'该订单状态禁止发货！')
        try:
            express_company_id = int(express_company)
        except:
            raise CustomError(u'无效的快递公司ID！')
        express_company = Option.objects.filter(id=express_company_id).first()
        if not express_company.enable:
            raise CustomError(u'该快递公司已被禁用！')
        if express_company.delete:
            raise CustomError(u'该快递公司已被删除！')
        with transaction.atomic():
            order.status = Order.WAIT_EVALUATE
            order.dispatch_time = timezone.now()
            order.dispatch_user = request.user
            order.express_no = express_no
            order.express_company = express_company
            order.save()
        return response_ok()

    @action(methods=['post'], detail=True)
    def cancel_order(self, request, pk):
        '''
        取消订单
        :param request:
        :param pk:
        :return:
        '''
        cancel_reason = request.POST.get('cancel_reason')
        order = self.get_object()
        if order.status == Order.CANCEL:
            raise CustomError(u'该订单已取消，禁止重复操作！')
        if order.status != Order.WAIT_PAY:
            raise CustomError(u'该订单已付款，禁止取消！')
        with transaction.atomic():
            order.status = Order.CANCEL
            order.cancel_reason = cancel_reason
            order.cancel_user = request.user
            order.cancel_time = timezone.now()
            order.save()
        return response_ok()
