# coding=utf-8
import datetime
from rest_framework import serializers
from .models import *
from django.conf import settings
from utils.booleancharfield import PriceShowCharField
from apps.base import Formater

class PackageSerializer(serializers.ModelSerializer):
    create_user_text = serializers.CharField(source='create_user.username', read_only=True)
    create_time_f = serializers.DateTimeField(source='create_time', format=settings.SHORT_DATETIME_FORMAT,
                                              read_only=True)
    amount = PriceShowCharField(read_only=True)
    give_amount = PriceShowCharField(read_only=True)

    class Meta:
        model = Package
        fields = '__all__'

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        validated_data['amount'] = Formater.formatPrice(self.initial_data['amount'])
        validated_data['give_amount'] = Formater.formatPrice(self.initial_data['give_amount'])
        instance = super(PackageSerializer, self).create(validated_data)
        instance.save()
        return instance

    def update(self, instance, validated_data):
        validated_data['amount'] = Formater.formatPrice(self.initial_data['amount'])
        validated_data['give_amount'] = Formater.formatPrice(self.initial_data['give_amount'])
        instance = super(PackageSerializer, self).update(instance, validated_data)
        instance.save()
        return instance

class OrderSerializer(serializers.ModelSerializer):
    create_user_text = serializers.CharField(source='create_user.username', read_only=True)
    create_time_f = serializers.DateTimeField(source='create_time', format=settings.SHORT_DATETIME_FORMAT,
                                              read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)

    total_amount = PriceShowCharField(read_only=True)
    balance_deduction = PriceShowCharField(read_only=True)
    actual_amount = PriceShowCharField(read_only=True)
    class Meta:
        model = Order
        fields = '__all__'

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        validated_data['total_amount'] = abs(Formater.formatPrice(self.initial_data['total_amount']))
        instance = super(OrderSerializer, self).create(validated_data)
        instance.no = instance.get_no()
        instance.save()
        return instance
