# 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, Order, OrderDetails
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


class OderSerializer(serializers.ModelSerializer):

    class Meta:
        model = Order
        fields = '__all__'

    def create(self, validated_data):
        validated_data['customer'] = self.context['request'].customer
        instance = super(OderSerializer, self).create(validated_data)
        return instance


class OderSimpleSerializer(serializers.ModelSerializer):
    total_amount = serializers.SerializerMethodField()
    total_point = serializers.SerializerMethodField()
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    details = serializers.SerializerMethodField()

    class Meta:
        model = Order
        fields = ('no', 'total_amount', 'total_point', 'status_text', 'details', 'id', 'name', 'tel', 'user_address', )

    def get_total_amount(self, obj):
        return Formater.formatValueShow(obj.total_amount)

    def get_total_point(self, obj):
        return '%.2f' % obj.total_point

    def get_details(self, obj):
        rows = OrderDetails.objects.filter(order=obj)
        serializer = OderDetailSimpleSerializer(rows, many=True)
        return serializer.data


class OderDetailSimpleSerializer(serializers.ModelSerializer):
    name = serializers.CharField(source='commodity.name', read_only=True)
    show_image = serializers.SerializerMethodField()
    amount = serializers.SerializerMethodField()
    point_amount = serializers.SerializerMethodField()
    type = serializers.CharField(source='commodity.type', read_only=True)
    commodity_id = serializers.CharField(source='commodity.id', read_only=True)

    class Meta:
        model = OrderDetails
        fields = ('name', 'show_image', 'amount', 'point_amount', 'count', 'type', 'commodity_id', )

    def get_show_image(self, obj):
        if obj.commodity and obj.commodity.show_image:
            return obj.commodity.show_image.get_path()
        return ''

    def get_amount(self, obj):
        return Formater.formatValueShow(obj.amount)

    def get_point_amount(self, obj):
        return '%.2f' % obj.point_amount
