# coding=utf-8

from django.contrib.auth import get_user_model

from rest_framework import serializers

from utils.exceptions import CustomError

from apps.log.models import BizLog
from apps.vehicle.models import Vehicle
from apps.xgjsms.models import XGJVCode

User = get_user_model()


class VehicleSerializer(serializers.ModelSerializer):

    class Meta:
        model = Vehicle
        fields = '__all__'

    def validate(self, attrs):
        attrs['user'] = self.context['request'].user
        if 'tel' in attrs:
            if attrs['user'].tel != attrs['tel']:
                vcode = self.context['request'].data.get('vcode')
                if not vcode:
                    raise CustomError(u'验证码不能为空！')
                XGJVCode.verify(attrs['tel'], vcode)
        return attrs

    def create(self, validated_data):
        vehicle = Vehicle.objects.filter(user=validated_data['user']).count()
        if vehicle:
            raise CustomError(u'您已有绑定设备！')
        instance = super(VehicleSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        if instance.user != validated_data['user']:
            raise CustomError(u'禁止操作他人设备！')
        instance = super(VehicleSerializer, self).update(instance, validated_data)
        return instance

