window._AMapSecurityConfig = {
    securityJsCode:"14720ba5bb6ba2553facb5fc6b6777c2",
}
//设备图标
const online = 'https://iot3d-oss.baozhida.cn/UpImage/1681698375d21af1db-3fd2-4032-b7cb-8ee8ac5f6cab.png';
const offline = 'https://iot3d-oss.baozhida.cn/UpImage/168169835869ac506d-f228-46a4-8878-9969b95e6424.png';
const danger = 'https://iot3d-oss.baozhida.cn/UpImage/1681698340c67c3a5a-7cf6-4fbf-be29-7ffae9d31ec1.png';
//设备图标
const online_x = 'https://iot3d-oss.baozhida.cn/UpImage/箱子-绿.png';
const offline_x = 'https://iot3d-oss.baozhida.cn/UpImage/箱子-灰.png';
const danger_x = 'https://iot3d-oss.baozhida.cn/UpImage/箱子-红.png';
//地图标注图标
const start = 'https://iot3d-oss.baozhida.cn/UpImage/16816984598b22098e-272f-48f7-a209-8bdc9fb46744.png';
const pass = 'https://iot3d-oss.baozhida.cn/UpImage/16816984821af72d4e-3be8-46c4-8e58-5351b49b5153.png';
const end = 'https://iot3d-oss.baozhida.cn/UpImage/16816984681ddcd8f0-a60d-455d-b455-42ac83535694.png';

const imageUrlMap = new Map();
imageUrlMap.set(0, offline);
imageUrlMap.set(1, online);
imageUrlMap.set(2, danger);
imageUrlMap.set(3, offline_x);
imageUrlMap.set(4, online_x);
imageUrlMap.set(5, danger_x);


$(window).load(function () {
    InitMap()
});

var trail_map = null
// 高德地图轨迹
function InitMap() {
    if(trail_map != null) return
    console.log("执行了初始化")
    AMapLoader.load({
        key: "51515b72616c71999b6607314e553953",       // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0",                 // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    }).then((AMap)=>{
        trail_map = new AMap.Map("v_trail", {
            resizeEnable: true,
            // center: [ [{center}] ],
            // zoom: [{zoom}],
            features: ['bg', 'road', 'building', 'point'], // 设置地图显示要素（Features）  区域面（bg）  道路（road）  建筑物（building）  标注（point）
        });
        trail_map.setMapStyle("amap://styles/darkblue");
        // getCompany_zhi()
        //单击地图就清除infoWindow
        AMap.Event.addListener(trail_map, 'click', () => {
            trail_map.clearInfoWindow();
        });
        //双击清除所有轨迹
        AMap.Event.addListener(trail_map, 'dblclick', () => {
            console.log('双击了地图，删除轨迹！');
            trail_map.remove(listMarker);
            trail_map.remove(polyLine);
        });
    }).catch((e)=>{
        console.error(e);  //加载错误提示
    });


}
GPS_fruits = new Map()
// 渲染所有点
function f_v_trail() {
    // 创建包含4个节点的折线及文字标注
    var path_gps = [
        // new AMap.LngLat(116.368904,39.913423),
        // new AMap.LngLat(116.398258,39.904600)
    ];
    for (var C_key in C_json.Device.DeviceList) {
        Device_r = C_json.Device.DeviceList[C_key]
        if (Device_r.T_Site.length > 2){
            ps = Device_r.T_Site.split(',');
            path_gps.push(new AMap.LngLat(Number.parseFloat(ps[0]),Number.parseFloat(ps[1])))
        }

    }
    AMap.convertFrom(path_gps, 'gps', (status, result) => {
        console.log("convertFrom:",result)
        if (result.info === 'ok') {
            let i_x = 0;
            for(let i = 0; i < C_json.Device.DeviceList.length; i++) {
                if (C_json.Device.DeviceList[i].T_Site.length > 2) {
                    console.log("GPS_fruits SET",C_json.Device.DeviceList[i].T_Site, result.locations[i_x])
                    GPS_fruits.set(C_json.Device.DeviceList[i].T_Site, result.locations[i_x]);
                    i_x++
                }
            }
            console.log("path_gps",path_gps.length," i_x:",i_x)

            for (var C_key in C_json.Device.DeviceList) {
                Device_r = C_json.Device.DeviceList[C_key]
                if (Device_r.T_Site.length > 2) {
                    AMapaddPoint(Device_r)  // 轨迹加载点
                }
            }
            return;
        }
    });


}

