from django.shortcuts import render
from apps.utils.viewsets import CustomGenericViewSet, CustomModelViewSet
from apps.sam.models import Customer, Contract, Order, OrderItem, ContractRecord
from apps.sam.serializers import CustomerSerializer, ContractSerializer, OrderSerializer, OrderItemSerializer, ContractRecordSerializer
from rest_framework.exceptions import ParseError
from rest_framework.mixins import ListModelMixin, CreateModelMixin, DestroyModelMixin
from apps.utils.mixins import BulkCreateModelMixin
from rest_framework.decorators import action
from django.db import transaction
from rest_framework import serializers
from rest_framework.exceptions import PermissionDenied
from django.utils import timezone
from rest_framework.response import Response
from .filters import OrderItemFilter


# Create your views here.
class CustomerViewSet(CustomModelViewSet):
    """
    list: 客户信息

    客户信息
    """
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer
    search_fields = ['name', 'contact']

    def perform_destroy(self, instance):
        if Contract.objects.filter(customer=instance).exists():
            raise ParseError('该客户存在合同不可删除')
        instance.delete()


class ContractViewSet(CustomModelViewSet):
    """
    list: 合同信息

    合同信息
    """
    queryset = Contract.objects.all()
    serializer_class = ContractSerializer
    select_related_fields = ['customer', 'create_by']
    search_fields = ['name', 'number']
    filterset_fields = ['customer']

    def perform_destroy(self, instance):
        if Order.objects.filter(contract=instance).exists():
            raise ParseError('该合同存在订单不可删除')
        instance.delete()


class OrderViewSet(CustomModelViewSet):
    """
    list: 订单信息

    订单信息
    """
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    select_related_fields = ['contract', 'customer']
    search_fields = ['number', 'contract__name', 'contract__number', 'customer__name', 'item_order__material__name',
                             'item_order__material__specification', 'item_order__material__model']
    filterset_fields = {
        "contract": ["exact"],
        "customer": ["exact"],
        "state": ["exact", "in"],
    }

    def perform_destroy(self, instance):
        if instance.state != Order.ORDER_CREATE:
            raise ParseError('订单非创建中不可删除')
        instance.delete()

    @action(methods=['post'], detail=True, perms_map={'post': 'order.update'}, serializer_class=serializers.Serializer)
    @transaction.atomic
    def submit(self, request, *args, **kwargs):
        """提交订单

        提交订单
        """
        order = self.get_object()
        user = request.user
        if order.create_by != user:
            raise PermissionDenied('非创建人不可提交')
        if order.state != Order.ORDER_CREATE:
            raise ParseError('订单非创建中')
        order.submit_time = timezone.now()
        order.state = Order.ORDER_SUBMITED
        order.save()
        return Response()


class OrderItemViewSet(ListModelMixin, CreateModelMixin, DestroyModelMixin, CustomGenericViewSet):
    """
    list: 订单明细

    订单明细
    """
    perms_map = {'get': '*', 'post': 'order.update', 'delete': 'order.update'}
    queryset = OrderItem.objects.all()
    serializer_class = OrderItemSerializer
    select_related_fields = ['order', 'material']
    filterset_class = OrderItemFilter
    ordering = ['create_time']

    def perform_destroy(self, instance):
        if instance.order.state != Order.ORDER_CREATE:
            raise ParseError('该订单状态下不可删除')
        return super().perform_destroy(instance)


class ContractRecordViewSet(CustomModelViewSet):
    """
    list: 销售合同到款流水

    销售合同到款流水
    """
    perms_map = {
        'get': '*',
        'post': 'contract.update',
        'put': 'contract.update',
        'patch': 'contract.update',
        'delete': 'contract.update',
    }
    queryset = ContractRecord.objects.all()
    serializer_class = ContractRecordSerializer
    search_fields = ['contract__number', 'contract__name', 'voucher_no', 'remark']
    select_related_fields = ['contract', 'contract__customer', 'create_by', 'update_by']
    filterset_fields = {
        'contract': ['exact'],
        'stage_type': ['exact', 'in'],
        'pay_method': ['exact', 'in'],
    }

    def perform_destroy(self, instance):
        if instance.contract.status == Contract.STATUS_TERMINATED:
            raise ParseError('合同已终止，不可删除到款流水')
        instance.delete()
