# coding=utf-8

from django.db import transaction
from rest_framework.views import APIView
from rest_framework.decorators import action
from rest_framework import generics
from utils import response_ok,response_error
from apps.account import tenant_log
from apps.foundation.models import BizLog
from rest_framework.exceptions import NotFound
from rest_framework.viewsets import ModelViewSet
from utils.permission import IsCustomerUser
from utils.custom_modelviewset import CustomModelViewSet

from .serializers import *
from apps.customer.filters import *
from apps.vehicle_order.filters import *
from apps.product_order.filters import *
from apps.maint_order.filters import *
from apps.pay.models import PayProduct
from .xgj import XGJ


class VehicleDriveReserveViewSet(generics.ListCreateAPIView):
    permission_classes = [IsCustomerUser, ]
    queryset = VehicleDriveReserve.objects.filter(delete=False)
    serializer_class = VehicleDriveReserveSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(VehicleDriveReserveViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data
            # 同步销管佳
            abutment_xgj = Config.getConfigValue(Config.KEY_ABUTMENT_XGJ) or ''
            if abutment_xgj and abutment_xgj == 'true':
                try:
                    XGJ.drive_reserve(instance)
                except Exception as e:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'试驾预约同步销管佳失败[%s]，id=%d' % (str(e), instance.id))
            tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加预约试驾，id=%d' % instance.id, validated_data)

        return response_ok()


class VehicleInquiryViewSet(generics.ListCreateAPIView):
    permission_classes = [IsCustomerUser, ]
    queryset = VehicleInquiry.objects.filter(delete=False)
    serializer_class = VehicleInquirySerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(VehicleInquiryViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data

            #同步销管佳
            abutment_xgj = Config.getConfigValue(Config.KEY_ABUTMENT_XGJ) or ''
            if abutment_xgj and abutment_xgj == 'true':
                try:
                    XGJ.vehicle_inquiry(instance)
                except Exception as e:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'新车询价同步销管佳失败[%s]，id=%d' % (str(e), instance.id))

            tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加新车询价，id=%d' % instance.id, validated_data)

        return response_ok()

