# coding=utf-8

from django.conf import settings
from rest_framework import serializers
from apps.store.models import Shop, StoreBrand
from apps.images.models import Images
from apps.vehicle.models import Brand

from utils.exceptions import CustomError


class ShopSerializer(serializers.ModelSerializer):
    enabled_text = serializers.SerializerMethodField()
    img_url = serializers.SerializerMethodField()
    brands = serializers.SerializerMethodField()
    brand_text = serializers.SerializerMethodField()

    def get_enabled_text(self, obj):
        if obj.enabled:
            return u'是'
        return u'否'

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

    def get_brands(self, obj):
        brand_rows = StoreBrand.objects.filter(store=obj)
        if brand_rows.count() > 0:
            return [brand_row.brand_id for brand_row in brand_rows]
        return []

    def get_brand_text(self, obj):
        brand_rows = StoreBrand.objects.filter(store=obj)
        data = []
        for brand_row in brand_rows:
            data.append(brand_row.brand.name)
        return ','.join(data)

    class Meta:
        model = Shop
        fields = '__all__'

    def create(self, validated_data):
        user = self.context['request'].user
        file = self.context['request'].FILES.get('image', None)
        if file:
            validated_data['img'] = Images.objects.employee_addnew(user, Images.SHOP_FILE, file)

        instance = super(ShopSerializer, self).create(validated_data)

        brands = self.context['request'].data.get('brands')
        if brands:
            brands = brands.split(',')
            for item in brands:
                brand = Brand.objects.filter(id=int(item), enabled=True, delete=False).first()

                if not brand:
                    raise CustomError(u'所选择的品牌不存在或不可用或已被删除')
                StoreBrand.objects.create(store=instance, brand=brand)
        return instance
