# -*- coding: utf-8 -*-
"""
Django settings for frame_server project.

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

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

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

import os
import configparser
config = configparser.ConfigParser()

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
RESOURCE_ROOT = os.path.join(BASE_DIR, 'data')

ENVIRONMENT = os.environ.get('SERVER_CFG', 'dev')

config.read(os.path.join(BASE_DIR, 'config_%s' % ENVIRONMENT))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '$br+r_=i40pe_2x*)2jb(tsy9kt=lagzvse#7oat$osf4@c^&-'

# SECURITY WARNING: don't run with debug turned on in production!
if ENVIRONMENT == 'dev':
    DEBUG = True
else:
    DEBUG = False

ALLOWED_HOSTS = ["*"]

AUTH_USER_MODEL = 'app.Members'
# Application definition

INSTALLED_APPS = [
    'simpleui',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # 第三方依赖库
    'rest_framework',
    'rest_framework.authtoken',
    'django_filters',
    'corsheaders',
    'django_cas_ng',
    'django_celery_beat',
    'django_celery_results',
    'drf_yasg',
    'app',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'utils.comm.middleware.GlobalRequestMiddleware.GlobalRequestMiddleware'
]

ROOT_URLCONF = 'frame_server.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'frame_server.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DB_ENGINE = config['db']['engine']
DB_NAME = config['db']['name']
DB_HOST = config['db']['host']
DB_PORT = config['db']['port']
DB_USER = config['db']['user']
DB_PASSWORD = config['db']['password']

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.{}'.format(DB_ENGINE),
#         'NAME': DB_NAME,
#         'HOST': DB_HOST,
#         'PORT': DB_PORT,
#         'USER': DB_USER,
#         'PASSWORD': DB_PASSWORD
#     }
# }

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'zh-Hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = False


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, "data", "static")
if not os.path.exists(STATIC_ROOT):
    os.makedirs(STATIC_ROOT)


# 配置跨域
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ORIGIN_WHITELIST = ()

CORS_ALLOW_METHODS = (
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
    'VIEW',
)

CORS_ALLOW_HEADERS = (
    'XMLHttpRequest',
    'X_FILENAME',
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
    'Pragma',
)

# Logging setting
LOG_LEVEL = config['base']['log_level']
if LOG_LEVEL not in ['DEBUG', 'INFO']:
    LOG_LEVEL = 'DEBUG'

loggers_app = [
    "utils.frame",
]
from .log import CustomLogConfig
LOGGING = CustomLogConfig().set_logging(LOG_LEVEL, loggers_app)


# 配置异步
from kombu import Queue
REDIS_HOST = config['redis']['rd_host']
REDIS_PASSWORD = config['redis']['rd_password']
REDIS_PORT = config['redis']['rd_port']
REDIS_BASE_DB = config['redis']['base_db']

# Redis 连接池 DB
REDIS_CONSTANCE_DB = config['redis']['constance_db']

# backer 存储生产者消息 DB
REDIS_BROKER_DB = config['redis']['broker_db']

# celery 缓存 DB
REDIS_CELERY_CACHE_DB = config['redis']['celery_cache_db']
# celery 结果存储 DB
REDIS_CELERY_RESULT_DB = config['redis']['celery_result_db']

# redis 连接池
CONSTANCE_REDIS_CONNECTION = f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_CONSTANCE_DB}"

# backer 存储生产者消息
BROKER_URL = f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_BROKER_DB}"

# celery 定时任务中间件
CELERYBEAT_SCHEDULER = "django_celery_beat.schedulers.DatabaseScheduler"

# celery 处理结果保存
CELERY_RESULT_BACKEND = f'redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_CELERY_RESULT_DB}'

# celery 缓存
CELERY_CACHE_BACKEND = f'redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_CELERY_CACHE_DB}'


# 队列配置
CELERY_QUEUES = (
    # celery 默认队列
    Queue('celery', routing_key='celery'),
    # demo
    Queue('notify', routing_key='notify'),
)
# 路由
CELERY_ROUTES = {
    '*.notify_queue*': {'queue': 'notify'},
}

CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
# celery时区设置，使用settings中TIME_ZONE同样的时区
CELERY_TIMEZONE = TIME_ZONE
# celery 禁用 UTC 和 TZ
CELERY_ENABLE_UTC = False
DJANGO_CELERY_BEAT_TZ_AWARE = False


# 后端认证
AUTHENTICATION_BACKENDS = [
    'django_cas_ng.backends.CASBackend',
    'django.contrib.auth.backends.ModelBackend',
]

# rest framework 配置
REST_FRAMEWORK = {
    # 配置分页，使用按偏移量分页
    'DEFAULT_PAGINATION_CLASS': 'utils.frame.pagination.CustomBasePagination',
    'PAGE_SIZE': 10,
    'EXCEPTION_HANDLER': 'utils.frame.exception_handler.CustomBaseExceptionHandler',

    # API接口权限验证，配置只有注册用户才可通过验证, AllowAny不做权限限制.
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),

    # 配置单点系统
    'DEFAULT_MIDDLEWARE_CLASSES': (
        'django_cas_ng.middleware.CASMiddleware',
    ),

    # 配置认证
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.TokenAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        # 'django_cas_ng.backends.CASBackend',
        'django.contrib.auth.backends.ModelBackend',
    ),
}


# CAS 的地址
# CAS_SERVER_URL = 'http://cas-g2.xxxxx.com.cn'    # 新域名
CAS_SERVER_URL = config['cas']['cas_server_url']   # 老域名

# CAS 版本
CAS_VERSION = '3'


# 存入所有 CAS 服务端返回的 User 数据。
CAS_APPLY_ATTRIBUTES_TO_USER = True
# 自定义返回值匹配用户表
# {'ln':'last_name'}，cas服务器返回的ln属性将重命名为last_name
CAS_RENAME_ATTRIBUTES = {
    'name': 'name',
    'unitname': 'unit_name',
    'deptname': 'dept_name',
    'employeeCode': 'employee_code',
    'employeeName': 'employee_name',
    'oaid': 'oaid',
    'postname': 'post_name',
    'telephone': 'telephone'
}

# CAS 自定义额外参数，用于在请求服务端返回指定json格式
CAS_EXTRA_LOGIN_PARAMS = {'format': 'json'}
CAS_RENEW = True

# CAS 自动创建用户
CAS_AUTO_CREATE_USERS = True


# Django 默认的数据存储根目录， model的 upload_to 字段用到
MEDIA_ROOT = RESOURCE_ROOT
MEDIA_URL = '/media/'


# 企业微信信息
CORP_ID = config['weixin']['corp_id']
CORP_SECRET = config['weixin']['corp_secret']
AGENT_ID = config['weixin']['agent_id']


SWAGGER_SETTINGS = {
    # 基础样式
    'SECURITY_DEFINITIONS': {
        "basic": {
            'type': 'basic'
        }
    },
    # 如果需要登录才能够查看接口文档, 登录的链接使用restframework自带的.
    'LOGIN_URL': '/admin/login',
    'LOGOUT_URL': '/admin/logout',
    # 'DOC_EXPANSION': None,
    # 'SHOW_REQUEST_HEADERS':True,
    # 'USE_SESSION_AUTH': True,
    # 'DOC_EXPANSION': 'list',
    # 接口文档中方法列表以首字母升序排列
    'APIS_SORTER': 'alpha',
    # 如果支持json提交, 则接口文档中包含json输入框
    'JSON_EDITOR': True,
    # 方法列表字母排序
    'OPERATIONS_SORTER': 'alpha',
    'VALIDATOR_URL': None,
    # 'DEFAULT_PAGINATOR_INSPECTORS': [
    #     'utils.frame.pagination.DrfYasgDjangoRestResponsePagination',
    #     'drf_yasg.inspectors.CoreAPICompatInspector',
    # ]
}


# web URL
WEB_BASE_URL = config['base']['web_base_url']