// -------------
const AMapaddPoint = (sensor) => {
    console.log("AMapaddPoint:",sensor)
    if(sensor.T_type < 200){
        return
    }
    let state = sensor.T_monitor;
    if (state == 1){
        if (sensor.T_t > sensor.T_Tupper || sensor.T_rh > sensor.T_RHupper || sensor.T_t < sensor.T_Tlower || sensor.T_rh < sensor.T_RHlower) {
            state = 2;
        }
    }
    if(sensor.T_type == 200 ||sensor.T_type == 210 || sensor.T_type == 220 || sensor.T_type == 230){
        state+=3
    }

    //坐标转换 start
    const convertPosition = async (position) => {
        if(GPS_fruits.has(position)){
            console.log("GPS_fruits",position,GPS_fruits.get(position))
            return GPS_fruits.get(position)
        }
        const ps = position.split(',');
        return new Promise((resolve, reject) => {
            AMap.convertFrom([Number.parseFloat(ps[0]), Number.parseFloat(ps[1])], 'gps', (status, result) => {
                console.log("convertFrom:",result.info)
                if (result.info === 'ok') {
                    GPS_fruits.set(k_, result.locations[0]);
                    resolve(result.locations[0]);
                    return;
                }
            });


        });
    };

    //坐标转换, 添加标记点 start
    convertPosition(sensor.T_Site).then((v) => {
        const marker = mapAddPoint(sensor.T_sn, [v.lng, v.lat], state);
        // console.log("marker:",sensor.T_sn,sensor.T_name, marker)
        addClickShowTrack(sensor.T_sn,sensor.T_name, marker);
        trail_map.add(marker);
        trail_map.setFitView(null, false, [50, 50, 600, 600]);
    });
    //添加坐标en

    //坐标转换 end
};

//坐标转换 end
//添加point start
function mapAddPoint(sn, ps, state)  {
    //@ts-ignore
    const option = {
        icon: new AMap.Icon({
            imageSize: [40, 40],
            image: imageUrlMap.get(state) || offline,
            size: new AMap.Size(40, 40)
        }),
        position: ps
    };
    const marker = new AMap.Marker(option);
    return marker;
};
//添加point end
function addClickShowTrack(sn,T_name, marker)  {
    //@ts-ignore
    AMap.Event.addListener(marker, 'click', () => {
        getDeviceTaskList(sn).then((resp) => {
            const list = resp.Data;
            let content = `
                <div style="font-size: 15px;padding: 10px; border-radius: 6px;background-color: white; position: relative;">
                    <div style="position: absolute;left:50%;bottom: 0;background-color:white;padding: 10px;transform: translate(-50%,50%) rotate(-45deg);"></div>`;
            content += `<p style="text-align: center;margin: 15px;/*! padding: 6px; */border: solid 1px #f00;border-radius: 6px;margin-top: 0px;color: #f00;border-left-width: 0px;border-right-width: 0px;border-top-width: 0px;border-bottom-width: 2px;padding-bottom: 5px;" >`+T_name+`</p>`;
            if (list.length == 0){
                content += `<p style="margin: 15px;padding: 6px;border: solid 1px #eeeeee;border-radius: 6px;" >没有找到任务</p>`;
            }else {
                Array.from(list).forEach(v => {
                    if (v === "0001-01-01 00:00:00"){
                        v = "现在"
                    }
                    content += `<p style="margin: 15px;padding: 6px;border: solid 1px #eeeeee;border-radius: 6px;"    onclick="loadingTrack('${sn}', ['${v.T_Ut_start}','${ v.T_Ut_end}']);">${v.T_Ut_start} ~ ${v.T_Ut_end}</p>`;
                });
            }
            // Array.from(list).forEach(v => {
            //     content += `<p style="margin: 15px;padding: 6px;border: solid 1px #eeeeee;border-radius: 6px;"    onclick="loadingTrack(${sn}, ['${v.T_Ut_start}','${ v.T_Ut_end}']);">${v.T_Ut_start} ~ ${v.T_Ut_end}</p>`;
            // });

            content += '</div>';
            const infoWindow = new AMap.InfoWindow({
                isCustom: true,
                content: content,
                offset: new AMap.Pixel(20, -15)
            });
            const ps = marker.getPosition();
            infoWindow.open(trail_map, [ps.lng, ps.lat]);
            console.log(infoWindow,ps, marker);
        });
    });
};
//# sourceMappingURL=pointHandle.js.map



