"""
Django settings for settings project.

Generated by 'django-admin startproject' using Django 3.0.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

# 加载环境配置
from settings.dev import *


# DEBUG = SWITCH['Debug']
# 访问白名单(默认允许所有)
ALLOWED_HOSTS = ['*']
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True


# 安装APP
COMMON_APPS = [
    # 认证授权框架
    'django.contrib.auth',
    # 内容类型框架
    'django.contrib.contenttypes',
    # 跨域请求头框架
    'corsheaders',
    # DRF
    'rest_framework',
    # 过滤器
    'django_filters'
]

# 中间件
MIDDLEWARE = [
    # 安全处理中间件：设置XSS防御的请求头、HTTP转HTTPS等
    'django.middleware.security.SecurityMiddleware',
    # CSRF防御中间件：提供CSRF攻击防御机制
    'django.middleware.csrf.CsrfViewMiddleware',
    # XFrame防御中间件：提供欺骗点击攻击防御机制
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    # 通用中间件：提供一些URL相关的便利功能，如URL末尾自动添加 ’/’ ，无 ‘www’ 自动重定项到有 ’www’ 的URL
    'django.middleware.common.CommonMiddleware',
    # 认证中间件：提供用户认证服务
    # 'django.contrib.auth.middleware.AuthenticationMiddleware',
    # 跨域请求头中间件
    'corsheaders.middleware.CorsMiddleware',
    # 历史记录中间件
    'simple_history.middleware.HistoryRequestMiddleware',
]

# DRF 配置
REST_FRAMEWORK = {
    # 异常回调类
    'EXCEPTION_HANDLER' : 'libs.exception_handler.exception_handler',
    # 默认认证类
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'libs.authtication.TokenAuthtication'
        ],
    # 默认权限类
    'DEFAULT_PERMISSION_CLASSES': [
        'libs.permission.CustomPermission'
    ],
    # 默认渲染类
    'DEFAULT_RENDERER_CLASSES': [
        'libs.render.CustomRenderer',
    ],
    # 默认过滤类
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend',
        'rest_framework.filters.SearchFilter',
        'rest_framework.filters.OrderingFilter'
    ],
    'DEFAULT_PAGINATION_CLASS': 'libs.pagination.CustomPagination',
    # 'DEFAULT_PAGINATION_CLASS': 'rbac.pagination.MyPagination',
    'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.coreapi.AutoSchema',
    'UNAUTHENTICATED_USER':None,
    # 日期时间格式
    'DATETIME_FORMAT': '%Y-%m-%d %H:%M:%S',
    # 日期格式
    'DATE_FORMAT': '%Y-%m-%d',
}

# if SWITCH['AuthMode']=='sys':
#     if SWITCH['sysAuth']['AdminBackend']:
#         COMMON_APPS = COMMON_APPS + [
#             # 后台管理框架
#             'django.contrib.admin',
#             # 会话框架
#             'django.contrib.sessions',
#             # 消息框架
#             'django.contrib.messages',
#             # 静态资源管理框架
#             'django.contrib.staticfiles'
#         ]
#         MIDDLEWARE = MIDDLEWARE + [
#             # 会话支持中间件
#             'django.contrib.sessions.middleware.SessionMiddleware',
#             # 消息中间件：展示一些后台信息给前端页面
#             'django.contrib.messages.middleware.MessageMiddleware',
#         ]
# else:
COMMON_APPS = COMMON_APPS + [
    # 权限控制模块
    'rbac',
]
# 认证用户模型
AUTH_USER_MODEL = 'rbac.User'
    # if SWITCH['rbacAuth']['UseLDAP']:
# import ldap
# from django_auth_ldap.config import LDAPSearch
# AUTH_LDAP_SERVER_URI = "ldap://10.30.10.127:389"
# AUTH_LDAP_BIND_DN = "cn=admin,dc=wetax,dc=com,dc=cn"
# AUTH_LDAP_BIND_PASSWORD = "4h7h#!psq1Luk^wv"
# AUTH_LDAP_USER_SEARCH = LDAPSearch(
#     'ou=users,dc=wetax,dc=com,dc=cn',
#     ldap.SCOPE_SUBTREE,
#     '(uid=%(user)s)',
# )

# AUTH_LDAP_ALWAYS_UPDATE_USER = True

# AUTH_LDAP_USER_ATTR_MAP = {
#     'username': 'uid', 
#     'password': 'userPassword',
#     'email': 'mail',
#     'id': 'uidNumber',
#     'password': 'userPassword',
#     'name': 'cn',
# }

# AUTHENTICATION_BACKENDS = (
#     'django_auth_ldap.backend.LDAPBackend',
# ) 

if DEBUG:
    COMMON_APPS = COMMON_APPS + [
        # 静态资源管理框架
        'django.contrib.staticfiles'
        ]
    REST_FRAMEWORK['DEFAULT_RENDERER_CLASSES'].append('rest_framework.renderers.BrowsableAPIRenderer')

INSTALLED_APPS = list(set(COMMON_APPS + INSTALLED_APPS))
MIDDLEWARE = list(set(MIDDLEWARE))

# 模板引擎
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
# 路由文件
ROOT_URLCONF = 'settings.urls'
# 请求入口
WSGI_APPLICATION = 'settings.wsgi.application'
# 设置语言
LANGUAGE_CODE = 'zh-hans'
# 设置时区
TIME_ZONE = 'Asia/Shanghai'
# 启用国际化
USE_I18N = True
# 启用本地化
USE_L10N = True
# 启用UTC时间
USE_TZ = False
# 默认支持多数据库配置
DATABASE_ROUTERS = ['libs.database_router.DatabaseAppsRouter']
# 忽略 MySQL唯一字符字段长度大于255的错误
SILENCED_SYSTEM_CHECKS = ['mysql.E001']

# 日志配置
# 日志路径
LOG_PATH = os.path.join(BASE_DIR, 'logs')
if not os.path.exists(LOG_PATH):
    os.mkdir(LOG_PATH)
from datetime import datetime, timedelta
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        # 输出错误日志
        'error': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_PATH, 'error-{}.log.json'.format(datetime.now().strftime('%Y-%m-%d'))),
            'maxBytes': 1024 * 1024 * 50,  # 文件大小
            'backupCount': 10,  # 备份数
            'encoding': 'utf-8',  # 设置默认编码
        },
        # 控制台输出
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
        },
        # 输出info日志
        'info': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_PATH, 'info-{}.log.json'.format(datetime.now().strftime('%Y-%m-%d'))),
            'maxBytes': 1024 * 1024 * 50,
            'backupCount': 10,
            'encoding': 'utf-8',  # 设置默认编码
        },
    },
    # 配置用哪几种 handlers 来处理日志
    'loggers': {
        # log 调用时需要当作参数传入
        'log': {
            'handlers': ['error', 'info', 'console',],
            'level': 'INFO',
            'propagate': True
        },
    }
}