import os
from Ansjer.config import BASE_DIR

SECRET_KEY = 'c7ki2_gkg4#sjfm-u1%$s#&n#szf01f*v69rwv2qsf#-zmm@tl'
DEBUG = True
# DEBUG = False
ALLOWED_HOSTS = ['*']

DEFAULT_AUTO_FIELD = 'django.db.models.AutoField'

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',
    'imagekit',
    'Model',
    'PushModel',
    'django_apscheduler',
    'AgentModel',
    'django_celery_beat',
    'Roomumy'
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'Service.middleware.StatisticsUrlMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'MiddleWare.requestRecord.RequestRecordMiddleware',  # 记录请求信息
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'corsheaders.middleware.CorsPostCsrfMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
]

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',  # django default backend
)

ADDR_URL = []
ANONYMOUS_USER_ID = -1  # 支持匿名用户

STATIC_URL = './static/'

# 上传路径根目录
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/Upgrate')
# 在浏览器上访问该上传文件的url的前缀
MEDIA_URL = '/static/Upgrate/'
ROOT_URLCONF = 'Ansjer.urls'
LOGIN_URL = '/account/login'
AUTH_USER_MODEL = 'Model.Device_User'  # 自定义Model
APPEND_SLASH = False

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR + '/templates', ],
        '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 = 'Ansjer.cn_config.test_wsgi.application'

# 业务数据库
DATABASE_DATA = 'ansjer_server_test'
SERVER_HOST = '124.70.222.33'
DATABASES_USER = 'root'
DATABASES_PASS = 'Ansjer123'

# 推送数据库
DATABASE_DATA2 = 'ansjer_push_test'
SERVER_HOST2 = '124.70.222.33'
DATABASES_USER2 = 'root'
DATABASES_PASS2 = 'Ansjer123'

# 业务代理客户数据库
DATABASE_DATA3 = 'test_asj_agent'
SERVER_HOST3 = '124.70.222.33'
DATABASES_USER3 = 'root'
DATABASES_PASS3 = 'Ansjer123'

# 袋鼠妈妈数据库
DATABASE_DATA4 = 'test_roomumy'
SERVER_HOST4 = '124.70.222.33'
DATABASES_USER4 = 'root'
DATABASES_PASS4 = 'Ansjer123'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DATABASE_DATA,
        'USER': DATABASES_USER,
        'PASSWORD': DATABASES_PASS,
        'HOST': SERVER_HOST,
        'PORT': '3306',
        'AUTOCOMMIT': True,
        'CONN_MAX_AGE': 60,
        'OPTIONS': {
            'charset': 'utf8mb4',
            'use_unicode': True,
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        }
    },
    'mysql02': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DATABASE_DATA2,
        'USER': DATABASES_USER2,
        'PASSWORD': DATABASES_PASS2,
        'HOST': SERVER_HOST2,
        'PORT': '3306',
        'AUTOCOMMIT': True,
        'CONN_MAX_AGE': 60,
        'OPTIONS': {
            'charset': 'utf8mb4',
            'use_unicode': True,
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        }
    },
    'mysql03': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DATABASE_DATA3,
        'USER': DATABASES_USER3,
        'PASSWORD': DATABASES_PASS3,
        'HOST': SERVER_HOST3,
        'PORT': '3306',
        'AUTOCOMMIT': True,
        'CONN_MAX_AGE': 60,
        'OPTIONS': {
            'charset': 'utf8mb4',
            'use_unicode': True,
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        }
    },
    'mysql04': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': DATABASE_DATA4,
        'USER': DATABASES_USER4,
        'PASSWORD': DATABASES_PASS4,
        'HOST': SERVER_HOST4,
        'PORT': '3306',
        'AUTOCOMMIT': True,
        'CONN_MAX_AGE': 60,
        'OPTIONS': {
            'charset': 'utf8mb4',
            'use_unicode': True,
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'"
        }
    },
}

DATABASE_ROUTERS = ['Ansjer.database_router.DatabaseAppsRouter']
DATABASE_APPS_MAPPING = {
    'Model': 'default',
    'django_apscheduler': 'default',
    'PushModel': 'mysql02',
    'AgentModel': 'mysql03',
    'Roomumy': 'mysql04'
}

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

