# coding=utf-8
import datetime
from rest_framework import serializers
from apps.tenant.models import Tenant
from apps.tenant.employee.models import Employee
from utils.exceptions import CustomError
from apps.account.models import User
from apps.upload.models import Upload

class TenantSerializer(serializers.ModelSerializer) :
    create_time = serializers.DateTimeField(format='%Y-%m-%d %H:%M', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    username = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField()

    class Meta:
        model = Tenant
        fields = '__all__'

    def get_image(self, obj):
        img = Upload.objects.filter(tenant=obj, type=Upload.COMPANY_IMAGE).first()
        if img:
            return img.get_path()
        else:
            return ''

    def get_username(self, obj):
        names = Employee.objects.filter(tenant=obj, user__type=User.SUPER).values('user__username')
        name = []
        for i in names:
            name.append(i.get('user__username'))
        return '，'.join(name)

    def create(self, validated_data):
        if Tenant.is_exist(validated_data['company_name']):
            raise CustomError(u'名称为[%s]的租户已存在' % validated_data['company_name'])
        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()
        return instance

    def update(self, instance, validated_data):
        if instance.delete:
            raise CustomError(u'租户[%s]已经被删除，禁止修改' % instance.company_name)
        if Tenant.is_exist(validated_data['company_name'], instance.id):
            raise CustomError(u'名称为[%s]的租户已存在' % validated_data['company_name'])

        instance = super(TenantSerializer, self).update(instance, validated_data)
        return instance



