# coding=utf-8
import json
from django.db.models import Sum, F
from django.db import transaction
from django.db.models import Q
from rest_framework.views import APIView
from utils.custom_modelviewset import CustomModelViewSet
from .serializers import *
from .filters import *
from apps.log.models import BizLog
from apps.base import Formater
from utils import response_ok, response_error
from utils.permission import isLogin
from apps.order.models import Order
from apps.WeChatResponse import WechatAppletPay
from apps.option.models import Balance
from django.contrib.auth import get_user_model

User = get_user_model()


class PackageView(APIView):

    def get(self, request):
        data = []
        queryset = Package.objects.filter()
        for row in queryset:
            item = {
                'id':row.id,
                'amount':Formater.formatPriceShow(row.amount),
                'give_amount':Formater.formatPriceShow(row.give_amount),
            }
            data.append(item)
        return response_ok(data)

class PackageViewSet(CustomModelViewSet):
    permission_classes = [isLogin, ]
    queryset = Package.objects.filter()
    serializer_class = PackageSerializer

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

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

    def list(self, request, *args, **kwargs):
        # 底栏合计
        queryset = self.filter_queryset(self.get_queryset())
        total = queryset.aggregate(total_amount=Sum('total_amount'), balance_deduction=Sum('balance_deduction'),
                                   actual_amount=Sum('actual_amount'))
        totalRow = {'totalRow': 1,
                    'total_amount': Formater.formatPriceShow(total['total_amount']),
                    'balance_deduction': Formater.formatPriceShow(total['balance_deduction']),
                    'actual_amount': Formater.formatPriceShow(total['actual_amount'], )}
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = serializer.data
            if len(data) > 0:
                data.append(totalRow)
            return self.get_paginated_response(data)

        serializer = self.get_serializer(queryset, many=True)
        return response_ok(serializer.data)

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

    def create(self, request, *args, **kwargs):
        openid = request.POST.get('openid')
        appid = request.POST.get('appid')
        package = request.POST.get('package') or ''
        try:
            with transaction.atomic():
                serializer = self.get_serializer(data=request.data)
                if serializer.is_valid(raise_exception=True):
                    instance = serializer.save()
                    total_amount = instance.total_amount

                    # 充值套餐
                    if package:
                        package = Package.objects.filter(id=package).first()
                        if package:
                            instance.package = package
                            actual_amount = package.amount
                        else:
                            raise CustomError('套餐错误，请刷新重试！')
                    else:
                        # 余额抵扣
                        balance = Balance.objects.filter(create_user=request.user).first()
                        if balance and balance.balance > 0:
                            if balance.balance >= total_amount:
                                instance.balance_deduction = total_amount
                                actual_amount = 0
                                instance.status = Order.FINISH

                                desc = '支付抵扣{}元'.format(Formater.formatPriceShow(total_amount))
                                Balance.update_balance(instance.create_user, -instance.balance_deduction, desc)
                            else:
                                raise CustomError('余额不足，请充值!')
                        else:
                            raise CustomError('余额不足，请充值!')
                    data = ''
                    if actual_amount:
                        # 小程序在线支付
                        pay = Pay.wechatAppPay(self.request.user, actual_amount, Pay.CUSTOMER)
                        wechatpay = WechatAppletPay(appid)
                        data = wechatpay.weChatUnifiedOrder(openid, pay.pay_no,
                                                            Formater.formatPriceShow(actual_amount))
                        instance.pay = pay

                    instance.save()
                    BizLog.objects.addnew(self.request.user, BizLog.INSERT,
                                          u'添加订单[%s]，id=%d' % (instance.no, instance.id), request.data)
                    return response_ok(data)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            import traceback
            traceback.print_exc()
            return response_error(str(e))
