# coding=utf-8

import datetime
from django.conf import settings
from rest_framework import serializers

from utils.exceptions import CustomError

from apps.order.models import ShoppingCart
from apps.base import Formater


class ShoppingCartSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='commodity_details.name', read_only=True)
    image = serializers.SerializerMethodField()
    price = serializers.SerializerMethodField()
    point_price = serializers.CharField(source='commodity_details.point_price', read_only=True)
    price_type = serializers.CharField(source='commodity_details.type', read_only=True)

    class Meta:
        model = ShoppingCart
        fields = '__all__'

    def get_price(self, obj):
        return Formater.formatValueShow(obj.commodity_details.price)

    def get_image(self, obj):
        if obj.commodity_details and obj.commodity_details.show_image:
            return obj.commodity_details.show_image.get_path()
        return ''

    def validate(self, attrs):
        if 'quantity' in attrs:
            try:
                quantity = int(attrs['quantity'])
            except:
                raise CustomError(u'商品数量错误，请修改！')
            if quantity <= 0:
                raise CustomError(u'商品数量错误，请修改！')
        if 'commodity_details' in attrs:
            if attrs['commodity_details'].delete:
                raise CustomError(u'该商品已删除，禁止购买！')
            if attrs['commodity_details'].status == settings.OFFLINE:
                raise CustomError(u'该商品已下架，禁止购买！')
        return attrs

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