# coding=utf-8

import json

from django.db import transaction
from django.db.models import Q, Sum
from django.conf import settings
from rest_framework.decorators import action
from rest_framework.views import APIView
from utils.custom_modelviewset import CustomModelViewSet
from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsCustomer, AnyOne

from apps.config.models import Config
from apps.commodity.models import Commodity
from apps.customer.commodity.serializers import CommoditySerializer
from apps.customer.models import SuperiorDistributor
from apps.customer.filters import SuperiorDistributorFilter
from apps.customer.distributor.serializers import DistributorSerializer
from apps.rebate.models import CashRebate, PointRebate
from apps.base import Formater

from rest_framework import generics


class DataTypeView(APIView):
    permission_classes = [AnyOne, ]

    def get(self, request):
        '''
        分销商页面用来判断进入那个页面  如果用户登陆且是分销商 要请求下级分销商数据
        如果用户没有登陆或者用户不是分销商 要请求成为分销商要购买的商品信息
        :param request:
        :return:
        '''
        type = 'no'
        if request.customer and request.customer.is_distributor:
            type = 'yes'
        return response_ok(type)


class DistributorView(generics.ListAPIView):
    permission_classes = [IsCustomer, ]
    queryset = SuperiorDistributor.objects.filter()
    serializer_class = DistributorSerializer

    def filter_queryset(self, queryset):
        customer = self.request.customer
        queryset = queryset.filter(
            Q(one_level=customer) | Q(two_level=customer) | Q(three_level=customer) | Q(four_level=customer) | Q(five_level=customer)
        )
        f = SuperiorDistributorFilter(self.request.GET, queryset=queryset)
        return f.qs

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        sum_rows = queryset.aggregate(sum_count=Sum('customer__success_count'), sum_amount=Sum('customer__total_amount'))
        sum_cash = CashRebate.objects.filter(customer=request.customer).aggregate(sum_amount=Sum('amount'))['sum_amount'] or 0
        sum_point = PointRebate.objects.filter(customer=request.customer).aggregate(sum_amount=Sum('amount'))['sum_amount'] or 0
        footer = {
            'sum_count': sum_rows['sum_count'] or 0,
            'sum_amount': Formater.formatValueShow(sum_rows['sum_amount']),
            'sum_cash': Formater.formatValueShow(sum_cash),
            'sum_point': sum_point,
        }

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response({'data': serializer.data, 'footer': footer})
        serializer = self.get_serializer(queryset, many=True)
        return response_ok({'data': serializer.data, 'footer': footer})


class DistributorCommodityView(APIView):

    def get(self, request):
        data = []
        commodity_id = Config.get_commodity()
        if commodity_id:
            commodity = Commodity.objects.filter(id=commodity_id, delete=False, status=settings.ONLINE).first()
            serializer = CommoditySerializer(commodity, many=False)
            data.append(serializer.data)
        return response_ok(data)
