#!E:\Pycharm Projects\Waytous
# -*- coding: utf-8 -*-
# @Time : 2021/7/23 11:25
# @Author : Opfer
# @Site :
# @File : settings.py
# @Software: PyCharm


# 数据库设备, redis设置, 日志设置
from tables import *
from urllib.parse import quote
import logging.handlers
import numpy as np
import os
from redis import StrictRedis, ConnectionPool
import redis
from datetime import datetime, timedelta
import copy
import json

json_file = "config.json"

with open(json_file) as f:
    para_config = json.load(f)["para"]

with open(json_file) as f:
    mysql_config = json.load(f)["mysql"]

with open(json_file) as f:
    postgre_config = json.load(f)["postgresql"]

with open(json_file) as f:
    redis_config = json.load(f)["redis"]

# 全局参数
########################################################################################################################
# 空载矿卡速度，单位（km/h）
empty_speed = para_config["empty_speed"]

# 重载矿卡速度，单位（km/h）
heavy_speed = para_config["heavy_speed"]

# 卸载设备目标卸载量
dump_target_mass = para_config["dump_target_mass"]

# 挖机目标装载量
excavator_target_mass = para_config["excavator_target_mass"]

logger = logging.getLogger("zxt")
logger.setLevel(logging.INFO)


def set_log():

    # 创建日志
    ########################################################################################################################
    # 日志存储地址
    log_path = para_config["log_path"]

    # 创建日志目录

    if not os.path.exists(log_path):
        os.mkdir(log_path)
    # logging初始化工作
    logging.basicConfig()


    # timefilehandler = logging.handlers.TimedRotatingFileHandler(log_path + "/dispatch.log", when='M', interval=1, backupCount=60)
    filehandler = logging.handlers.RotatingFileHandler(log_path + "/dispatch.log", maxBytes=3*1024*1024, backupCount=10)
    # filehandler = logging.handlers.RotatingFileHandler("./Logs/dispatch.log", maxBytes=3 * 1024 * 1024, backupCount=10)
    # 设置后缀名称，跟strftime的格式一样
    filehandler.suffix = "%Y-%m-%d_%H-%M.log"

    formatter = logging.Formatter("%(asctime)s - %(name)s: %(levelname)s %(filename)s %(message)s")
    filehandler.setFormatter(formatter)
    logger.addHandler(filehandler)


def get_logger(module_name):
    logger = logging.getLogger(module_name)
    return logger


# 连接reids
########################################################################################################################
# redis 5 存储设备状态
pool5 = ConnectionPool(host=redis_config["host"], db=5, port=6379, password=redis_config["password"])

redis5 = StrictRedis(connection_pool=pool5)

# redis 2 存储派车计划
pool2 = ConnectionPool(host=redis_config["host"], db=2, port=6379, password=redis_config["password"])

redis2 = StrictRedis(connection_pool=pool2)

# 数据库连接设置
########################################################################################################################
# 创建对象的基类:
Base = declarative_base()

sql_str = str("mysql+mysqlconnector://" + mysql_config["user"] + ":%s@" + mysql_config["host"] + \
              ":" + mysql_config["port"] + "/" + mysql_config["database"])

postgre_str = str("postgresql://" + postgre_config["user"] + ":%s@" + postgre_config["host"] + \
                  ":" + postgre_config["port"] + "/" + postgre_config["database"])

try:
    engine_mysql = create_engine(
        # "mysql+mysqlconnector://root:%s@192.168.28.111:3306/waytous"
        # % quote("Huituo@123")

        # "mysql+mysqlconnector://" + mysql_config["user"] + ":" + mysql_config["password"] + "@" + mysql_config[
        # "host"] + ":" + mysql_config["port"] + "/" + mysql_config["database"]

        sql_str % quote(mysql_config["password"])
    )

    engine_postgre = create_engine(
        # "postgresql://postgres:%s@192.168.28.111:5432/shenbao_2021520"
        # % quote("Huituo@123")

        # "postgresql://" + postgre_config["user"] + ":" + postgre_config["password"] + "@" + postgre_config[
        #     "host"] + ":" + postgre_config["port"] + "/" + postgre_config["database"]

        postgre_str % quote(postgre_config["password"])
    )

    # 创建DBsession_mysql类型:
    DBsession_mysql = sessionmaker(bind=engine_mysql)

    DBsession_mysql = scoped_session(DBsession_mysql)

    DBsession_postgre = sessionmaker(bind=engine_postgre)

    DBsession_postgre = scoped_session(DBsession_postgre)

    # 创建session_mysql对象:
    session_mysql = DBsession_mysql()

    session_mysql.expire_on_commit = False

    session_postgre = DBsession_postgre()

    session_postgre.expire_on_commit = False
except Exception as es:
    logger.error("数据库连接失败")
    logger.error(es)


def str_to_byte(item):
    return bytes(item, encoding='utf8')

def byte_to_str(item):
    return str(item, encoding='utf-8')
