# coding=utf-8

import requests
from django.db import transaction
from rest_framework.views import APIView
from rest_framework import generics


from utils import response_ok, response_error
from utils.exceptions import CustomError
from utils.permission import IsCustomerUser
from utils.custom_modelviewset import CustomModelViewSet

from apps.xgjsms.models import XGJVCode
from apps.vehicle.models import Vehicle
from apps.vehicle.filters import VehicleFilter
from apps.log.models import BizLog
from .serializers import *


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

    def get(self, request, *args, **kwargs):
        tel = request.GET.get('tel')
        appid = request.GET.get('appid')

        try:
            XGJVCode.send(tel, appid)
        except CustomError as e:
            return response_error(e.get_error_msg())
        return response_ok()


# class VCodeVerifyView(APIView):
#     permission_classes = [IsCustomerUser, ]
#
#     def post(self, request):
#         tel = request.POST.get('tel')
#         vcode = request.POST.get('vcode')
#
#         if not tel:
#             raise CustomError(u'手机号码不能为空！')
#         if not vcode:
#             raise CustomError(u'验证码不能为空！')
#
#         XGJVCode.verify(tel, vcode)
#         return response_ok()


class VehicleViewSet(CustomModelViewSet):
    permission_classes = [IsCustomerUser, ]
    queryset = Vehicle.objects.filter()
    serializer_class = VehicleSerializer

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

    def perform_create(self, serializer):
        super(VehicleViewSet, self).perform_create(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.INSERT, u'绑定设备，id=%d' % instance.id, validated_data)

    def perform_update(self, serializer):
        super(VehicleViewSet, self).perform_update(serializer)
        instance = serializer.instance
        validated_data = serializer.validated_data
        BizLog.objects.addnew(self.request.user, BizLog.UPDATE, u'换绑设备，id=%d' % instance.id, validated_data)
