let stopLineData
import * as mapTools from "@/utils/mapboxTools";
import { initWs } from "@/config/holo/websocket";
export default {
    data() {
        return {
            currentNearestCrossId: ''
        }
    },
    mounted() {
        fetch("stopLines.json").then((res) => {
            res.json().then((result) => {
                stopLineData = result.content;
                console.log('stopLineData', stopLineData);
            });
        });
    },
    methods: {
        resetLightNearestCross() {
            this.currentNearestCrossId = ''
        },
        refreshLightWs() {
            let map = window.map
            if (map.getZoom() < 17.5 || this.currentCheck!=='first') {
                this.closeWs("callLight").then(() => {
                    this.currentNearestCrossId = null;
                    this.removeLayers("lightLayer,lightLayerText");
                });
            } else {
                let targetPoint = turf.point([map.getCenter().lng, map.getCenter().lat]);
                // 取最近点的crossId   判断哪个路口离当前视野中心点最近 请求对应的灯态websocket
                let nearest = turf.nearestPoint(targetPoint, this.crossGeo);
                let nearestCrossId = nearest.properties.id;
                // 如果求得最近路口不是上次的最近路口，则关闭上个ws，请求最新路口ws
                if (nearestCrossId !== this.currentNearestCrossId) {
                    this.currentNearestCrossId = nearestCrossId;
                    this.closeWs("callLight").then(() => {
                        let socket = initWs({
                            // url: `${ws_config.CROSS_CONTROL}${nearestCrossId},holo-web`,
                            url: `ws://${window.wsHost}/utc/signalStatus/${nearestCrossId},holo-web`,
                            callback: this.callLight,
                            name: "callLight",
                        });
                        socket.ws.onopen = () => {
                            if (socket.ws.readyState === 1) {
                                this.sockets.push(socket);
                            }
                        };
                    });
                }
            }

        },
        // 处理灯态
        callLight(msg) {
            let lightResults = [];
            let waitResultFeatures = [];
            for (let crossLight of msg) {
                let dirsLights = crossLight.dirLampGroupMapList;
                for (let singleDirLight of dirsLights) {
                    let stopLine = stopLineData.find((stop) => {
                        return (
                            stop.lkid == crossLight.crossId &&
                            stop.dirtype == singleDirLight.dir
                        );
                    });
                    if (stopLine) {
                        // 停止线往路口中心偏移0.8米
                        let resultStopLine = turf.lineString(
                            JSON.parse(stopLine.geom).coordinates
                        );
                        let stopLineGeom = turf.lineOffset(resultStopLine, -0.0008, {
                            units: "kilometers",
                        }).geometry.coordinates;
                        let splitPoints = {};
                        splitPoints.left = stopLineGeom[0];
                        splitPoints.right = stopLineGeom[stopLineGeom.length - 1];
                        splitPoints.center = turf.midpoint(
                            turf.point(splitPoints.left),
                            turf.point(splitPoints.right)
                        ).geometry.coordinates;
                        let lightNumSplitMap = {
                            1: ["center"],
                            2: ["left", "right"],
                        };
                        let stopLineAngle = stopLine.angle;
                        // 停止线对应的转向数组 只有属于此数组的才视为合法转向灯
                        let stopLineTurns = stopLine.turntype.replace(",3", "").split(",");
                        // console.log("stopLineTurns", stopLineTurns);
                        // 根据停止线 turntype 筛选合法灯组
                        let newSingleDirTurnLightList = [];
                        for (let i = 0; i < singleDirLight.turnList.length; i++) {
                            if (stopLineTurns.includes(singleDirLight.turnList[i].turn)) {
                                newSingleDirTurnLightList.push(singleDirLight.turnList[i]);
                            }
                        }
                        for (let i = 0; i < newSingleDirTurnLightList.length; i++) {
                            lightResults.push({
                                state: newSingleDirTurnLightList[i].color,
                                remainTime: newSingleDirTurnLightList[i].countDown || `-`,
                                turn: newSingleDirTurnLightList[i].turn,
                                coordinates:
                                    splitPoints[lightNumSplitMap[stopLineTurns.length][i]],
                                ts: `${newSingleDirTurnLightList[i].turn}${newSingleDirTurnLightList[i].color}`,
                                lightAngle: stopLineAngle - 90,
                            });
                        }
                    }
                    // let targetWait = waitGeo.features.find((wait) => {
                    //     return (
                    //         wait.properties.lkid == crossLight.crossId &&
                    //         wait.properties.dirtype == singleDirLight.dir
                    //     );
                    // });
                    // if (targetWait) {
                    //     let currentWaiting = singleDirLight.turnList.find((item) => {
                    //         return item.turn == "20";
                    //     });
                    //     let color = currentWaiting?.color.replace("Flash", "") || "white";
                    //     waitResultFeatures.push(
                    //         turf.polygon(targetWait.geometry.coordinates, { state: color })
                    //     );
                    // }
                }
            }
            let features = [];
            for (let item of lightResults) {
                features.push(turf.point(item.coordinates, item));
            }
            let geo = turf.featureCollection(features);
            mapTools.addOrUpdateLightLayers(map, geo);
            // let waitG = turf.featureCollection(waitResultFeatures);
            // mapTools.addOrUpdateWaitingPolygons(map, waitG);
        },
    },
}