"""
Django settings for industrial_internet_wss project.

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

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 sys
import datetime
from celery.schedules import timedelta
from celery.schedules import crontab

from .base import *

APPS_DIR = BASE_DIR.join("console")

# 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!
# SECURITY WARNING: don't run with debug turned on in production!

# Application definition
DJANGO_APPS = [
    'django.contrib.admin', 'django.contrib.auth',
    'django.contrib.contenttypes', 'django.contrib.sessions',
    'django.contrib.messages', 'django.contrib.staticfiles',
    'django_extensions', "dwebsocket", "notifications.base"
]
WEBSOCKET_ACCEPT_ALL = True
THIRD_PARTY_APPS = [
    'rest_framework',
    'django_filters',
    'drf_yasg',
    'rest_framework_jwt',
]

COMMON_APPS = [
    'common.accounts', "common.forms", "common.upload", 'common.configs',
    'common.celery_task'
]

LOCAL_APPS = [
    "console.test", "console.customer", "console.electricityuser",
    "console.powerstation", "console.team", "console.learningcenter",
    "console.task", "console.order", "console.electrical_info",
    "console.inspection", "console.equipment", "console.dashboard",
    "console.contract", "console.organizations", "console.APP",
    "console.dictionary", "console.wechat", "console.home_page",
    "console.circuit_diagram", "console.message", "console.monitor",
    "console.electricity_bill", "console.customer_system",
    "console.video_management", "console.sim_card", "crm.plan",
    "crm.crm_customer", "crm.crm_statistic",
    "crm.crm_app", "crm.crm_users",
]

OPEN_APPS = ["openapi.individual_soldier"]

INSTALLED_APPS = DJANGO_APPS + THIRD_PARTY_APPS + COMMON_APPS + LOCAL_APPS + OPEN_APPS

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',
    'common.utils.log.ExceptionLoggingMiddleware',
    'django.middleware.gzip.GZipMiddleware',
]

# if OPEN_SILK:
#     MIDDLEWARE.append('silk.middleware.SilkyMiddleware')

AUTHENTICATION_BACKENDS = [
    "common.utils.auth_backends.CustomAuthBackend",
    "django.contrib.auth.backends.ModelBackend",
]

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

DATABASES = {
    # 'default': {
    #     'ENGINE': 'django.db.backends.mysql',
    #     'NAME': os.environ.get("MYSQL_DB", 'console'),
    #     'USER': os.environ.get('MYSQL_USER', 'root'),
    #     'PASSWORD': os.environ.get('MYSQL_PASS', '1qaz@WSX'),
    #     'HOST': os.environ.get('MYSQL_HOST',
    #                            'sh-cdb-ptpdw86e.sql.tencentcdb.com'),
    #     'PORT': os.environ.get('MYSQL_PORT', 60852),
    #     'OPTIONS': {
    #         "init_command": "SET foreign_key_checks = 0;",
    #         'charset': 'utf8mb4',
    #     }
    # },
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ.get("MYSQL_DB", 'console'),
        'USER': os.environ.get('MYSQL_USER', 'root'),
        'PASSWORD': os.environ.get('MYSQL_PASS', 'Afa@1qaz2wsx'),
        'HOST': os.environ.get('MYSQL_HOST',
                               '188.131.235.243'),
        'PORT': os.environ.get('MYSQL_PORT', 31007),
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;",
            'charset': 'utf8mb4',
        }
    },
    'power_oa': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'power_oa',
        'USER': 'poweroa_xzjn',
        'PASSWORD': 'EPK22xzjn',
        'HOST': 'rm-uf690m4x98j71szlno.mysql.rds.aliyuncs.com',
        'PORT': 3306,
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;",
            'charset': 'utf8mb4',
        }
    },
    'monitor_oa': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_powerdata',
        'USER': 'powerdata_ts',
        'PASSWORD': 'EPK333ts',
        'HOST': 'rm-uf62t848gm38k2y5mo.mysql.rds.aliyuncs.com',
        'PORT': 3306,
        'OPTIONS': {
            'charset': 'utf8mb4',
        }
    },
    'monitor': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "monitor",
        'USER': os.environ.get('MYSQL_USER', 'root'),
        'PASSWORD': os.environ.get('MYSQL_PASS', '1qaz@WSX'),
        'HOST': os.environ.get('MYSQL_HOST',
                               'sh-cdb-ptpdw86e.sql.tencentcdb.com'),
        'PORT': os.environ.get('MYSQL_PORT', 60852),
    },
    'score': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ.get("MYSQL_DB", 'faladi'),
        'USER': os.environ.get('MYSQL_USER', 'root'),
        'PASSWORD': os.environ.get('MYSQL_PASS', '1qaz@WSX'),
        'HOST': os.environ.get('MYSQL_HOST',
                               'sh-cdb-ptpdw86e.sql.tencentcdb.com'),
        'PORT': os.environ.get('MYSQL_PORT', 60852),
        'OPTIONS': {
            "init_command": "SET foreign_key_checks = 0;",
            'charset': 'utf8mb4',
        }
    },
}
# DATABASES = {"default": env.db("DATABASE_URL")}
# DATABASES["default"]["ATOMIC_REQUESTS"] = True
DJANGO_REDIS_IGNORE_EXCEPTIONS = True
DJANGO_REDIS_LOG_IGNORED_EXCEPTIONS = True
AppId = "xxxx"  # 写小程序的id
AppSecret = "xxxx"  # 写小程序的秘钥
code2Session = "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code"

REDIS_HOST = os.environ.get("REDIS_HOST", "127.0.0.1")
REDIS_PORT = os.environ.get("REDIS_PORT", "6379")
REDIS_PASSWORD = os.environ.get("REDIS_PASSWORD", None)
# https://docs.djangoproject.com/en/dev/ref/settings/#root-urlconf
ROOT_URLCONF = "etc.urls.urls"
# https://docs.djangoproject.com/en/dev/ref/settings/#wsgi-application
WSGI_APPLICATION = "etc.wsgi.wsgi.application"

# 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/

# STATIC
# ------------------------------------------------------------------------------
# https://docs.djangoproject.com/en/dev/ref/settings/#static-root
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'formatters': {
        'standard': {
            'format':
                "%(asctime)s [%(levelname)s] localhost [%(funcName)s] %(pathname)s:%(lineno)s %(message)s",
            'datefmt': "%Y-%m-%d %H:%M:%S"
        },
    },
    'handlers': {
        'file_handler': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_PATH, 'console.log'),
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 5,
            'formatter': 'standard',
        },
        'request_api': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(LOG_PATH, 'request.log'),
            'maxBytes': 1024 * 1024 * 5,
            'backupCount': 5,
            'formatter': 'standard',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'stream': sys.stdout,
            'formatter': 'standard'
        }
    },
    'loggers': {
        '': {
            'handlers': DEFAULT_HANDLERS,
            'level': 'DEBUG',
            'propagate': True,
        },
        'request_api': {
            'handlers': ['request_api'],
            'level': 'DEBUG',
            'propagate': True,
        },
        'django.request': {
            'handlers': ['request_api'],
            'level': 'DEBUG',
            'propagate': True,
        }
    }
}

# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS
# STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")]
# https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
    "django.contrib.staticfiles.finders.FileSystemFinder",
    "django.contrib.staticfiles.finders.AppDirectoriesFinder",
]

# rest-framework
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_PERMISSION_CLASSES':
        ('rest_framework.permissions.IsAuthenticated',),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
    'DEFAULT_FILTER_BACKENDS':
        ('django_filters.rest_framework.DjangoFilterBackend',),
    'DEFAULT_PAGINATION_CLASS':
        'common.utils.pagination.CustomPageNumberPagination',
    'PAGE_SIZE':
        10,
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
        'rest_framework.parsers.FormParser',
        'rest_framework.parsers.MultiPartParser',
        'rest_framework.parsers.FileUploadParser',
    ),
    'EXCEPTION_HANDLER':
        'common.utils.exceptions.custom_exception_handler'
}

JWT_AUTH = {
    'JWT_ENCODE_HANDLER': 'rest_framework_jwt.utils.jwt_encode_handler',
    'JWT_DECODE_HANDLER': 'rest_framework_jwt.utils.jwt_decode_handler',
    'JWT_PAYLOAD_HANDLER': 'rest_framework_jwt.utils.jwt_payload_handler',
    'JWT_PAYLOAD_GET_USER_ID_HANDLER':
        'rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler',
    'JWT_RESPONSE_PAYLOAD_HANDLER':
        'rest_framework_jwt.utils.jwt_response_payload_handler',
    'JWT_SECRET_KEY': SECRET_KEY,
    'JWT_GET_USER_SECRET_KEY': None,
    'JWT_PUBLIC_KEY': None,
    'JWT_PRIVATE_KEY': None,
    'JWT_ALGORITHM': 'HS256',
    'JWT_VERIFY': True,
    'JWT_VERIFY_EXPIRATION': True,
    'JWT_LEEWAY': 0,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(seconds=604800),
    'JWT_AUDIENCE': None,
    'JWT_ISSUER': None,
    'JWT_ALLOW_REFRESH': False,
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
    'JWT_AUTH_HEADER_PREFIX': 'AFAJWT',
    'JWT_AUTH_COOKIE': "token",
}

# Celery
# ------------------------------------------------------------------------------
if USE_TZ:
    # http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-timezone
    CELERY_TIMEZONE = TIME_ZONE
    CELERY_ENABLE_UTC = True
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-broker_url
if REDIS_PASSWORD:
    REDIS_BASE_URL = "redis://:{}@{}:{}/".format(REDIS_PASSWORD, REDIS_HOST, REDIS_PORT)
else:
    REDIS_BASE_URL = "redis://{}:{}/".format(REDIS_HOST, REDIS_PORT)
REDIS_URL = REDIS_BASE_URL + "1"
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER_URL", REDIS_BASE_URL + "7")
CELERY_RESULT_BACKEND = os.environ.get("CELERY_BACKEND_URL", REDIS_BASE_URL + "8")
CELERYD_MAX_TASKS_PER_CHILD = 100
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-accept_content
CELERY_ACCEPT_CONTENT = ["json"]
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-task_serializer
CELERY_TASK_SERIALIZER = "json"
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#std:setting-result_serializer
CELERY_RESULT_SERIALIZER = "json"
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-time-limit
CELERYD_TASK_TIME_LIMIT = 15 * 60
# http://docs.celeryproject.org/en/latest/userguide/configuration.html#task-soft-time-limit
CELERYD_TASK_SOFT_TIME_LIMIT = 60

CELERYD_FORCE = True

# Celery 定时器配置
CELERY_BEAT_SCHEDULE = {
    'shard_log': {
        'task': 'common.celery_task.tasks.shard_log',
        'schedule': crontab(hour=0),
    },
    'create_inspection_plan': {
        'task': 'common.celery_task.tasks.create_plan',
        'schedule': crontab(hour=0, minute=0),
    },
    'dashboard_customer_list': {
        'task': 'common.celery_task.tasks.dashboard_customers',
        'schedule': timedelta(minutes=15),
    },
    'create_day_inspection_task': {
        'task': 'common.celery_task.tasks.create_day_inspection_task',
        'schedule': timedelta(minutes=30),
    },
    # 'sync_transformer_capacity': {
    #     'task': 'common.celery_task.tasks.sync_transformer_capacity',
    #     'schedule': timedelta(minutes=60),
    # },
    'clear_dashboard_zero_eq': {
        'task': 'common.celery_task.tasks.clear_dashboard_zero_eq',
        'schedule': crontab(hour=0, minute=30),
    },
    'check_monitor_over_tm': {
        'task': 'common.celery_task.tasks.check_monitor_over_tm',
        'schedule': timedelta(minutes=15),
    },
    'check_monitor_data_density': {
        'task': 'common.celery_task.tasks.check_monitor_data_density',
        'schedule': crontab(hour=8, minute=0),
    },
    'get_dashboard_month_ep': {
        'task': 'common.celery_task.tasks.get_dashboard_month_ep',
        'schedule': timedelta(seconds=10),
    },
    'get_dashboard_real_data': {
        'task': 'common.celery_task.tasks.get_dashboard_real_data',
        'schedule': timedelta(seconds=10),
    },
    'del_user_location': {
        'task': 'common.celery_task.tasks.del_timeout_user_location',
        'schedule': timedelta(seconds=10),
    },
    'sync_monitor_points_and_devices_from_oa': {
        'task': 'common.celery_task.tasks.sync_monitor_points_and_devices_from_oa',
        'schedule': timedelta(hours=1),
    },
    'sync_monitor_points_from_oa': {
        'task': 'common.celery_task.tasks.sync_monitor_points_from_oa',
        'schedule': timedelta(hours=1),
    },
    'insert_oa_real_data': {
        'task': 'common.celery_task.tasks.insert_oa_real_data',
        'schedule': crontab(minute='0,15,30,45'),
    },
    # 'insert_changsha_mo_dt_sync': {
    #     'task': 'common.celery_task.tasks.insert_changsha_mo_dt_sync',
    #     'schedule': timedelta(minutes=15),
    # },
    # 'get_changsha_month_ep': {
    #     'task': 'common.celery_task.tasks.get_changsha_month_ep',
    #     'schedule': timedelta(minutes=5),
    # },
    # 'get_changsha_real_data': {
    #     'task': 'common.celery_task.tasks.get_changsha_real_data',
    #     'schedule': crontab(minute="*/5"),
    # },
}

SWAGGER_SETTINGS = {
    'PERSIST_AUTH': True,
    'REFETCH_SCHEMA_WITH_AUTH': True,
    'REFETCH_SCHEMA_ON_LOGOUT': True,
    'DEFAULT_INFO': 'etc.urls.base.swagger_info',
    'SECURITY_DEFINITIONS': {
        'Bearer': {
            'type': 'apiKey',
            'name': 'authorization',
            'in': 'header'
        },
    }
}

REDOC_SETTINGS = {
    # ReDoc UI configuration settings, see https://github.com/Rebilly/ReDoc#redoc-tag-attributes
    'LAZY_RENDERING': True,
    'HIDE_HOSTNAME': False,
    'EXPAND_RESPONSES': 'all',
    'PATH_IN_MIDDLE': False,
}


class DisableMigrations(object):
    def __contains__(self, item):
        return True

    def __getitem__(self, item):
        return None


APPEND_SLASH = False
TESTS_IN_PROGRESS = False
if 'test' in sys.argv[1:] or 'jenkins' in sys.argv[1:]:
    PASSWORD_HASHERS = ('django.contrib.auth.hashers.MD5PasswordHasher',)
    DEBUG = False
    TEMPLATE_DEBUG = False
    TESTS_IN_PROGRESS = True
    MIGRATION_MODULES = DisableMigrations()

# 腾讯云短信平台配置
SMS_APPID = os.getenv("SMS_APPID", "1400450392")
SMS_APPKEY = os.getenv("SMS_APPKEY", "3d7ad25730d4a303f67a424a7c544e2e")
SMS_SIGN = os.getenv("SMS_SIGN", "电管家")

# 栾数接口对接配置
PUBBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" + \
              "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOMvYDjrahRshdTN6DmYJ5H09" + \
              "+5QtH07ISLjUGfyd8JKpZm5nCChV7oYDxcAxT" + \
              "p2ozMBHqL4Ss9OAqAVI0+RQhkCAwEAAQ==\n" + \
              "-----END PUBLIC KEY-----"
ORGANIZATION_CODE = "DGJ-20201130"
TOKEN_URL = "https://dtdx-api-xzhdwg3.as.digitwin.com.cn/kq-get-token"
UPLOAD_FILE_URL = "https://dtdx-api-xzhdwg3.as.digitwin.com.cn/dtdw-uploads"
GET_FILE_URL = "https://dtdx-api-xzhdwg3.as.digitwin.com.cn/dtdw-launch-urls/"

# twilio自动拨号配置
TWILIO_ACCOUNT_SID = "ACb578ab2594b7265610df19670ad67e50"
TWILIO_ACCOUNT_TOKEN = "ccffea7c5e442b8a78c0c3a3cff34373"
TWILIO_PHONE = "+17196314249"
TWILIO_CALL_URL = "http://192.168.0.193:8081/api/v1/console/message/call"

# 内存配置
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": REDIS_URL,
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

# 时区配置为上海
TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

# 置为False
USE_TZ = False

# celery定时任务告警号码
CELERY_NOTIFY_PHONE = ["17343184154", "18601179258", "18575156335"]
