# coding=utf-8

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

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.order.models import Order
from apps.order.filters import OrderFilter
from apps.rebate.models import PointRebate, CashRebate, TransferCashRebate, TransferCashRebateDetail
from apps.rebate.filters import TransferCashRebateFilter, TransferCashRebateDetailFilter
from apps.rebate.serializers import OrderRebateSerializer, CashRebateSerializer, PointRebateSerializer, TransferCashRebateSerializer, TransferCashRebateDetailSerializer
from apps.rebate.bussiness import CustomerRebateTransfer, transfer_detail_refresh, transfer_refresh


class OrderRebateViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = Order.objects.filter(status__in=[Order.WAIT_DISPATCH, Order.CONFIRM_DISPATCH])
    serializer_class = OrderRebateSerializer

    def filter_queryset(self, queryset):
        order_list = []
        p_order = PointRebate.objects.filter().values_list('order_id', flat=True)
        for item in p_order:
            order_list.append(item)
        c_order = CashRebate.objects.filter().values_list('order_id', flat=True)
        for item in c_order:
            order_list.append(item)
        order_list = list(set(order_list))

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

    @action(methods=['get'], detail=True)
    def cash_rebate(self, request, pk):
        '''
        现金返利明细
        :return:
        '''
        instance = self.get_object()
        rows = CashRebate.objects.filter(order=instance)
        serializer = CashRebateSerializer(rows, many=True)
        return response_ok(serializer.data)

    @action(methods=['get'], detail=True)
    def point_rebate(self, request, pk):
        '''积分返利明细'''
        instance = self.get_object()
        rows = PointRebate.objects.filter(order=instance)
        serializer = PointRebateSerializer(rows, many=True)
        return response_ok(serializer.data)

    @action(methods=['post'], detail=True)
    def transfer_rebate(self, request, pk):
        '''现金返利转账申请'''
        instance = self.get_object()
        crt = CustomerRebateTransfer(instance)
        with transaction.atomic():
            crt.transfer_rebate()
            BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'申请订单[{}]现金返利转账'.format(instance.no), )
        return response_ok()


class TransferCashRebateViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = TransferCashRebate.objects.filter()
    serializer_class = TransferCashRebateSerializer

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

    def list(self, request, *args, **kwargs):
        '''查看订单转账记录  同时刷新该转账的状态  刷新这个订单的批次单在处理中的记录 刷新他们的状态 一般一个订单只有一个批次单在处理中'''
        queryset = self.filter_queryset(self.get_queryset())
        refresh = queryset.filter(~Q(transfer_status__in=[TransferCashRebate.DEFAULT, TransferCashRebate.FINISHED, TransferCashRebate.CLOSED]))
        for item in refresh:
            with transaction.atomic():
                transfer_refresh(item)

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

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

    @action(methods=['post'], detail=True)
    def apply_again(self, request, pk):
        instance = self.get_object()
        if instance.transfer_status != TransferCashRebate.DEFAULT:
            return
        # 再次申请转账 但是不需要创建转账表
        return response_ok()


class TransferCashRebateDetailViewSet(CustomModelViewSet):
    permission_classes = [IsEmployee, ]
    queryset = TransferCashRebateDetail.objects.filter()
    serializer_class = TransferCashRebateDetailSerializer

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

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())

        refresh = queryset.filter(status=TransferCashRebateDetail.PENDING)

        for item in refresh:
            # 微信支付明细单号查询明细单
            with transaction.atomic():
                transfer_detail_refresh(item)

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

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

    @action(methods=['post'], detail=True)
    def apply_again(self, request, pk):
        instance = self.get_object()
        if instance.status != TransferCashRebateDetail.FAIL:
            raise CustomError(u'该转账明细未失败，禁止再次申请转账！')
        # 失败的明细重新申请转账  创建新的转账批次和转账批次明细
        order = instance.main.order
        crt = CustomerRebateTransfer(order)
        with transaction.atomic():
            crt.transfer_rebate(detail=instance)
            BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'转账明细[{}]转账失败，重新申请转账！'.format(instance.no), )
        return response_ok()
