#!E:\Pycharm Projects\Waytous
# -*- coding: utf-8 -*-
# @Time : 2021/7/21 16:45
# @Author : Opfer
# @Site :
# @File : realtime_dispatch.py
# @Software: PyCharm


# 实时调度模块
from para_config import *
from equipment.truck import TruckInfo
from equipment.excavator import ExcavatorInfo
from equipment.dump import DumpInfo
import sched
import time
from core.dispatcher import Dispatcher
from core.schedule import PreSchedule
from data.dispatchInfo import DispatchInfo


def process(dispatcher):
    """
    周期调度进程
    :param dispatcher:  (Dispatch Class) 矿卡调度类对象
    :return: None
    """

    # try:
    # 更新周期参数
    logger.info("#####################################周期更新开始#####################################")

    global_period_para_update()

    if get_value("dynamic_dump_num") * get_value("dynamic_excavator_num") == 0:
        raise Exception("无动态派车计划可用")
        return
    if get_value("dynamic_truck_num") == 0:
        raise Exception("无动态派车可用矿卡")
        return

    # 清空数据库缓存
    session_mysql.commit()
    session_mysql.flush()

    # 清空数据库缓存
    session_postgre.commit()
    session_postgre.flush()

    global_period_para_update()

    # 更新数据
    DispatchInfo.renew_set()

    DispatchInfo.dispatch_group_init()

    DispatchInfo.update_device_group_structure()

    DispatchInfo.update_route_distance()

    DispatchInfo.update_group_mode()

    # 调度生成
    dispatcher.period_update()

    dispatcher.group_generate()

    dispatcher.group_dispatch()

    #     logger.info("#####################################周期更新结束#####################################")
    #
    # except Exception as es:
    #     logger.error("最外层异常捕获")
    #     logger.error(es)


def perform(inc, dispatcher):
    """
    控制程序循环执行
    :param inc: (int) 循环周期, 单位, 秒
    :param dispatcher:  (Dispatch Class) 矿卡调度类对象
    :return: None
    """
    scheduler.enter(inc, 0, perform, (inc, dispatcher))
    process(dispatcher)


def main(inc, dispatcher):
    """
    程序循环入口函数
    :param inc:  (int) 循环周期, 单位, 秒
    :param dispatcher:  (Dispatch Class) 矿卡调度类对象
    :return: None
    """
    scheduler.enter(0, 0, perform, (inc, dispatcher))
    scheduler.run()


if __name__ == "__main__":

    # 初始化日志
    set_log()
    # 获取日志器
    logger = get_logger("zxt.main")

    # 全局参数更新
    global_period_para_update()

    # 实例化设备对象
    dump = DumpInfo()
    excavator = ExcavatorInfo()
    truck = TruckInfo(dump, excavator)

    # 实例化程序调度器
    scheduler = sched.scheduler(time.time, time.sleep)

    # 实例化调度预测器
    pre_sch = PreSchedule(truck, excavator, dump)

    # 实例化矿卡调度器
    dispatcher = Dispatcher(truck, dump, excavator, pre_sch, False)

    logger.info(" ")
    logger.info("调度系统启动")

    main(30, dispatcher)
