$(function () {

    /*变量、对象 定义*/
    var on_off = true;          //用于重新定位筛选开关
    var cityString = new Object();
    var page = 1;


    /*
    * 一、以下为地图页面的功能;
    * 1、地图默认进来的时候,获取所有城市以AJAX请求数据,返回所在城市的主推楼盘信息,把返回的数据在地图上显示并在列表中显示所返回楼盘信息;
    * 2、点击筛选条件时,把条件存储在对象 dataAjax 对象中并提交,返回的数据遍历在地图上与列表中,筛选的条件内容在条件列表中显示;
    * 3、在条件列表中,每删除一个条件都会重新请求一个数据,列表中显示的条件都为再次请求的条件;
    * 4、每删除一个条件时,都会在存储对象中删除对应的属性与值;
    * 5、输入检索时,去除所有的空格与HMTL标签;
    *
    */

    // 设置地图展示框的高度
    var _h = $(window).height();
    $('.max_box').css('height', _h);   //最外层盒子高度
    $('#allmap').css('height', _h);    //地图高度
    $('.m_qhcs_box').css('height', _h);  //区域选择盒子高度


    // 选择请选择查看区域 选择
    // $('.m_City_ul_li').on('touchstart', 'div.m_City_province', function () {
    //     on_off = true;    //开启重新定位
    //     var _this = $(this);
    //     var txt = _this.text();
    //     var city_id = _this.attr('data-id');
    //     FnAera(city_id);    //区域请求数据

    //     page = 1;

    //     $('.batch').fadeOut();    //不喜欢按钮隐藏


    //     $('.map_aera a').html(txt);
    //     $('.m_qhcs_box').animate({top: "-" + _h + "px"});
    //     $('.m_qhcs_box').fadeOut();
    // })
    (function (){
        on_off = true;    //开启重新定位
        var txt = '海南';
        var city_id = 68;
        FnAera(city_id);    //区域请求数据

        page = 1;

        $('.batch').fadeOut();    //不喜欢按钮隐藏


        $('.map_aera a').html(txt);
        $('.m_qhcs_box').animate({top: "-" + _h + "px"});
        $('.m_qhcs_box').fadeOut();
        })();
   


    // 选择区域
    $('.map_aera').on('touchstart', function () {
        $('.m_qhcs_box').fadeIn();
        $('.m_qhcs_box').animate({top: "0px"});

        $('.batch').fadeOut();    //不喜欢按钮隐藏
    })


    // 展示区域数据请求
    function FnAera(cityN) {
        $.ajax({
            url: "/json/getcity",
            type: "post",
            data: {city: cityN, csrf_token_m: csrfToken},
            dataType: "json",
            success: function (data) {
                remove_overlay();     // 清除地图上所有的覆盖物   每切换一次都要消除
                if (data.code == 200) {
                    $.each(data.data, function (k, v) {
                        labelFu(v);
                    })
                }
            },
            error: function (request) {
                console.log('加载失败!');
            }
        })
    }


    // 不喜欢换一批
    $('.batch').on('touchstart', function () {
        ++page;

        if (cityString.hasOwnProperty('page')) {
            page = cityString.page;
            delete cityString.page;
        }

        $('.max_box').append('<div class="load"><img src="/overseas/map/image/loading1.gif" alt="" /></div>')

        var prov = cityString.city;
        fuAjaxLabel(prov, page);    //  请求当前城市的数据
    })


    /*------------------以上为页面功能   *   以下为地图功能----------------------*/

    /*
    * 二、以下为地图展示模块
    *   1、创建地图实例,设置默认位置、城市;
    *   2、进入地图时,浏览器获取当前城市,并发出请求;
    *   3、自定义显示标签;
    *   4、根据返回数据的经纬度,以自定义标签把楼盘信息显示在地图上;
    *   5、给地图上每个标签绑定对应楼盘首页地址,点击时跳转楼盘首页;
    *   6、
    *
    */

    /*默认初起化数据*/
    var currentLocation, cityName, map, point;
    var cityObject = {cityName: '海口', cityPoint: {lng: '110.300805', lat: '20.003838'}}   //默认初始化位置


    // 创建地图
    map = new BMap.Map("allmap");    // 创建Map实例
    point = new BMap.Point(cityObject.cityPoint.lng, cityObject.cityPoint.lat);
    map.centerAndZoom(point, 8);  // 初始化地图,设置中心点坐标和地图级别
    map.setCurrentCity(cityObject.cityName);          // 设置地图显示的城市 此项是必须设置的
    map.enableScrollWheelZoom(true);     //开启鼠标滚轮缩放

    var geoc = new BMap.Geocoder();

    //添加缩放控件,anchor默认定位 offset 设置偏移值
    var top_left_navigation = new BMap.NavigationControl({
        anchor: BMAP_ANCHOR_BOTTOM_RIGHT,
        offset: new BMap.Size(10, 50)
    });  //左上角,添加默认缩放平移控件
    map.addControl(top_left_navigation);


    // 省、市、县覆盖物
    function labelFu(data) {
        var datacenter = data;                          //数据重新赋值
        var text = datacenter.name;                     //获取城市
        // var pid = datacenter.id;                     //省份iD
        var count = datacenter.number;                   //获取城市楼盘数量
        var point = newPoint(datacenter.point);
        var _points = new BMap.Point(point[0], point[1]);    //经纬度处理

        if (on_off) {
            map.centerAndZoom(_points, 8);    //重新定位
            on_off = false;           //开关,每次检索或筛选要重新定位第一个楼盘位置;
        }

        // 复杂的自定义覆盖物
        /*添加图标*/
        function ComplexCustomOverlays(point) {
            this._point = point;
        }

        ComplexCustomOverlays.prototype = new BMap.Overlay();
        ComplexCustomOverlays.prototype.initialize = function (map) {
            this._map = map;
            var div = this._div = document.createElement("div");
            div.style.position = "absolute";
            div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);//聚合功能?
            div.style.height = "45px";
            div.style.width = "45px";
            div.style.cursor = "pointer";
            div.style.zIndex = 0;
            // div.setAttribute("pointX", this._point.lng);
            // div.setAttribute("pointY", this._point.lat);
            // div.setAttribute("pid", pid);
            // console.log(rank);

            var arrow = this._arrow = document.createElement("p");
            arrow.style.background = "url(/overseas/map/image/yuan1.png) no-repeat 0px 0px/62px 117px";
            arrow.style.backgroundPosition = "8px -54px";
            arrow.style.width = "70px";
            arrow.style.height = "55px";
            arrow.style.lineHeight = "20px";
            arrow.style.marginTop = "-8px";
            arrow.style.textAlign = "center";
            arrow.style.top = "30px";
            arrow.style.padding = "10px 0";
            arrow.style.left = "68px";
            arrow.style.color = "#FFF";
            arrow.style.fontSize = "0.75rem";
            // arrow.innerHTML = text;

            var _ew = this.arow = document.createElement("em");
            _ew.innerHTML = text;

            var _arow = this.arow = document.createElement("span");
            _arow.style.display = " block";
            _arow.innerHTML = count;

            arrow.appendChild(_ew);
            div.appendChild(arrow);
            arrow.appendChild(_arow);

            div.onmouseover = function () {
                arrow.style.background = "url(/overseas/map/image/yuan1.png) no-repeat center/62px 117px";
                arrow.style.backgroundPosition = "8px 1px";
                this.style.zIndex = 99990;
            }

            div.onmouseout = function () {
                arrow.style.background = "url(/overseas/map/image/yuan1.png) no-repeat center/62px 117px";
                arrow.style.backgroundPosition = "8px -54px";
                this.style.zIndex = 0;
            }

            /*
             *    给覆盖物添加点击事件
             */
            div.addEventListener("touchstart", function () {
                var province = $(this).find('em').text();
                on_off = true;      //开启重新定位

                cityString.city = province;

                $('.batch').fadeIn();       //不喜欢按钮显示

                fuAjaxLabel(province, page);    //  请求当前城市的数据

            });

            map.getPanes().labelPane.appendChild(div);     //getPanes(),返回值:MapPane,返回地图覆盖物容器列表  labelPane呢???

            return div;

        }

        ComplexCustomOverlays.prototype.draw = function () {
            var map = this._map;
            var pixel = map.pointToOverlayPixel(this._point);
            this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
            this._div.style.top = pixel.y - 30 + "px";
        }

        var myCompOverlay = new ComplexCustomOverlays(_points);     //添加覆盖物的经纬度
        map.addOverlay(myCompOverlay);                              //将标注添加到地图中

    }

    //点击城市获取楼盘数据展示
    function fuAjaxLabel(cityName, page) {
        $.ajax({
            url: "/json/houselist",
            type: "post",
            data: {city: cityName, page: page, csrf_token_m: csrfToken},
            dataType: "json",
            success: function (data) {
                setTimeout(function () {
                    $('.load').remove();
                }, 300);
                setTimeout(function () {
                    if (data.code == 200) {
                        remove_overlay();     // 清除地图上所有的覆盖物 请求成功

                        /*返回区域主推楼盘先*/
                        $.each(data.data.data, function (k, v) {
                            addCover(v);        //添加覆盖物的方法
                        })
                        if (data.data.data.length < 20) {
                            cityString.page = 1;
                        }
                    } else if (data.code == 300) {
                        cityString.page = 1;
                    }
                }, 350);
            },
            error: function (request) {
                console.log('加载失败!');
            }
        })
    }

    /*市县楼盘展示*/
    function addCover(objData) {
        // console.log(objData)
        var pic = objData.price;
        var _pic = (pic != '0' && pic != null && pic != '' && pic != 'null') ? objData.price : "待定";

        var txt = objData.name, mouseoverTxt = "";
        var information = objData;
        var coordinate = newPoint(objData.longitude_latitude); //  转换经纬度

        // console.log(coordinate)
        var _point = new BMap.Point(coordinate[0], coordinate[1]);
        var myCompOverlay = new ComplexCustomOverlay(_point, txt, mouseoverTxt, information);
        map.addOverlay(myCompOverlay);

        if (on_off) {
            map.centerAndZoom(_point, 11);    //重新定位
            on_off = false;           //开关,每次检索或筛选要重新定位第一个楼盘位置;
        }
    }


    // 复杂的自定义覆盖物
    function ComplexCustomOverlay(point, text, mouseoverText, information) {
        this._point = point;
        this._text = text;
        this._overText = mouseoverText;
        this.information = information;
        // console.log(this.information.id)
    }

    ComplexCustomOverlay.prototype = new BMap.Overlay();
    ComplexCustomOverlay.prototype.initialize = function (map) {

        this._map = map;
        var div = this._div = document.createElement("div");
        div.style.position = "absolute";
        div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
        div.style.backgroundColor = "#33C0D0";
        div.style.border = "1px solid #33C0D0";
        div.style.color = "white";
        // div.style.height = "18px";
        div.style.padding = "5px 15px";
        div.style.lineHeight = "18px";
        div.style.whiteSpace = "nowrap";
        div.style.MozUserSelect = "none";
        div.style.fontSize = "12px";
        div.setAttribute("class", "shadow");
        div.setAttribute("pid", this.information.id);     //存储ID
        var span = this._span = document.createElement("span");
        div.appendChild(span);
        span.appendChild(document.createTextNode(this._text));
        var that = this;

        var arrow = this._arrow = document.createElement("div");
        arrow.style.background = "url(/overseas/map/image/label.png) no-repeat";
        arrow.style.position = "absolute";
        arrow.style.width = "11px";
        arrow.style.height = "10px";
        arrow.style.top = "28px";
        arrow.style.left = "10px";
        arrow.style.backgroundPosition = "0 -19px";
        arrow.style.overflow = "hidden";
        div.appendChild(arrow);

        /*手机端页面添加 点击事件*/
        div.addEventListener("touchstart", function () {
            var hid = $(this).attr('pid');
            FnInfo(hid);     //传楼盘ID;
            // console.log(hid)
        });

        div.onmouseover = function () {
            this.style.backgroundColor = "#6BADCA";
            this.style.borderColor = "#0000ff";
            this.getElementsByTagName("span")[0].innerHTML = that._text;
            arrow.style.backgroundPosition = "0px -20px";
        }

        div.onmouseout = function () {
            this.style.backgroundColor = "#EE5D5B";
            this.style.borderColor = "#BC3B3A";
            this.getElementsByTagName("span")[0].innerHTML = that._text;
            arrow.style.backgroundPosition = "0px 0px";
        }

        map.getPanes().labelPane.appendChild(div);

        return div;
    }

    ComplexCustomOverlay.prototype.draw = function () {
        var map = this._map;
        var pixel = map.pointToOverlayPixel(this._point);
        this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
        this._div.style.top = pixel.y - 30 + "px";
    }


    // 弹窗
    function FnInfo(id) {
        $.ajax({
            url: "/json/details",
            type: "get",
            data: {hid: id},
            dataType: "json",
            success: function (data) {
                var v = data.data;
                if (data.code == 200) {

                    // 修改数据
                    var price = '<span style="font-size:1rem;color:red;">待定</span>'
                    if (v.sale_price != 0 && v.sale_price != "" && v.sale_price != null) {
                        price = '价格:<span><em>' + v.sale_price + '</em><i>' + v.price_unit + '</i></span>';
                    }
                    var main_units = (v.main_units != '') ? v.main_units : '<span style="color:#999;">暂无信息</span>';

                    $('.w_info_box').find('.w_house_img img').attr('src', v.thumb);
                    $('.w_info_box').find('.w_house_img > a').attr('href', '/house/' + v.id + '');
                    $('.w_info_box').find('.w_house_img a > span').html(v.city_name);
                    $('.w_info_box').find('.w_title').html('<span>' + v.name + '</span>');
                    $('.w_info_box').find('.w_map_hu i').html(main_units);
                    $('.w_info_box').find('.w_price').html(price);
                    var _li = ""
                    $.each(v.characteristic, function (k, j) {
                        _li += '<i>' + j + '</i>'
                    })
                    $('.w_info_box').find('.w_feature').html(_li);

                    // 特效
                    $('.w_info_box').fadeIn();
                    $('.w_info_box').animate({top: '20%'});
                    $('.cover').fadeIn();
                }
            },
            error: function (request) {
                console.log('加载失败!');
            }
        })
    }


    // 弹窗关闭按钮
    $('.w_btn').on('touchstart', function () {
        $('.w_info_box').animate({top: '-100%'});
        $('.cover').fadeOut();
    })
    // 遮挡层
    $('.cover').on('touchstart', function () {
        $('.w_info_box').animate({top: '-100%'});
        $(this).fadeOut();
    })

    //清除覆盖物
    function remove_overlay() {
        map.clearOverlays();
    }

    /*转换经纬度*/
    function newPoint(_point) {
        var pointArr = [];
        if (_point != null) {
            if (_point.indexOf(',') !== -1) {
                var _pointx = _point.split(',')[0];
                var _pointy = _point.split(',')[1];
            } else if (_point.indexOf('|') !== -1) {
                var _pointx = _point.split('|')[0];
                var _pointy = _point.split('|')[1];
            }

            pointArr.push(_pointx, _pointy);
            return pointArr;
        }
    }

    setInterval(function () {
        $('#LXB_CONTAINER_SHOW').hide();
        $('#LRMINIBar').hide();
    }, 80);
})