class UsedVehicleInquiryViewSet(generics.ListCreateAPIView):
    permission_classes = [IsCustomerUser, ]
    queryset = UsedVehicleInquiry.objects.filter(delete=False)
    serializer_class = UsedVehicleInquirySerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(UsedVehicleInquiryViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data
            tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加二手车询价，id=%d' % instance.id, validated_data)

        return response_ok()

class UsedVehicleEstimateViewSet(generics.ListCreateAPIView):
    permission_classes = [IsCustomerUser, ]
    queryset = UsedVehicleEstimate.objects.filter(delete=False)
    serializer_class = UsedVehicleEstimateSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(UsedVehicleEstimateViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data

            # 同步销管佳
            abutment_xgj = Config.getConfigValue(Config.KEY_ABUTMENT_XGJ) or ''
            if abutment_xgj and abutment_xgj == 'true':
                try:
                    XGJ.vehicle_estimate(instance)
                except Exception as e:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'置换咨询同步销管佳失败[%s]，id=%d' % (str(e), instance.id))
            tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加二手车预估，id=%d' % instance.id, validated_data)

        return response_ok()


class InsurConsultationViewSet(generics.ListCreateAPIView):
    permission_classes = [IsCustomerUser, ]
    queryset = InsurConsultation.objects.filter(delete=False)
    serializer_class = InsurConsultationSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(InsurConsultationViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data

            # 同步销管佳
            abutment_xgj = Config.getConfigValue(Config.KEY_ABUTMENT_XGJ) or ''
            if abutment_xgj and abutment_xgj == 'true':
                try:
                    XGJ.insur_consultation(instance)
                except Exception as e:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'续保咨询同步销管佳失败[%s]，id=%d' % (str(e), instance.id))
            tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加续保咨询，id=%d' % instance.id, validated_data)

        return response_ok()


class MaintOrderReserveViewSet(generics.ListCreateAPIView):
    permission_classes = [IsCustomerUser, ]
    queryset = MaintOrderReserve.objects.filter(delete=False)
    serializer_class = MaintOrderReserveSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(MaintOrderReserveViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data
            abutment_xgj = Config.getConfigValue(Config.KEY_ABUTMENT_XGJ) or ''
            if abutment_xgj and abutment_xgj == 'true':
                try:
                    XGJ.maint_reserve(instance)
                except Exception as e:
                    tenant_log(instance.customer.user, BizLog.INSERT, u'置换咨询同步销管佳失败[%s]，id=%d' % (str(e), instance.id))
            tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加售后预约单，id=%d' % instance.id, validated_data)

        return response_ok()

class ProductOrderViewSet(generics.ListAPIView):
    permission_classes = [IsCustomerUser, ]
    queryset = ProductOrder.objects.filter(delete=False)
    serializer_class = ProductOrderSerializer

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


class ProductOrderSaveViewSet(generics.CreateAPIView):
    permission_classes = [IsCustomerUser, ]
    serializer_class = ProductOrderSerializer

    def create(self, request, *args, **kwargs):
        with transaction.atomic():
            wechat_customer = CustomerWechat.objects.filter(customer=request.customer).first()
            if not wechat_customer or not wechat_customer.openid:
                raise CustomError(u'获取到用户！')
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data
            if instance.amount == 0:
                instance.status = ProductOrder.PAID
                instance.save()
                tenant_log(instance.customer.user, BizLog.INSERT, u'添加商品订单，no=%s' % instance.no, validated_data)
            else:
                pay_package, query_string = PayProduct.addnew(instance, wechat_customer.openid)
                tenant_log(instance.customer.user, BizLog.INSERT, u'添加商品订单，no=%s' % instance.no, validated_data)
                if query_string:
                    return response_ok(query_string)
        return response_ok()


class GetMaintOrder(APIView):
    permission_classes = [IsCustomerUser, ]

    def get(self, request):
        id = request.GET.get('id')
        abutment_xgj = Config.getConfigValue(Config.KEY_ABUTMENT_XGJ) or ''
        if abutment_xgj and abutment_xgj == 'true':
            try:
                res = XGJ.get_order(id)
            except Exception as e:
                return response_error(str(e))
            return response_ok(res)
        return response_ok({'data': []})

class CustomerVehicleViewSet(CustomModelViewSet):
    permission_classes = [IsCustomerUser, ]
    queryset = CustomerVehicle.objects.filter()
    serializer_class = CustomerVehicleSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(CustomerVehicleViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def perform_create(self, serializer):
        super(CustomerVehicleViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加车辆，id=%d' % instance.id, validated_data)

    @action(methods=['post'], detail=True)
    def vehicle_update(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data
            tenant_log(instance.customer.user, BizLog.UPDATE, u'客户修改车辆信息，id=%d' % instance.id, validated_data)
        return response_ok()

    @action(methods=['get'], detail=True)
    def addr_destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            queryset = self.get_queryset().filter(customer=self.request.customer).exclude(id=instance.id)
            instance.destory(queryset)
            tenant_log(instance.customer.user, BizLog.INSERT, u'客户删除车辆信息，id=%d' % instance.id)
        return response_ok()


class CustomerAddressViewSet(CustomModelViewSet):
    permission_classes = [IsCustomerUser, ]
    queryset = CustomerAddress.objects.filter(delete=False)
    serializer_class = CustomerAddressSerializer

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

    def list(self, request, *args, **kwargs):
        try:
            data = super(CustomerAddressViewSet, self).list(request)
        except NotFound:
            return response_ok([])
        return data

    def perform_create(self, serializer):
        super(CustomerAddressViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        tenant_log(instance.customer.user, BizLog.INSERT, u'客户添加收货地址，id=%d' % instance.id, validated_data)

    @action(methods=['post'], detail=True)
    def addr_update(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            serializer = self.get_serializer(instance, data=request.data)
            serializer.is_valid(raise_exception=True)
            serializer.save()
            instance = serializer.instance
            validated_data = serializer.validated_data

            if instance.default:
                CustomerAddress.objects.filter(Q(customer=request.customer, delete=False), ~Q(id=instance.id)).update(default=False)

            tenant_log(instance.customer.user, BizLog.UPDATE, u'客户修改收货地址，id=%d' % instance.id, validated_data)
        return response_ok()

    @action(methods=['get'], detail=True)
    def addr_destroy(self, request, *args, **kwargs):
        with transaction.atomic():
            instance = self.get_object()
            queryset = self.get_queryset().filter(customer=self.request.customer).exclude(id=instance.id)
            instance.destory(queryset)
            tenant_log(instance.customer.user, BizLog.INSERT, u'客户删除收货地址，id=%d' % instance.id)
        return response_ok()

    @action(methods=['get'], detail=True)
    def set_default(self, request, *args, **kwargs):
        with transaction.atomic():
            status = request.GET.get('status')
            instance = self.get_object()
            if status == 'true':
                self.get_queryset().filter(customer=self.request.customer, default=True).update(default=False)
                instance.default = True
                tenant_log(instance.customer.user, BizLog.UPDATE, u'客户设置默认收货地址，id=%d' % instance.id)
            else:
                instance.default = False
                tenant_log(instance.customer.user, BizLog.UPDATE, u'客户取消默认收货地址，id=%d' % instance.id)
            instance.save()
        return response_ok()


class MaintReserveOptionsView(APIView):
    permission_classes = [IsCustomerUser, ]
    def get(self, request):
        vehicles = CustomerVehicle.objects.filter(customer=request.customer, delete=False).values('id', 'number')
        vehicle_data = []
        for vehicle in vehicles:
            vehicle_data.append({'id': vehicle['id'], 'name': vehicle['number']})
        data = {
            'maint_types': Option.objects.filter(type=Option.MAINT_TYPE, delete=False, enable=True).values('id', 'name'), #品牌
            'vehicles': vehicle_data #车辆
        }
        return response_ok(data)


class UsedVehicleBrandsView(APIView):
    def get(self, request):
        rows = Option.objects.filter(delete=False, enable=True, type=Option.USED_VEHICLE_BRAND)
        data = rows.values('id', 'name')
        return response_ok(data)


class PlanProductOrderView(APIView):
    permission_classes = [IsCustomerUser, ]

    def get(self, request):
        product_id = request.GET.get('id')

        product_order = Product.objects.filter(id=product_id).first()

        address_order = CustomerAddress.objects.filter(customer=request.customer, default=True, delete=False).first()
        if not address_order:
            address_order = CustomerAddress.objects.filter(customer=request.customer, delete=False).first()

        product_item = {}
        if product_order:
            cover = {}
            if product_order.cover_id:
                cover = {'width': product_order.cover.width, 'height': product_order.cover.height, 'url': product_order.cover.get_path()}
            product_item = {
                'id':product_order.id,
                'name': product_order.name,
                'describe': product_order.describe,
                'notes': product_order.notes,
                'cover':cover,
                'price': Formater.formatPriceShow(product_order.price),
            }

        address_item = {}
        if address_order:
            address_item = {
                'id': address_order.id,
                'name': address_order.name,
                'tel': address_order.tel,
                'area': address_order.area,
                'addr': address_order.addr,
                'default': address_order.default,
            }

        data = {
            'product': product_item,
            'address': address_item,
        }
        return response_ok(data)