# coding:utf-8
import logging
import json
from django.conf import settings
from django.http.response import JsonResponse, HttpResponse
from rest_framework.response import Response
from rest_framework.exceptions import ErrorDetail
from django.utils.deprecation import MiddlewareMixin

logger = logging.getLogger('myapp')  # 获取自定义日志器


class ResponseMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if isinstance(response, JsonResponse):
            return response
        status_code = response.status_code
        rsp_data = response.data
        if status_code == 200:
            if not rsp_data:
                rsp_data = {}
            data = rsp_data
            if 'page_size' not in rsp_data:
                data = {'items': rsp_data}
            response = JsonResponse(status=status_code, data={
                'msg': '成功',
                'code': 0,
                'data': data
            })
        elif 400 <= status_code < 500:
            if status_code in [403, 401]:
                response = JsonResponse(
                    status=200, 
                    data={
                        'msg': "无权限访问",
                        'code': 403,
                        'data': {}
                        }
                    )
            elif status_code == 404:
                response = JsonResponse(
                    status=200, 
                    data={
                    'msg': "数据不存在",
                    'code': 400,
                    'data': {}
                })
            elif isinstance(rsp_data, dict):
                if 'msg' in rsp_data:
                    response = JsonResponse(
                        status=200, 
                        data={
                        'msg': rsp_data['msg'],
                        'code': 400,
                        'data': {}
                    })
            else:
                response = JsonResponse(
                        status=200, 
                        data={
                        'msg': '其它错误',
                        'code': 400,
                        'data': {}
                    })
        return response


