from common.utils.views import ManagerApiView
from console.dictionary.models import Dictionary
from console.dictionary.serializers import DictionaryCreateSerializer

from console.dictionary.serializers import DictionaryUpdateSerializer
from rest_framework.response import Response

from common.utils.return_structure import general_message, error_message
from common.utils.service_code import API_ERROR
from console.dictionary.serializers import DictionaryInfoSerializer

from common.utils.pagination import CustomPageNumberPagination
from common.utils.views import BaseApiView
from console.dictionary.filters import DictionaryFilter


class DictionaryCreateView(ManagerApiView):
    queryset = Dictionary.objects.all()
    serializer_class = DictionaryCreateSerializer

    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)


class DictionaryUpdateView(ManagerApiView):
    queryset = Dictionary.objects.all()
    serializer_class = DictionaryUpdateSerializer

    def put(self, request, *args, **kwargs):
        dictionary = Dictionary.objects.filter(id=kwargs.get("id")).first()
        serializer = DictionaryUpdateSerializer(dictionary, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(general_message(msg_show="修改成功"))
        return Response(
            error_message(msg_show="修改失败",
                          msg=serializer.errors,
                          code=API_ERROR))


class DictionaryListView(ManagerApiView):
    queryset = Dictionary.objects.all()
    serializer_class = DictionaryInfoSerializer
    pagination_class = CustomPageNumberPagination
    filter_class = DictionaryFilter

    def get(self, request, *args, **kwargs):
        return self.get_list(request, *args, **kwargs)


class DictionaryInfoView(ManagerApiView):
    queryset = Dictionary.objects.all()
    serializer_class = DictionaryInfoSerializer

    def get(self, request, *args, **kwargs):
        return self.get_info(request, *args, **kwargs)


class DictionarySelectView(BaseApiView):
    queryset = Dictionary.objects.filter()
    serializer_class = DictionaryInfoSerializer

    def get(self, request, *args, **kwargs):
        model = request.GET.get("model")
        name = request.GET.get("name")
        if not model:
            return Response(
                error_message(msg_show="数据请求失败",
                              msg="model is required!",
                              code=API_ERROR))
        if not name:
            return Response(
                error_message(msg_show="数据请求失败",
                              msg="name is required!",
                              code=API_ERROR))
        dictionary = self.get_queryset().filter(name=name, model=model).first()
        serializer = self.get_serializer(dictionary)
        return Response(
            general_message(msg_show="数据获取成功", bean=serializer.data))
