# coding=utf-8

from rest_framework import serializers
from .models import Option

from utils.exceptions import CustomError

class OptionSerializer(serializers.ModelSerializer):
    type_name = serializers.CharField(source='get_type_display', read_only=True)
    enable_text = serializers.SerializerMethodField()
    end_stage_text = serializers.SerializerMethodField()

    def get_enable_text(self,obj):
        if obj.enable:
            return '是'
        return '否'

    def get_end_stage_text(self,obj):
        if obj.end_stage:
            return '是'
        return '否'

    class Meta:
        model = Option
        fields = '__all__'

    def create(self, validated_data):
        validated_data['create_user'] = self.context['request'].user
        is_exist = Option.is_exist(validated_data['type'], validated_data['name'])
        if is_exist:
            raise CustomError(u'自定义项[%s]已存在！' % validated_data['name'])
        instance = super(OptionSerializer,self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        is_exist = Option.is_exist(validated_data['type'], validated_data['name'], instance.id)
        if is_exist:
            raise CustomError(u'自定义项[%s]已存在！' % validated_data['name'])
        instance = super(OptionSerializer, self).update(instance, validated_data)
        return instance

class OptionComboboxSerializer(serializers.ModelSerializer):

    class Meta:
        model = Option
        fields = ('id','name','track_day')
