#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import logging

from django.contrib.auth.models import AnonymousUser
from django_restql.mixins import DynamicFieldsMixin
from rest_framework import serializers
from rest_framework.fields import empty
from rest_framework.request import Request
from rest_framework.serializers import ModelSerializer

from django_base_ai.system.models import Dept, Users

logger = logging.getLogger(__name__)


class CustomModelSerializer(DynamicFieldsMixin, ModelSerializer):
    """
    增强DRF的ModelSerializer,可自动更新模型的审计字段记录
    (1)self.request能获取到rest_framework.request.Request对象
    """

    # 修改人的审计字段名称, 默认modifier, 继承使用时可自定义覆盖
    modifier_field_id = "modifier"
    modifier_name = serializers.SerializerMethodField(read_only=True)

    def get_modifier_name(self, instance):
        if not hasattr(instance, "modifier"):
            return None
        queryset = Users.objects.filter(id=instance.modifier).values_list("name", flat=True).first()

        if queryset:
            return queryset
        return None

    # 创建人的审计字段名称, 默认creator, 继承使用时可自定义覆盖
    creator_field_id = "creator"
    creator_name = serializers.SerializerMethodField(read_only=True)

    def get_creator_name(self, instance):
        if not hasattr(instance, "creator"):
            return None
        queryset = Users.objects.filter(id=instance.creator).values_list("name", flat=True).first()

        if queryset:
            return queryset
        return None

    avatar_field_id = "avatar"
    creator_avatar = serializers.SerializerMethodField(read_only=True)

    def get_creator_avatar(self, instance):
        if not hasattr(instance, "avatar"):
            return None
        queryset = Users.objects.filter(id=instance.creator).values_list("avatar", flat=True).first()

        if queryset:
            return queryset
        return None

    dept_belong_id = "dept_belong_id"
    dept_info = serializers.SerializerMethodField(read_only=True)

    def get_dept_info(self, instance):
        if not hasattr(instance, "dept_belong_id"):
            return None
        queryset = (
            Dept.objects.filter(id=instance.dept_belong_id).values("id", "name", "short_name", "dept_full_path").first()
        )

        if queryset:
            return queryset
        return None

    # 数据所属部门字段
    dept_belong_id_field_name = "dept_belong_id"
    # 添加默认时间返回格式
    create_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False, read_only=True)
    update_datetime = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S", required=False)

    def __init__(self, instance=None, data=empty, request=None, **kwargs):
        super().__init__(instance, data, **kwargs)
        self.request: Request = request or self.context.get("request", None)

    def save(self, **kwargs):
        return super().save(**kwargs)

    def create(self, validated_data):
        if self.request and self.request.user and not isinstance(self.request.user, AnonymousUser):
            if self.modifier_field_id in self.fields.fields:
                validated_data[self.modifier_field_id] = self.get_request_user_id()
            if self.creator_field_id in self.fields.fields:
                validated_data[self.creator_field_id] = self.get_request_user_id()

            if (
                self.dept_belong_id_field_name in self.fields.fields
                and validated_data.get(self.dept_belong_id_field_name, None) is None
            ):
                validated_data[self.dept_belong_id_field_name] = getattr(self.request.user, "dept_id", None)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        if self.request and self.request.user and not isinstance(self.request.user, AnonymousUser):
            if self.modifier_field_id in self.fields.fields:
                validated_data[self.modifier_field_id] = self.get_request_user_id()
            if hasattr(self.instance, self.modifier_field_id):
                setattr(self.instance, self.modifier_field_id, self.get_request_user_id())
        return super().update(instance, validated_data)

    def get_request_username(self):
        if getattr(self.request, "user", None):
            user = self.request.user
            # 如果用户是 AnonymousUser，返回 None 而不是 "AnonymousUser"
            if isinstance(user, AnonymousUser):
                return None
            return getattr(user, "username", None)
        return None

    def get_request_name(self):
        if getattr(self.request, "user", None):
            return getattr(self.request.user, "name", None)
        return None

    def get_request_user_id(self):
        if getattr(self.request, "user", None):
            return getattr(self.request.user, "id", None)
        return None

    @property
    def errors(self):
        # get errors
        errors = super().errors
        verbose_errors = {}

        # fields = { field.name: field.verbose_name } for each field in model
        fields = {
            field.name: field.verbose_name
            for field in self.Meta.model._meta.get_fields()
            if hasattr(field, "verbose_name")
        }

        # iterate over errors and replace error key with verbose name if exists
        for field_name, error in errors.items():
            if field_name in fields:
                verbose_errors[str(fields[field_name])] = error
            else:
                verbose_errors[field_name] = error
        return verbose_errors
