# coding=utf-8

from rest_framework import serializers
from .models import Option, Config, BizLog
from apps.account import tenant_log


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 u'是'
        return u'否'

    class Meta:
        model = Option
        fields = '__all__'

    def create(self, validated_data):
        instance = super(OptionSerializer, self).create(validated_data)
        return instance

    def update(self, instance, validated_data):
        instance = super(OptionSerializer, self).update(instance, validated_data)
        return instance

class ConfigSerializer(serializers.ModelSerializer):

    class Meta:
        model = Config
        fields = '__all__'

    def create(self, validated_data):
        tenant = self.context['request'].user.employee.tenant
        data = self.context['request'].data
        for item in data:
            if not item['value'] or item['value'].strip() == '':
                continue
            config = Config.objects.filter(property=item['key'], tenant=tenant).first()
            if config:
                config.value = item['value']
                config.save()
            else:
                Config.objects.create(property=item['key'], value=item['value'], tenant=tenant)
        tenant_log(self.context['request'].user, BizLog.INSERT, u'修改系统配置', data)