# celery配置,需要以CELERY_开头
# 设置broker
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0'
# 设置结果存储
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/1'

# 配置定时任务
CELERY_TIMEZONE = 'Asia/Shanghai'
DJANGO_CELERY_BEAT_TZ_AWARE = True
CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Shanghai'
# TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True

# 跨域增加忽略
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',
)

#########################################
'''
增加错误信息推送到管理员邮箱
'''
# 管理员邮箱
ADMINS = (
    ('admin', 'sonalh@foxmail.com'),
)

# 非空链接，却发生404错误，发送通知MANAGERS
SEND_BROKEN_LINK_EMAILS = True
MANAGERS = ADMINS

# Email设置
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.163.com'  # QQ邮箱SMTP服务器(邮箱需要开通SMTP服务)
EMAIL_PORT = 25  # QQ邮箱SMTP服务端口
EMAIL_HOST_USER = 'chanjunkai@163.com'  # 我的邮箱帐号
EMAIL_HOST_PASSWORD = 'cjk1234'  # 授权码
EMAIL_SUBJECT_PREFIX = 'website'  # 为邮件标题的前缀,默认是'[django]'
EMAIL_USE_TLS = True  # 开启安全链接
DEFAULT_FROM_EMAIL = SERVER_EMAIL = EMAIL_HOST_USER  # 设置发件人

LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'error_format': {
            'format': '%(asctime)s %(threadName)s %(thread)d %(lineno)d %(levelname)s %(message)s'
        },
        'standard': {
            'format': '[%(asctime)s] [%(filename)s:%(lineno)d] [%(module)s:%(funcName)s] '
                      '[%(levelname)s]- %(message)s'},

    },
    'filters': {
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'class': 'django.utils.log.AdminEmailHandler',
            'include_html': True,
        },
        'default': {
            'level': 'ERROR',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR + '/static/log/error/error.log',
            'maxBytes': 1024 * 1024 * 5,  # 5 MB
            'backupCount': 5,
            'formatter': 'error_format',
        },
        'console': {
            'level': 'ERROR',
            'class': 'logging.StreamHandler',
            'formatter': 'error_format'
        },
        'info': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR + '/static/log/info/info.log',
            'backupCount': 3,
            'maxBytes': 1024 * 1024 * 2 * 1024,  # 2G
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'error_code': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR + '/static/log/error_code/error_code.log',
            'backupCount': 3,
            'maxBytes': 1024 * 1024 * 2 * 1024,  # 2G
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'success_code': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR + '/static/log/success_code/success_code.log',
            'backupCount': 3,
            'maxBytes': 1024 * 1024 * 2 * 1024,  # 2G
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'pay': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': BASE_DIR + '/static/log/pay/info.log',
            'backupCount': 60,
            'when': 'D',
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'apple_pay': {
            'level': 'INFO',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': BASE_DIR + '/static/log/apple_pay/apple_pay.log',
            'backupCount': 3,
            'maxBytes': 1024 * 1024 * 2 * 1024,  # 2G
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
        'token': {
            'level': 'INFO',
            'class': 'logging.handlers.TimedRotatingFileHandler',
            'filename': BASE_DIR + '/static/log/token/token.log',
            'backupCount': 60,
            'when': 'D',
            'formatter': 'standard',
            'encoding': 'utf-8',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['default', 'console'],
            'level': 'ERROR',
            'propagate': False
        },
        # log 调用时需要当作参数传入
        'info': {
            'handlers': ['info'],
            'level': 'INFO',
            'propagate': False
        },
        'error_code': {
            'handlers': ['error_code'],
            'level': 'INFO',
            'propagate': False
        },
        'success_code': {
            'handlers': ['success_code'],
            'level': 'INFO',
            'propagate': False
        },
        'pay': {
            'handlers': ['pay'],
            'level': 'INFO',
            'propagate': False
        },
        'apple_pay': {
            'handlers': ['apple_pay'],
            'level': 'INFO',
            'propagate': False
        },
        'token': {
            'handlers': ['token'],
            'level': 'INFO',
            'propagate': False
        },
    }
}
