# 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()

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

    class Meta:
        model = Option
        fields = '__all__'

    def create(self, validated_data):
        validated_data['tenant'] = self.context['request'].user.employee.tenant
        validated_data['create_user'] = self.context['request'].user
        is_exist = Option.is_exist(validated_data['tenant'],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):
        if instance.tenant != self.context['request'].user.employee.tenant:
            raise CustomError(u'禁止跨租户操作！')
        if instance.delete:
            raise CustomError(u'系统选项[%s]已经被删除，禁止操作' % instance.name)
        is_exist = Option.is_exist(instance.tenant, 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
