from rest_framework import serializers
from .models import OperationHelp,OperationHelpUpfile

class OperationHelpSerializer(serializers.ModelSerializer):
    enable_text = serializers.SerializerMethodField()
    create_user_name = serializers.CharField(source='create_user.employee.name', read_only=True)
    tenant_name = serializers.CharField(source='tenant.company_name', read_only=True)

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

    class Meta:
        model = OperationHelp
        fields = '__all__'

    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['create_user'] = user
        validated_data['tenant'] = self.context['request'].user.employee.tenant
        content = self.initial_data['content']
        instance = super(OperationHelpSerializer, self).create(validated_data)
        operation_files = OperationHelpUpfile.objects.filter(tenant=instance.tenant,operation_help__isnull=True)
        for operation_file in operation_files:
            if operation_file.file_path in content:
                operation_file.operation_help = instance
                operation_file.save()
            else:
                operation_file.del_file()
        return instance

    def update(self, instance, validated_data):
        content = self.initial_data['content']
        operation_files = OperationHelpUpfile.objects.filter(operation_help=instance)
        for operation_file in operation_files:
            if not operation_file.file_path in content:
                operation_file.del_file()

        OperationHelpUpfile.objects.filter(tenant=instance.tenant, operation_help__isnull=True,).update(operation_help=instance)
        instance = super(OperationHelpSerializer, self).update(instance, validated_data)
        return instance