const listMarker = [];
const listPolyLinePath = [];
let polyLine;
//加载track start
function loadingTrack(sn, timeRange) {
    console.log(sn, "  轨迹显示  ",timeRange);
    //去除其他显示
    if (listMarker.length !== 0)
        trail_map.remove(listMarker);
    if (polyLine !== undefined)
        trail_map.remove(polyLine);
    listPolyLinePath.length = 0;
    listMarker.length = 0;
    console.log('执行到获取数据了')
    getDeviceSensorData(sn, timeRange).then((resp) => {
        const list = resp.Data;
        console.log("响应信息：",list)
        if (list == null || list.length === 0) {
            alert("数据正在上传...！")
            return;
        }
        //去除开始和结束
        Array.from(list.slice(1, list.length - 1)).forEach((v) => {
            const d = trackPoint(v, pass, trail_map);
            console.log("d:",d)
            if(d.lnglat.kT != 0) {
                listMarker.unshift(d.marker);
                listPolyLinePath.unshift(d.lnglat);
            }

        });
        // //去除开始和结束
        // Array.from(list.slice(1, list.length - 1)).forEach((v) => {
        //     const d = trackPoint(v, pass, trail_map);
        //     console.log("d:",d)
        //     if(d.lnglat.kT != 0) {
        //         listMarker.unshift(d.marker);
        //         listPolyLinePath.unshift(d.lnglat);
        //     }
        //
        // });
        //开始和结束
        const endData = trackPoint(list[list.length - 1], end, trail_map);
        const startData = trackPoint(list[0], start, trail_map);
        if(endData.lnglat.kT != 0) {
            listMarker.push(endData.marker);
            listPolyLinePath.push(endData.lnglat);
        }
        if(startData.lnglat.kT != 0) {
            listMarker.unshift(startData.marker);
            // listPolyLinePath.unshift(startData.lnglat);
        }
        trail_map.add(listMarker);
        console.log("listPolyLinePath:",listPolyLinePath)
        //添加轨迹
        polyLine = new AMap.Polyline({
            path: listPolyLinePath,
            borderWeight: 1,
            strokeColor: 'skyblue',
            lineJoin: 'round'
        });
        trail_map.add(polyLine);
    });
    console.log('loadingTrack 执行完了')
};
//加载track end
function trackPoint(v, img, map) {
    const ps = v.T_site.split(',');
    const lnglat = new AMap.LngLat(Number.parseFloat(ps[0]), Number.parseFloat(ps[1]));


    const option = {
        icon: new AMap.Icon({
            imageSize: [40, 40],
            image: img,
            size: [40, 40],
        }),
        position: lnglat,
        offset: new AMap.Pixel(-20, -30),
    };
    const marker = new AMap.Marker(option);
    //@ts-ignore
    AMap.Event.addListener(marker, 'click', () => {
        const infoWindow = new AMap.InfoWindow({
            isCustom: true,
            content: getDeviceSensorDataInfo(v),
            offset: new AMap.Pixel(-3, -55),
        });
        infoWindow.open(map, [lnglat.lng, lnglat.lat]);
    });
    return {marker: marker, lnglat: lnglat};
};
function getDeviceSensorDataInfo(v) {
    let content = `
                <div style="font-size: 15px;padding: 10px; border-radius: 6px;background-color: white; position: relative;">
                    <div style="position: absolute;left:50%;bottom: 0;background-color:white;padding: 10px;transform: translate(-50%,50%) rotate(-45deg);"></div>`;
    return content+`
                        <div class="border rounded shadow bg-white p-2 text-dark">
                            <p class="m-1">设备名称：${v.T_name}  </p>
                            <p class="m-1">当前温度：${v.T_t} <span class="m-1"></span> 当前湿度： ${v.T_rh}</p>
                            <p class="m-1">温度上下限：${v.T_Tlower} ~ ${v.T_Tupper} <span class="m-1"></span> 湿度上下限：${v.T_RHlower} ~ ${v.T_RHupper}</p>
                            <p class="m-1">记录时间：${v.T_time}</p>
                        </div>
                   </div>
    `;
};
//# sourceMappingURL=tarckHandle.js.map

//获取设备任务列表
function getDeviceTaskList (sn){
    return new Promise((resolve, reject) => {
        $.ajax({
            async:false,
            method:"POST",
            url: "./DeviceTask_List",
            data: {
                T_sn: sn,
            },
            success: function (rlt) {
                console.log(rlt)
                resolve(rlt)
            }
        })
    })
}

//获取设备探头数据
function getDeviceSensorData(sn,timeRanges) {
    return new Promise((resolve, reject)=>{
        $.ajax(({
            async:false,
            method: "POST",
            url: "./DeviceData_List",
            data:{
                Time_start: timeRanges[0],
                Time_end: timeRanges[1],
                T_sn: sn,
            },
            success: function (rlt){
                console.log(rlt)
                resolve(rlt)
            }
        }))
    })
}
