import { containsCoordinate } from 'ol/extent';
import { OLMap } from "@/assets/map/OLMap";
import '@/assets/map/popup.css'
import { gradientColors, markerZoomSize, labelZoomSize, colorRGBtoHex, jqAjax } from "@/assets/map/maptool";
import $ from "@/assets/map/jquery.min";

OLMap.prototype.eventViewChange = function (func) { //根据地图缩放级别控制popup弹窗的显隐
    var view = this.map.getView();
    var map = this.map;
    view.on('change:resolution', function (event) {
        let z = view.getZoom();
        let r = view.getResolution();
        var region = view.calculateExtent(map.getSize());
        //console.log('extent: '+region);
        var overlays = map.getOverlays().getArray();
        var popups = []; //记录popup
        //查找marker和label
        for (var k in overlays) {
            let oid = overlays[k].getId();
            if (oid.indexOf('marker') >= 0) {
                let ediv = overlays[k].get('element');
                let params = JSON.parse(ediv.getAttribute("desc"));
                let level = params.level;
                if (level == 1) {
                    if (z < 5.3) {
                        var wh = markerZoomSize(5, z);
                        ediv.style.setProperty('width', wh + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    } else if (z >= 5.3 && z < 6.3) {
                        var wh = markerZoomSize(4, z);
                        ediv.style.setProperty('width', wh + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    } else {
                        var wh = markerZoomSize(3, z);
                        ediv.style.setProperty('width', (wh * 1.5) + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    }
                }
                if (level == 2) {
                    if (z < 7.2) {
                        var wh = markerZoomSize(6, z);
                        ediv.style.setProperty('width', wh + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    } else if (z >= 7.2 && z < 7.6) {
                        var wh = markerZoomSize(5, z);
                        ediv.style.setProperty('width', wh + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    } else if (z >= 7.6 && z < 8) {
                        var wh = markerZoomSize(4, z);
                        ediv.style.setProperty('width', wh + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    } else {
                        var wh = markerZoomSize(3, z);
                        ediv.style.setProperty('width', (wh * 1.5) + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    }
                }
                if (level == 3) {
                    if (z < 8.5) {
                        var wh = markerZoomSize(7, z);
                        ediv.style.setProperty('width', wh + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    } else if (z >= 8.5 && z < 9) {
                        var wh = markerZoomSize(5, z);
                        ediv.style.setProperty('width', wh + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    } else {
                        var wh = markerZoomSize(3, z);
                        ediv.style.setProperty('width', (wh * 1.5) + 'px');
                        ediv.style.setProperty('height', wh + 'px');
                    }
                }
            }
            if (oid.indexOf("label") >= 0) {
                // 重新设置标注的尺寸
                let ea = overlays[k].get('element');
                let params = JSON.parse(ea.getAttribute("desc"));
                let level = params.level;
                if (level == 1) {
                    var fz = labelZoomSize(6.3, z);
                    if (z >= 6.3) {
                        fz = fz > 8 ? fz : 8;
                    }
                    ea.style.setProperty('font-size', fz + "px");
                }
                if (level == 2) {
                    var fz = labelZoomSize(8, z);
                    if (z >= 8) {
                        fz = fz > 8 ? fz : 8;
                    }
                    ea.style.setProperty('font-size', fz + "px");
                }
                if (level == 3) {
                    var fz = labelZoomSize(9, z);
                    if (z >= 9) {
                        fz = fz > 8 ? fz : 8;
                    }
                    ea.style.setProperty('font-size', fz + "px");
                }
            }
            //console.log("zoom: "+z+", "+event.target.get(event.key));
            // 记录位于当前视图的popup
            if (oid.indexOf("popup") >= 0) {
                let ep = overlays[k].get('element');
                let pos = ep.getElementsByTagName('input')[0].value;
                pos = pos.split(',');
                let pt = [parseFloat(pos[0]), parseFloat(pos[1])];
                //console.log('pos'+"_"+pt);
                if (containsCoordinate(region, pt)) {
                    popups.push(overlays[k]);
                }
            }

        }
        //获取当前视图下的Overlay要素
        //console.log('zoom: '+z+'_'+popups.length)
        if (popups.length <= 8) {
            for (var p in popups) {
                if (popups[p].getPosition() != undefined) {
                    continue;
                }
                let ep = popups[p].get('element');
                let pos = ep.getElementsByTagName('input')[0].value;
                pos = pos.split(',');
                let pt = [parseFloat(pos[0]), parseFloat(pos[1])];
                //popups[p].setPosition(pt);  //设置为当前站点位置
                let id=popups[p].getId().split("popup_")[1];
                func(id,popups[p],pt);
            }
        }
    });
    view.on('change:center', function (event) {
        let z = view.getZoom();
        let r = view.getResolution();
        var region = view.calculateExtent(map.getSize());
        //console.log('chang-extent: '+region);
        var overlays = map.getOverlays().getArray();
        var popups = []; //记录popup
        for (var k in overlays) {
            let oid = overlays[k].getId();
            // 记录位于当前视图的popup
            if (oid.indexOf("popup") >= 0) {
                let ep = overlays[k].get('element');
                let pos = ep.getElementsByTagName('input')[0].value;
                pos = pos.split(',');
                let pt = [parseFloat(pos[0]), parseFloat(pos[1])];
                //console.log('pos'+"_"+pt);
                if (containsCoordinate(region, pt)) {
                    popups.push(overlays[k]);
                }
            }

        }
        //获取当前视图下的Overlay要素
        //console.log('zoom: '+z.toFixed(1)+'_popups: '+popups.length)
        if (popups.length <= 8) {
            for (var p in popups) {
                if (popups[p].getPosition() != undefined) {
                    continue;
                }
                let ep = popups[p].get('element');
                let pos = ep.getElementsByTagName('input')[0].value;
                pos = pos.split(',');
                let pt = [parseFloat(pos[0]), parseFloat(pos[1])];
                //popups[p].setPosition(pt);  //设置为当前站点位置
                let id=popups[p].getId().split("popup_")[1];
                func(id,popups[p],pt);
            }
        }

    });
}

OLMap.prototype.eventOverlayClose = function () {//关闭所有弹窗
    this.map.on('click', function (evt) {
        //console.log("事件源："+evt.target.tagName+", 类型："+evt.type+"，是否冒泡事件："+evt.bubbles);
        //去除所有Popup
        var overlays = this.getOverlays().getArray();
        //console.log(overlays.length);
        for (var k in overlays) {
            let oid = overlays[k].getId();
            if (oid.indexOf('marker') >= 0) {
                let e = overlays[k].get('element');
                let c = e.style['background-color'];
                c = colorRGBtoHex(c);
                //console.log('c='+c);
                e.style.setProperty('border', '1px solid' + c);
            }
            if (oid.indexOf("popup") >= 0) {
                overlays[k].setPosition(undefined); //隐藏所有POPUP
            }
        }
    });
}

export function updatePopupTitle(map, switch_flag) {
    var types = ['popup']
    var layers = map.getOverlays().getArray();
    for (let i = 0; i < layers.length; i++) {
        const layer = layers[i];
        let oid = layer.getId();
        let ediv = layer.get('element');
        let params = JSON.parse(ediv.getAttribute("desc"));
        let id = params.id;
        let name = params.name;
        for (let i in types) {
            if (oid.indexOf(types[i]) >= 0) {
                //更改popup的标题
                let x = $(ediv).find("#flag_switch");
                let sname = switch_flag ? strOmit(name, 8) : id; //显示站名、站号
                x.html(sname);
            }
        }
    }
}

export function rmOverlaysByLevel(map, levels = [3], types = ['marker', 'label', 'popup']) {//清除指定Level的Marker和Popup
    var layers = map.getOverlays().getArray();
    //console.log('删除前图层数: '+layers.length);
    var overlays = []
    for (let i = 0; i < layers.length; i++) {
        const layer = layers[i];
        let oid = layer.getId();
        let ediv = layer.get('element');
        let params = JSON.parse(ediv.getAttribute("desc"));
        let level = params.level;
        for (let i in types) {
            for (let j in levels) {
                if (oid.indexOf(types[i]) >= 0 && level == levels[j]) {
                    overlays.push(layer);
                }
            }
        }
    }
    for (let i in overlays) {
        map.removeOverlay(overlays[i]);
    }
    //layers = map.getOverlays().getArray();
    //console.log('删除后图层数: '+layers.length);
}

export function hiddenOverlaysByLevel(map, hidden = true, levels = [3], types = ['marker', 'label', 'popup']) {//关闭指定Level的Marker和Popup
    var layers = map.getOverlays().getArray();
    var overlays = []
    for (let i = 0; i < layers.length; i++) {
        const layer = layers[i];
        let oid = layer.getId();
        let ediv = layer.get('element');
        let params = JSON.parse(ediv.getAttribute("desc"));
        let level = params.level;
        for (let i in types) {
            for (let j in levels) {
                if (oid.indexOf(types[i]) >= 0 && level == levels[j]) {
                    if (hidden) {
                        ediv.classList.add("hidden");
                    } else {
                        ediv.classList.remove("hidden");
                    }
                }
            }
        }
    }
}
export function updateMarkerAndLabel(map, data, dataFactor) {
    if (String(data.msg).toLowerCase() == "ok") {
        //获取数据列表
        var feas = data.datas.list;
        var statis = null;
        //console.log("气象因子: "+dataFactor);
        switch (dataFactor) {
            case 'wd':
                statis = data.global_air_temp;
                break;
            case 'qy':
                statis = data.global_apressure;
                break;
            default:
                statis = data.global_air_temp;
        }
        if (statis == null) {
            throw ("统计参数为空！");
        }
        var max = parseFloat(statis.max) + 1; //防止色带数溢出，最大值需加1
        var min = parseFloat(statis.min) - 1; //防止色带数溢出，最小值需减1
        var color = gradientColors("#0000FF", "#FF0000", parseInt(max - min));
        //console.log("要素长度：" + feas.length);

        //查找markers和labels
        var overlays = map.getOverlays().getArray();
        //查找markers
        for (var k in overlays) {
            let oid = overlays[k].getId();
            for (var i = 0; i < feas.length; i++) {
                var fea = feas[i];
                var fid = fea.id;
                var fname = fea.name;
                var wd = '温度'
                var sd = '湿度';
                var qy = '气压';
                var fx = '风向';
                var yun = '云量';
                var yl = '雨量';
                var fs = '风速';
                var jd = '能见度';
                var tq = '天气';
                var time = null;
                var label = '';
                var cv = 0;
                var fd = null;
                switch (dataFactor) {
                    case 'wd':
                        fd = fea.AIR_TEMP; //fd: feature data
                        time = fd.time.slice(-8, -3); //截取“时:分”
                        wd = parseFloat(fd.value).toFixed(1);
                        label = wd + "°C";
                        cv = wd;
                        break;
                    case 'qy':
                        fd = fea.APRESSURE;
                        time = fd.time.slice(-8, -3); //截取“时:分”
                        qy = parseFloat(fd.value).toFixed(0);
                        label = qy + "kPa";
                        cv = qy;
                        break;
                    default:
                        fd = fea.AIR_TEMP;
                        time = fd.time.slice(-8, -3); //截取“时:分”
                        wd = parseFloat(fd.value).toFixed(1);
                        label = wd + "°C";
                        cv = wd;
                }
                // 符号化
                //cv = cv > max ? max : cv;
                //cv = cv < min ? min : cv;
                var color_idx = Math.floor((cv - min), 0);
                var fcolor = color[color_idx];
                //console.log("Color: "+fcolor+", "+color_idx+", "+cv);
                //更新marker样式
                if (oid.split('marker_')[1] == fid) {
                    let ediv = overlays[k].get('element');
                    ediv.style.setProperty('background-color', fcolor);
                    ediv.style.setProperty('border', '1px solid' + fcolor);
                }
                //更新label文本
                if (oid.split('label_')[1] == fid) {
                    let ediv = overlays[k].get('element');
                    ediv.innerHTML = label; //设置文本
                }
            }
        }
    }
}

export function getSiteStatus(map) {
    var overlays = map.getOverlays().getArray();
    //查找markers
    var nTotal = 0;
    var nNormal = 0;
    var nAbnormal = 0;
    var nCease = 0;
    var nOther = 0;
    for (var k in overlays) {
        let oid = overlays[k].getId();
        if (oid.indexOf('marker') >= 0) {
            let ediv = overlays[k].get('element');
            let sdesc = ediv.getAttribute("desc");
            let params = JSON.parse(sdesc);
            let status = params.status;
            switch (status) {
                case "正常": nNormal++; break;
                case "故障": nAbnormal++; break;
                case "停用": nCease++; break;
                default: nOther++;
            }
            nTotal++;
        }
    }
    return { total: nTotal, normal: nNormal, abnormal: nAbnormal, cease: nCease, other: nOther };
}

export function getTableStyle(flag) {
    var styleList = [["正常", "popup_normal_border", "popup_normal_tdborder", "popup_normal_bg", "popup_normal_triangle"],
    ["故障", "popup_abnormal_border", "popup_abnormal_tdborder", "popup_abnormal_bg", "popup_abnormal_triangle"],
    ["停用", "popup_cease_border", "popup_cease_tdborder", "popup_cease_bg", "popup_cease_triangle"],
    ["未知", "popup_unknown_border", "popup_unknown_tdborder", "popup_unknown_bg", "popup_unknown_triangle"]];
    var arr;
    for (var i in styleList) {
        arr = styleList[i];
        if (arr[0] == flag) {
            return arr.slice(1, 5);
        }
    }
    return arr.slice(1, 5);
}

export function getALLMarkersId(map) {
    var overlays = map.getOverlays().getArray();
    var ids = [];
    for (var k in overlays) {
        let oid = overlays[k].getId();
        if (oid.indexOf('marker') >= 0) {
            ids.push(oid.split('marker_')[1]);
        }
    }
    return ids;
}

function strOmit(str, N = 8) { //字符串截留，超过长度n的字符串将被截断
    var n = str.length; //字的长度
    if (n > N) {
        return str.slice(0, N);
    }
    return str;
}

function showPopup(id, popup, cpoint) {
    //获取弹窗中的表格元素
    let div = popup.getElement();
    let trs = $(div).find("table tr");
    let tr1 = $(trs[1]).find("td");
    let tr2 = $(trs[2]).find("td");
    let tr3 = $(trs[3]).find("td");

    //向后台发送id，查询九宫格数据
    let url = 'http://debug.api.9poc.com/map/zhandian';
    let p = {
        "ID": id,
        "TOKEN": "SW6Q7Q74YX2V97JZSW6Q7Q74YX2V97JZ"
    }
    let params = {
        ACT: "GIRD9_DATA",
        PARAMETERS: JSON.stringify(p),
    }
    jqAjax(url, params, 'POST', function (data) {
        if(data.code==0){
            let grid = data.msg.grid;
            let wd = grid[0].value + "°C";;
            let sd = grid[1].value + grid[1].unit;
            let qy = grid[2].value + "kPa";
            let fx = grid[3].value + grid[3].unit;
            let yun = grid[4].value + grid[4].unit;
            let yl = grid[5].value + grid[5].unit;
            let fs = grid[6].value + grid[6].unit;
            let jd = grid[7].value + grid[7].unit;
            let tq = grid[8].value;
            let time = null;
            //向九宫格中赋新值
            tr1[0].innerHTML = wd;
            tr1[1].innerHTML = sd;
            tr1[2].innerHTML = qy;
            tr2[0].innerHTML = fx;
            tr2[1].innerHTML = yun;
            tr2[2].innerHTML = yl;
            tr3[0].innerHTML = fs;
            tr3[1].innerHTML = jd;
            tr3[2].innerHTML = tq;
        }
        popup.setPosition(cpoint);  //设置为当前站点位置
        
    });
}

export function load_data(mapDiv, data, dataFactor, sitelevel, switch_flag, leftClick, rightClick) {
    if (String(data.msg).toLowerCase() == "ok") {
        var feas = data.datas.list;
        var statis = null;
        //console.log("气象因子: "+dataFactor);
        switch (dataFactor) {
            case 'wd':
                statis = data.global_air_temp;
                break;
            case 'qy':
                statis = data.global_apressure;
                break;
            default:
                statis = data.global_air_temp;
        }
        if (statis == null) {
            throw ("统计参数为空！");
        }
        var max = parseFloat(statis.max) + 1; //防止色带数溢出，最大值需加1
        var min = parseFloat(statis.min) - 1; //防止色带数溢出，最小值需减1
        var color = gradientColors("#0000FF", "#FF0000", parseInt(max - min));
        //console.log("要素长度：" + feas.length);
        //添加点位
        for (var i = 0; i < feas.length; i++) {
            var fea = feas[i];
            var fid = fea.id;
            var fname = fea.name;
            var lon = fea.longitude;
            var lat = fea.latitude;
            var zt = fea.status.text; //站点状态码：正常、故障、停用、未知
            var style = getTableStyle(zt);
            var sname = switch_flag ? strOmit(fname, 8) : fid; //显示站名、站号
            var stitle = "站名：" + fname + "，站号：" + fid
            var params = { level: sitelevel, status: zt, name: fname, id: fid };

            var wd = '温度'
            var sd = '湿度';
            var qy = '气压';
            var fx = '风向';
            var yun = '云量';
            var yl = '雨量';
            var fs = '风速';
            var jd = '能见度';
            var tq = '天气';
            var time = null;
            var label = '';
            var cv = 0;
            var fd = null;
            switch (dataFactor) {
                case 'wd':
                    fd = fea.AIR_TEMP; //fd: feature data
                    time = fd.time.slice(-8, -3); //截取“时:分”
                    wd = parseFloat(fd.value).toFixed(1);
                    label = wd + "°C";
                    cv = wd;
                    break;
                case 'qy':
                    fd = fea.APRESSURE;
                    time = fd.time.slice(-8, -3); //截取“时:分”
                    qy = parseFloat(fd.value).toFixed(0);
                    label = qy + "kPa";
                    cv = qy;
                    break;
                default:
                    fd = fea.AIR_TEMP;
                    time = fd.time.slice(-8, -3); //截取“时:分”
                    wd = parseFloat(fd.value).toFixed(1);
                    label = wd + "°C";
                    cv = wd;
            }

            //这里使用模板字符串便于将DOM转换为JS对象
            let styleh = 'popup';
            let style0 = style[0];
            let style1 = style[1];
            let style2 = style[2];
            let style3 = style[3];
            let div = `<div class='${styleh}'>`;
            let table = `<table class='${style0}' title='鼠标【左/右键】点击九宫格查看【详细信息/快捷菜单】'>`
                + `<tr class='${style2}' style='color:#FFF' title='点击[x]或弹窗外任意区域关闭弹窗'>`
                + `<td colspan=2><span id='flag_switch' style='margin-left:18px; font-size:12px; font-weight:bold' title='${stitle}'>${sname}</span></td>`
                + `<td style='text-align:center; font-size:12px'>${time}</td>`
                + `</tr>`
                + `<tr>`
                + `<td class='${style1}'>${wd}</td>`
                + `<td class='${style1}'>${sd}</td>`
                + `<td class='${style1}'>${qy}</td>`
                + `</tr>`
                + `<tr>`
                + `<td class='${style1}'>${fx}</td>`
                + `<td class='${style1}'>${yun}</td>`
                + `<td class='${style1}'>${yl}</td>`
                + `</tr>`
                + `<tr>`
                + `<td class='${style1}'>${fs}</td>`
                + `<td class='${style1}'>${jd}</td>`
                + `<td class='${style1}'>${tq}</td>`
                + `</tr>`
                + `</table>`;
            let info = div + table + `<div class='${style3}'></div></div>`;
            /*
            //将模板字符串DOM转为JS对象
            let t = document.createElement('template');
            t.innerHTML=info;
            let _div=t.content.firstElementChild;
            let _tab=_div.firstElementChild;
            console.log("NodeName: "+_tab.nodeName);
            */

            document.oncontextmenu = function (e) {
                //去掉默认的contextmenu事件，否则会和右键事件同时出现。
                e.preventDefault();
            };

            // 符号化
            //cv = cv > max ? max : cv;
            //cv = cv < min ? min : cv;
            var color_idx = Math.floor((cv - min), 0);
            //console.log(cv, max, min);
            //console.log(sname+"_"+color_idx+"_"+color[color_idx]+"_"+min+"_"+max);
            //点位去重检查
            let m = mapDiv.markerIsExist([lon, lat]);
            //let m = mapDiv.markerIsExistById(fid);
            //console.log("站点是否存在："+fid+", "+m);
            if (!m) {
                mapDiv.addPopup([lon, lat], 0, fid, info, leftClick, rightClick, params);  //添加POPUP弹窗
                if (sitelevel != 3) {
                    mapDiv.addMarkerAndLabel([lon, lat], fid, label, color[color_idx], 0.8,
                        params, { width: '8px', height: '8px' }, showPopup); //添加marker和label
                } else {
                    mapDiv.addMarkerAndLabel([lon, lat], fid, label, color[color_idx], 0.8,
                        params, { width: '12px', height: '12px' }, showPopup); //添加marker和label
                }
            }
        }
        mapDiv.eventOverlayClose();
        mapDiv.eventViewChange(showPopup);
    } else {
        throw ("加载数据失败，数据标识:" + data.msg);
    }
}

