# 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
from utils.booleancharfield import BooleanCharField

class OrderSerializer(serializers.ModelSerializer):
    coupon_name = serializers.CharField(source='coupon.name', read_only=True)
    commodity_name = serializers.CharField(source='commodity.name', read_only=True)
    student_text = serializers.CharField(source='student.name', read_only=True)
    create_user_text = serializers.CharField(source='create_user.username', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)

    total_amount = PriceShowCharField(read_only=True)
    actual_amount = PriceShowCharField(read_only=True)
    class_text = serializers.SerializerMethodField()

    def get_class_text(self, obj):
        name = '{}-{}-{}'.format(obj.student.school.name, obj.student.classes.grade.name, obj.student.classes.name, )
        return name

    class Meta:
        model = Order
        fields = '__all__'

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

class CouponSerializer(serializers.ModelSerializer):
    create_user_text = serializers.CharField(source='create_user.username', read_only=True)
    amount = PriceShowCharField()
    enable_text = BooleanCharField(source='enable', read_only=True)
    category_text = serializers.SerializerMethodField()
    school_text = serializers.SerializerMethodField()
    category_ids = serializers.SerializerMethodField()

    def get_category_ids(self, obj):
        return obj.category.split(',')

    def get_school_text(self, obj):
        name = ''
        if obj.school:
            rows = School.objects.filter(id__in=obj.school.split(','))
            for row in rows:
                name += row.name + '，'
        return name

    def get_category_text(self, obj):
        name = ''
        if obj.category:
            rows = CommodityLevel.objects.filter(id__in=obj.category.split(','))
            for row in rows:
                name1 = row.name
                if row.category:
                    name1 = '{}-{}'.format(row.category.name, name1)
                    if row.category.category:
                        name1 = '{}-{}'.format(row.category.category.name, name1)
                name += name1 + '，'
        return name

    class Meta:
        model = Coupon
        fields = '__all__'

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

    def update(self, instance, validated_data):
        validated_data['amount'] = Formater.formatPrice(validated_data['amount'])
        instance = super(CouponSerializer, self).update(instance, validated_data)
        return instance

class ShoppingCartSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='commodity.name', read_only=True)
    stock = serializers.CharField(source='commodity.stock', read_only=True)
    price = serializers.SerializerMethodField()
    images = serializers.SerializerMethodField()

    def get_price(self, obj):
        return Formater.formatPriceShow(obj.commodity.price * obj.commodity.discount / 100)

    def get_images(self, obj):
        if obj.commodity.main_image:
            img = Upload.objects.filter(id=obj.commodity.main_image.id).first()
            if img:
                return img.get_path()
        return ''

    class Meta:
        model = ShoppingCart
        fields = (
            'id', 'name', 'price', 'stock', 'images', 'quantity', 'commodity'
        )

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        validated_data['quantity'] = validated_data.get('quantity')
        instance = ShoppingCart.objects.filter(commodity=self.initial_data['commodity'],
                                               create_user=validated_data['create_user']).first()
        if instance:
            instance.quantity += validated_data['quantity']
            instance.save()
        else:
            instance = super(ShoppingCartSerializer, self).create(validated_data)
        return instance
