# coding=utf-8

import json

from django.conf import settings
from rest_framework import serializers
from django.db.models import Q

from apps.commodity.models import Commodity, CommodityImage
from apps.images.models import Images
from apps.base import Formater

from utils.exceptions import CustomError


class CommoditySerializer(serializers.ModelSerializer):
    category_text = serializers.CharField(source='category.name', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    create_user_text = serializers.CharField(source='create_user.employee.name', read_only=True)
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    price = serializers.SerializerMethodField()
    vip_price = serializers.SerializerMethodField()
    point_price = serializers.SerializerMethodField()

    show_image_url = serializers.CharField(source='show_image.picture', read_only=True)
    detail_image = serializers.SerializerMethodField()
    carousel_image = serializers.SerializerMethodField()

    class Meta:
        model = Commodity
        fields = '__all__'

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

    def get_vip_price(self, obj):
        return Formater.formatPriceShow(obj.vip_price)

    def get_point_price(self, obj):
        return Formater.formatPriceShow(obj.point_price)

    def get_detail_image(self, obj):
        count = CommodityImage.objects.filter(commodity=obj, type=CommodityImage.DETAILS).count()
        return count

    def get_carousel_image(self, obj):
        count = CommodityImage.objects.filter(commodity=obj, type=CommodityImage.CAROUSEL).count()
        return count

    def validate(self, attrs):
        if 'category' in attrs and attrs['category']:
            if not attrs['category'].enable:
                raise CustomError(u'该商品类别已被禁用，请刷新后重试！')
            if attrs['category'].delete:
                raise CustomError(u'该商品类别已被删除，请刷新后重试！')
        if 'price' in self.initial_data:
            attrs['price'] = Formater.formatPrice(self.initial_data['price'])
        if 'vip_price' in self.initial_data:
            attrs['vip_price'] = Formater.formatPrice(self.initial_data['vip_price'])
        if 'point_price' in self.initial_data:
            attrs['point_price'] = Formater.formatPrice(self.initial_data['point_price'])

        if attrs['type'] == Commodity.CASH:
            attrs['point_price'] = 0
        elif attrs['type'] == Commodity.POINT:
            attrs['price'] = 0
            attrs['vip_price'] = 0
        return attrs

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

    def update(self, instance, validated_data):
        if instance.delete:
            raise CustomError(u'该商品已删除，禁止操作！')
        instance = super(CommoditySerializer, self).update(instance, validated_data)
        return instance


class CommodityImageSerializer(serializers.ModelSerializer):
    img_url = serializers.SerializerMethodField()

    def get_img_url(self, obj):
        return '%s%s' % (settings.MEDIA_URL, obj.img.picture)

    class Meta:
        model = CommodityImage
        fields = ('img_url', 'id',)
