# coding=utf-8
from django.conf import settings
from rest_framework import serializers
import datetime
from apps.tenant.models import Tenant
from utils.exceptions import CustomError
from apps.upload.models import Upload

class TenantSerializer(serializers.ModelSerializer):

    class Meta:
        model = Tenant
        fields = '__all__'

    def create(self, validated_data):
        if Tenant.is_exist(validated_data['company_name']):
            raise CustomError(u'名称为[%s]的租户已存在' % validated_data['company_name'])
        user = self.context['request'].user
        image = self.context['request'].data.get('image')
        validated_data['user'] = self.context['request'].user
        instance = super(TenantSerializer, self).create(validated_data)
        instance.company_no = instance.get_no()
        instance.end_date = (datetime.datetime.now() + datetime.timedelta(days=30)).strftime('%Y-%m-%d')
        instance.save()
        Upload.objects._addnew(instance, user, Upload.COMPANY_IMAGE, image)
        return instance
