import json
import time

import ezdxf
from tqdm import tqdm

import core
from drawer import ShaftDrawer, TunDrawer, WindowDrawer, GateDrawer, FanMainDrawer, FanSystemDrawer, WindFlowDrawer
from drawer.WindBridgeDrawer import WindBridgeDrawer

import requests

url = 'http://192.168.183.216:8008/python/tunCAD'


def calculate_route_middle(wind_flow_unit):
    path_start = wind_flow_unit[0]['x'], wind_flow_unit[0]['z']
    path_end = wind_flow_unit[-1]['x'], wind_flow_unit[-1]['z']
    path_middle = core.find_point_on_line(path_start, path_end, 1 / 2)
    route = core.calculate_angle_with_x_axis(path_start, path_end)
    return path_middle, route


if __name__ == '__main__':
    response = requests.get(url)
    print(f"请求耗时 {response.elapsed.total_seconds()} 秒")
    cad_json = {}
    if response.status_code == 200:
        cad_json = response.json()  # 将响应内容解析为JSON格式
        # print(json.dumps(result, indent=4))  # 使用json.dumps来美化打印结果
    else:
        print(f"请求失败，状态码：{response.status_code}")

    # doc = ezdxf.readfile("data/moban.dxf", encoding="utf-8")
    doc = ezdxf.new('R2000')
    doc.styles.add("LiberationSerif", font="LiberationSerif.ttf")
    msp = doc.modelspace()

    # with open("data/Cad.json", 'r', encoding='utf-8') as r:
    #     cad_json = json.loads(r.read())
    node_list = cad_json["tunsMapCAD"]
    tun_list = []
    window_list = []
    gate_list = []
    fan_list = []
    for node in node_list:
        node = node[1]
        tun = {
            "vec12": node["vec12"],
            "vec34": node["vec34"],
            "tun_id": node["ntunid"],
            "from": (node["nfrom"]["x"], node["nfrom"]["z"]),
            "to": (node["nto"]["x"], node["nto"]["z"]),
            "layer_id": node["nlayerid"],
            "width": node["fwidth"],
            "type": node["tunType"],
            "angle": node["angleRad"],
            "route": core.calculate_angle_with_x_axis((node["nfrom"]["x"], node["nfrom"]["z"]),
                                                      (node["nto"]["x"], node["nto"]["z"]))
        }
        tun_list.append(tun)
        for window in node["windows"]:
            window["route"] = tun["route"]
            window["gap"] = node["fwidth"]

        window_list.extend(node["windows"])
        for gate in node["gates"]:
            gate["route"] = tun["route"]
            gate["gap"] = node["fwidth"]
        gate_list.extend(node["gates"])

        for fan in node["fans"]:
            fan["route"] = tun["route"]
            fan["gap"] = node["fwidth"]

        fan_list.extend(node["fans"])

    for tun in tqdm(tun_list, desc=' 【巷道绘制中】'):
        if tun['type'] == '1':
            shaft_center = tun['from'][0], tun['from'][1]
            sd = ShaftDrawer(msp, tun['width'], shaft_center, tun["route"], 42)
            sd.draw_shaft_drawer()
        else:
            vec12 = []
            vec34 = []
            for item in tun['vec12']:
                vec12.append({
                    "x": item["x"],
                    "y": item["z"]
                })
            for item in tun['vec34']:
                vec12.append({
                    "x": item["x"],
                    "y": item["z"]
                })
            color = core.get_color_by_layer(tun['layer_id'])

            td = TunDrawer(msp, tun['layer_id'], color, vec12, vec34, tun["from"], tun["to"])
            td.draw_tun()

    for window in tqdm(window_list, desc=f' 【风窗绘制中】'):
        point_c = window['x'], window['z']
        wd = WindowDrawer(msp, window["gap"], point_c, window["route"])
        wd.draw_window()

    for gate in tqdm(gate_list, desc=f' 【风窗绘制中】'):
        point_c = gate['x'], gate['z']
        gd = GateDrawer(msp, gate["gap"], point_c, gate["route"])
        gd.draw_gate()

    for fan in tqdm(fan_list, desc=f' 【风扇绘制中】'):
        if 'fanmain' in str(fan['strtype']):
            point_c = fan['x'], fan['z']
            fmd = FanMainDrawer(msp, fan["gap"], point_c, fan["route"])
            fmd.draw_fan_main()
        if 'fansystem' in str(fan['strtype']):
            point_c = fan['x'], fan['z']
            fsd = FanSystemDrawer(msp, fan["gap"], point_c, fan["route"])
            fsd.draw_fan_system()

    path_point_layers = cad_json["pathPointMap"]

    for path_point in path_point_layers:

        in_paths = path_point[1]['inPaths']
        for in_path in tqdm(in_paths, desc=f'图层{path_point[0]} 【进风方向绘制中】'):
            if len(in_path) != 0:
                path_middle, route = calculate_route_middle(in_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
                wfd.draw_wind_flow()
        no_paths = path_point[1]['noPaths']
        for no_path in tqdm(no_paths, desc=f'图层{path_point[0]} 【未指定方向绘制中】'):
            if len(no_path) != 0:
                path_middle, route = calculate_route_middle(no_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 3)
                wfd.draw_wind_flow()
        out_paths = path_point[1]['outPaths']
        for out_path in tqdm(out_paths, desc=f'图层{path_point[0]} 【回风方向绘制中】'):
            if len(out_path) != 0:
                path_middle, route = calculate_route_middle(out_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)
                wfd.draw_wind_flow()
        use_paths = path_point[1]['usePaths']
        for use_path in tqdm(use_paths, desc=f'图层{path_point[0]} 【用风方向绘制中】'):
            if len(use_path) != 0:
                path_middle, route = calculate_route_middle(use_path)
                wfd = WindFlowDrawer(msp, 5, path_middle, route, 1)

    layer_map = cad_json["layerMap"]

    for layer in layer_map:
        cross_nodes = layer[1]['crossNodes']
        for cross_node in tqdm(cross_nodes, desc=f'图层{layer[0]} 【风桥绘制中】'):
            center = cross_node['crossPoint']['x'], -cross_node['crossPoint']['y']
            tun = [tun_ for tun_ in tun_list if tun_.get("tun_id") == cross_node['tun1Id']][0]
            route = core.calculate_angle_with_x_axis(tun["from"], tun["to"])
            line_1 = (tun["vec12"][0]["x"], tun["vec12"][0]["z"]), (tun["vec12"][-1]["x"], tun["vec12"][-1]["z"])
            line_2 = (tun["vec34"][0]["x"], tun["vec34"][0]["z"]), (tun["vec34"][-1]["x"], tun["vec34"][-1]["z"])
            gap = core.min_distance_between_segments(line_1,
                                                     line_2)
            wbd = WindBridgeDrawer(msp, center, cross_node['tun1Id'], cross_node['tun2Id'], layer[0], tun["angle"], gap)
            wbd.draw_wind_bridge_drawer()

    a = time.time()
    doc.saveas(f'save/tuns{str(a)}.dxf')
