# coding=utf-8

import json
from rest_framework import serializers
from apps.tenant.employee.models import Employee

from utils.exceptions import CustomError
from apps.account.models import User


class EmployeeSerializer(serializers.ModelSerializer):
    gender_text = serializers.CharField(source='get_gender_display', read_only=True)
    status_text = serializers.CharField(source='get_status_display', read_only=True)
    type_text = serializers.CharField(source='get_type_display', read_only=True)
    create_time = serializers.DateTimeField(source='user.date_joined', read_only=True)
    tenant = serializers.DateTimeField(source='tenant.company_name', read_only=True)
    username = serializers.CharField(source='user.username', read_only=True)

    class Meta:
        model = Employee
        fields = '__all__'

    def create(self, validated_data):
        if Employee.checkSuper(self.context['request'].user.employee.tenant):
            raise CustomError(u'已存在一个平台管理员，禁止操作！')
        username = self.initial_data['tel']
        # 判断用户是否已经注册登陆过
        password = None
        if self.initial_data['password']:
            password = self.initial_data['password']
        user = User.objects.filter(username=username).first()
        if not user:
            # 创建user实例
            user = User.objects.create_tenant_user(validated_data['type'], username, password)

        validated_data['user'] = user
        validated_data['tenant'] = self.context['request'].user.employee.tenant

        try:
            instance = super(EmployeeSerializer, self).create(validated_data)
            return instance
        except Exception as e:
            if e.args[0] == 1062:
                raise CustomError(u'该手机号已被游客或者其他员工使用，请检查！')

    def update(self, instance, validated_data):
        if instance.tenant != self.context['request'].user.employee.tenant:
            raise CustomError(u'禁止跨租户操作！')
        if Employee.checkSuper(instance.tenant, instance.id):
            raise CustomError(u'已存在一个平台管理员，禁止操作！')
        username = self.initial_data['tel']
        if username and self.initial_data['password'].strip() != '':
            if instance.user:
                user = {
                    'username': username,
                    'password': self.initial_data['password'],
                    'is_active': 1 if self.initial_data['status'] == '1' else 0,
                    'type': self.initial_data['type'],
                }
                instance.user.update_item(user)
            else:
                is_active = 1 if self.initial_data['status'] == '1' else 0
                user = User.objects.create_tenant_user(validated_data['type'],
                                                       username,
                                                       self.initial_data['password'],
                                                       is_active=is_active)
                validated_data['user'] = user
        instance = super(EmployeeSerializer, self).update(instance, validated_data)
        return instance
