# coding=utf-8

import traceback

from django.db import transaction

from rest_framework import generics
from rest_framework.exceptions import NotFound
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from rest_framework.decorators import action

from util import response_ok, response_error
from util.wx.wechat import WeChat
from util.permission import IsCustomerUser
from util.exceptions import CustomError

from apps.foundation.models import BizLog
from apps.customer.order.serializers import OrderSerializer, ActivityOrderSerializer
from apps.activity.models import Activity, Order, Pay
from apps.activity.base import OrderUpdate
from apps.WechatApplet.models import WechatApplet
from apps.activity.filters import OrderFilter


class OrderViewSet(ModelViewSet):
    permission_classes = [IsCustomerUser, ]
    queryset = Order.objects.filter(delete=False)
    serializer_class = OrderSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            # 获取订单前更新订单状态
            OrderUpdate.update_status()
            data = super(OrderViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def create(self, request, *args, **kwargs):
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                serializer.is_valid(raise_exception=True)
                serializer.save()
                instance = serializer.instance
                validated_data = serializer.validated_data

                if instance.amount == 0:
                    instance.status = Order.FINISH
                    instance.save()
                    BizLog.objects.addnew(request.customer.user, BizLog.INSERT, u"添加商品订单,id=%d" % instance.id, validated_data)
                else:
                    openid = request.POST.get('openid', None)
                    if not openid:
                        raise CustomError(u'未获取openid！')
                    appid = request.POST.get('appid', None)
                    app = WechatApplet.getByAppid(appid)
                    profit_sharing = "N"
                    if instance.rebate > 0 and instance.recommend_member:
                        profit_sharing = "Y"
                    pay, query_string = Pay.wechatPay(app, instance.branch, instance.member, instance.amount, openid, profit_sharing)
                    instance.pay = pay
                    instance.save()
                    BizLog.objects.addnew(request.customer.user, BizLog.INSERT, u'添加商品订单，id=%d' % instance.id, validated_data)
                    if query_string:
                        return response_ok(query_string)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            traceback.print_exc()
            return response_error(str(e))
        return response_ok()

    @action(methods=['post'], detail=True)
    def pay_order(self, request, pk):
        openid = request.POST.get('openid')
        appid = request.POST.get('appid')
        try:
            if not openid:
                raise CustomError(u'未获取openid！')
            app = WechatApplet.getByAppid(appid)
            order = Order.objects.filter(id=pk).first()
            if not order:
                raise CustomError(u'未找到相应的订单')
            order.activity.checkStatus()
            with transaction.atomic():
                data = order.payOrder(openid, app)
                BizLog.objects.addnew(request.customer.user, BizLog.INSERT, u'支付订单，id=%d' % order.id, request.data)
            return response_ok(data)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            traceback.print_exc()
            return response_error(str(e))

    @action(methods=['post'], detail=True)
    def del_order(self, request, pk):

        try:
            order = Order.objects.filter(id=pk).first()
            if not order:
                raise CustomError(u'未找到相应的订单！')
            if order.delete:
                raise CustomError(u'该订单已删除！')

            with transaction.atomic():
                order.delete = True
                order.save()
                BizLog.objects.addnew(request.customer.user, BizLog.DELETE, u'删除订单，id=%d' % order.id, request.data)
            return response_ok()
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            traceback.print_exc()
            return response_error(str(e))


class ActivityOrderListView(generics.ListAPIView):
    '''
    小程序显示已有人购买订单列表--  查询这个活动的订单记录(删除的也显示)
    '''
    queryset = Order.objects.filter(status=Order.FINISH)
    serializer_class = ActivityOrderSerializer

    def filter_queryset(self, queryset):
        activity_id = self.request.GET.get('activity_id')
        activity = Activity.getById(activity_id)

        queryset = queryset.filter(activity=activity)
        f = OrderFilter(self.request.GET, queryset=queryset)
        return f.qs

    def list(self, request, *args, **kwargs):
        try:
            data = super(ActivityOrderListView, self).list(request)
        except NotFound:
            return response_ok([])
        return data
