# coding=utf-8

from utils.custom_modelviewset import CustomModelViewSet
import datetime
from django.utils import timezone
from rest_framework.decorators import action
from utils.permission import IsAdministratorUser
from apps.log.models import BizLog
from django.db import transaction
from utils.exceptions import CustomError
from utils import response_ok, response_error
from apps.tenant.serializers import Invoice,InvoiceSerializer,Pay
from apps.tenant.filters import InvoiceFilter


class InvoiceViewSet(CustomModelViewSet):
    permission_classes = [IsAdministratorUser, ]
    queryset = Invoice.objects.filter()
    serializer_class = InvoiceSerializer

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

    @action(methods=['post'], detail=True)
    def check(self, request, pk):
        # 审核
        status = request.POST.get('status')
        reject_reason = request.POST.get('reason')
        try:
            with transaction.atomic():
                instance = Invoice.objects.filter(id=pk).first()
                if not instance:
                    raise CustomError('当前发票信息有误！')
                # 审核
                if instance.status in [Invoice.NOT_MAIL, Invoice.MAILED,]:
                    raise CustomError('当前发票已审核！')

                instance.status = status
                instance.reject_reason = reject_reason
                instance.save()
                start_date = (datetime.datetime.now() - datetime.timedelta(days=90)).strftime('%Y-%m-%d')
                Pay.objects.filter(tenant=instance.tenant,invoice__isnull=True, create_time__gte=start_date,).update(invoice=instance)
                BizLog.objects.addnew(None, request.user, BizLog.INSERT,
                                      u'审核企业发票[%s]状态为[%s],id=%d' % (instance.invoice_name, status, instance.id))
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('审核完成！')

    @action(methods=['post'], detail=True)
    def check(self, request, pk):
        # 审核
        status = request.POST.get('status')
        reject_reason = request.POST.get('reason')
        try:
            with transaction.atomic():
                instance = Invoice.objects.filter(id=pk).first()
                if not instance:
                    raise CustomError('当前发票信息有误！')
                # 审核
                if instance.status in [Invoice.NOT_MAIL, Invoice.MAILED,]:
                    raise CustomError('当前发票已审核！')

                instance.status = status
                instance.reject_reason = reject_reason
                instance.use_time = timezone.now()
                instance.save()
                Pay.objects.filter(tenant=instance.tenant,invoice__isnull=True).update(invoice=instance)
                BizLog.objects.addnew(None, request.user, BizLog.INSERT,
                                      u'审核企业发票[%s]状态为[%s],id=%d' % (instance.invoice_name, status, instance.id))
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('审核完成！')

    @action(methods=['post'], detail=True)
    def deliver(self, request, pk):
        express_company = request.POST.get('express_company')
        express_number = request.POST.get('express_number')
        try:
            with transaction.atomic():
                instance = Invoice.objects.filter(id=pk).first()
                if not instance:
                    raise CustomError('当前发票信息有误！')
                # 发快递
                if instance.status != Invoice.NOT_MAIL:
                    raise CustomError('当前发票状态不对！')

                instance.status = Invoice.MAILED
                instance.express_company = express_company
                instance.express_number = express_number
                instance.use_time = timezone.now()
                instance.save()
                BizLog.objects.addnew(None, request.user, BizLog.INSERT,
                                      u'企业发票[%s]发货,id=%d' % (instance.invoice_name,  instance.id))
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
        return response_ok('发货完成！')
