# coding=utf-8

from django.conf import settings

from rest_framework import serializers

from utils.exceptions import CustomError

from apps.base import Formater
from apps.images.models import Images

from .models import Product, ProductImg


class ProductSerializer(serializers.ModelSerializer):
    category_t = serializers.CharField(source='category.name', read_only=True)
    price_f = serializers.SerializerMethodField()
    enabled_t = serializers.SerializerMethodField()
    create_user_t = serializers.CharField(source='create_user.name', read_only=True)
    cover_url = serializers.SerializerMethodField()

    def get_cover_url(self, obj):
        if obj.cover:
            return '{}{}'.format(settings.MEDIA_URL, obj.cover.picture)
        return ''

    def get_enabled_t(self, obj):
        if obj.enabled:
            return u"是"
        return u"否"

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

    class Meta:
        model = Product
        fields = '__all__'

    def validate(self, attrs):
        if 'price' in attrs:
            attrs['price'] = Formater.formatPrice(attrs['price'])
        return attrs

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        cover = self.initial_data.get('image', None)
        if not cover:
            raise CustomError(u'商品封面图是必填项！')
        validated_data['cover'] = Images.objects.employee_addnew(validated_data['create_user'], Images.PRODUCT_COVER, cover)
        instance = super(ProductSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        old_cover = None
        cover = self.initial_data.get('image', None)
        if cover:
            old_cover = instance.cover
            validated_data['cover'] = Images.objects.employee_addnew(self.context['request'].user, Images.PRODUCT_COVER, cover)
        instance = super(ProductSerializer, self).update(instance, validated_data)
        if old_cover:
            old_cover.del_images()
        return instance


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

    def get_img_url(self, obj):
        return '{}{}'.format(settings.MEDIA_URL, obj.img.picture)

    class Meta:
        model = ProductImg
        fields = '__all__'
