from flask import Flask, request
from flask.json import jsonify
from para_config import *
from equipment.truck import TruckInfo
from equipment.excavator import ExcavatorInfo
from equipment.dump import DumpInfo
from dispatcher import Dispatcher, PreSchedule, DispatchSubmission

app = Flask(__name__)


@app.route("/dispatch", methods=["POST"])
def dispatch_request():

    # 获取报文数据
    data_json = request.get_json()

    # 分组id
    group_id = data_json.get("group_id")

    # 调度开始时间
    rtd_start_time = datetime.now()

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

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

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

    # 全局参数更新
    global_period_para_update()

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

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

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

    # 周期更新
    dispatcher.dispatcher_period_update()

    request_trucks = []
    try:

        request_trucks = dispatcher.group.group_dispatch_truck[group_id]
    except Exception as es:
        logger.error(es)
        return jsonify(msg="派车计划生成失败", detail="调度分组异常",  code=1005)

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

        if get_value("dynamic_dump_num") * get_value("dynamic_excavator_num") == 0:
            # raise Exception("无动态派车计划可用")
            return jsonify(msg="派车计划生成失败", detail="无动态派车计划可用", code=1003)
        if get_value("dynamic_truck_num") == 0:
            # raise Exception("无动态派车可用矿卡")
            return jsonify(msg="派车计划生成失败", detail="无动态派车可用矿卡", code=1004)

        # 更新请调矿卡派车计划
        for truck_id in request_trucks:
            # 调度计算
            dispatcher.truck_request(truck_id)

        logger.info("#####################################请求调度更新结束#####################################")

    except Exception as es:
        logger.error("最外层异常捕获")
        logger.error(es)
        return jsonify(msg="派车计划生成失败", detail="未知异常",  code=1002)

    # 调度结束时间
    rtd_end_time = datetime.now()

    print(f'调度时耗 {rtd_end_time - rtd_start_time}')

    return jsonify(msg="派车计划生成成功", code=1001)