# coding=utf-8
from apps.exceptions import CustomError
from rest_framework import serializers
from apps.activity.models import Order
from apps.customer.models import Customer
from util.format import Formater


class ActivityOrderSerializer(serializers.ModelSerializer):
    number = serializers.SerializerMethodField()
    create_time = serializers.DateTimeField(format='%m-%d %H:%M', read_only=True)

    class Meta:
        model = Order
        fields = ('number', 'create_time', )

    def get_number(self, obj):
        if obj.number:
            l = len(obj.number)
            if l < 4:
                return ''
            return obj.number[:2] + '***' + obj.number[l - 2:l]
        return ''


class OrderSerializer(serializers.ModelSerializer):
    activity_name = serializers.CharField(source='activity.title', read_only=True)
    show_amount = serializers.SerializerMethodField()

    class Meta:
        model = Order
        fields = '__all__'

    def get_show_amount(self, obj):
        return Formater.formatPriceShow(obj.amount)

    def validate(self, attrs):
        attrs['member'] = self.context['request'].customer
        if 'activity' in attrs and attrs['activity']:
            attrs['activity'].checkStatus()
            required_signs = []
            if attrs['activity'].required_signs:
                required_signs = attrs['activity'].required_signs.split(',')
            for item in required_signs:
                if item == u'姓名':
                    if ('name' not in attrs) or (not attrs['name']):
                        raise CustomError(u'请输入姓名')
                if item == u'车牌号':
                    if ('number' not in attrs) or (not attrs['number']):
                        raise CustomError(u'请输入车牌号')
                if item == u'车型':
                    if ('model' not in attrs) or (not attrs['model']):
                        raise CustomError(u'请输入车型')
        return attrs

    def create(self, validated_data):
        validated_data['branch'] = validated_data['activity'].branch
        validated_data['amount'] = Formater.formatPrice(validated_data['activity'].amount)
        validated_data['rebate'] = Formater.formatPrice(validated_data['activity'].rebate)
        instance = super(OrderSerializer, self).create(validated_data)
        return instance
