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
from flask_caching import Cache

config = {
    "DEBUG": True,          # some Flask specific configs
    "CACHE_TYPE": "SimpleCache",  # Flask-Caching related configs
    "CACHE_DEFAULT_TIMEOUT": 300
}

app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)


@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")

    logger.info("请求调度模式")

    try:

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

        # 清空数据库缓存
        session_postgre.commit()
        session_postgre.flush()
    except Exception as es:
        logger.error("数据库访问异常")
        logger.error(es)
        return jsonify(msg="未知异常, 请联系管理员", code=506)

    try:

        # 全局参数更新
        global_period_para_update()
        # get_global_para_from_cache(cache)

        # 实例化设备对象
        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()
    except Exception as es:
        logger.error("参数更新异常")
        logger.error(es)
        session_mysql.rollback()
        session_postgre.rollback()
        return jsonify(msg="未知异常, 请联系管理员", code=505)

    request_trucks = []
    try:
        request_trucks = dispatcher.group.group_dispatch_truck[group_id]
    except Exception as es:
        logger.error(es)
        return jsonify(msg="未知异常, 请联系管理员", code=504)

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

        if get_value("dynamic_dump_num") * get_value("dynamic_excavator_num") == 0:
            # raise Exception("无动态派车计划可用")
            return jsonify(msg="未知异常, 请联系管理员", code=503)
        if get_value("dynamic_truck_num") == 0:
            # raise Exception("无动态派车可用矿卡")
            return jsonify(msg="未知异常, 请联系管理员", code=502)

        # 更新请调矿卡派车计划
        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="未知异常, 请联系管理员", code=501)

    # DBsession_postgre.close_all()
    # DBsession_mysql.close_all()

    session_mysql.close()
    session_postgre.close()

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

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

    return jsonify(msg="success", code=0)