/**
 * guoj
 * 2020.05.27
 * 客户坐标维护
    */
    import { UPCLOUD_RDC_TMS_MAINDATA_SERVICE,UPCLOUD_RDC_TMS_BUSINESS_SERVICE,UPCLOUD_RDC_TMS_INTERFACE_SERVICE} from '@/config/serviceSettings.js';
    import { getSelectGJ, querySysPicture } from '@/utils/prolog.ajax.js';
export default () => {
    var map;
    var myGeo;
    let PoSingle_from1;
    //货主table
    var consignor_Table = {
        columns: [
            { id: "companyid", name: "id", type: "ro", width: "130", hidden: true },
            { id: "companycode", name: "货主编号", type: "ro" },
            { id: "companyname", name: "货主名称", type: "ro" }
        ],
        multiselect: false,
        pagebar: { type: "simple" },

        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubCompany/queryCompanyConsignor", //数据接口
        type: "post", //数据提交方式，默认为get
        contentType: "application/json",
        params: JSON.stringify({"companytype": "H"}), //查询提交参数，分页参数默认为pageNum,pageSize
        page: true, //是否启用分页
        totalCount: "totalCount" //总记录数字段，默认totalCount
    };
    var opts = {
        //terrace显示全部，card分页显示
        skin: "card",
        columns: [
            { id: "INDEX", name: "id", type: "ro", width: "100", hidden: true },
            { id: "companyname", name: "客户名称", type: "ro", width: 150 },
            { id: "address", name: "客户地址", type: "ro", width: 150 },
            {
                id: "consignorname",
                name: "货主",
                type: "ro",
                width: 100
            },
            { id: "longitude", name: "客户经度", type: "ro", width: 100 },
            { id: "latitude", name: "客户纬度", type: "ro", width: 100 },
            { id: "remark", name: "备注", type: "ro", width: 130 }
        ],
        toolbar: [
            { type: "settings", labelWidth: 50, labelAlign: "right" },
            {
                type: "row",
                list: [
                    { type: "input", name: "companyname", label: "客户:", className: "layui-col-md6" },
                    {
                        className: "layui-col-md6",
                        type: "selectTable",
                        placeholder: "请选择货主",
                        readonly: false,
                        table: consignor_Table,
                        tableWidth: 500,
                        tableHeight: 400,
                        fieldText: "companyname",
                        fieldValue: "companycode",
                        name: "consignorcode1",
                        label: "货主:",
                        listener: function (consignorGrid) {
                            setMethod(consignorGrid, consignor_Table, function (data) {
                                var fromdata = grid.getToolBarForm().getFormData();
                                data = fromdata.consignorcode1.length == 2 ? "" : data;
                                var datad = {};
                                datad.consignor = data.companyid ? data.companyid : "";
                                grid.getToolBarForm().setFormData(datad);
                            });
                        }
                    },
                    { type: "hidden", name: "consignor", label: "货主:" },
                    {
                        type: "block", className: "layui-col-md6 form_btn_left",
                        list: [
                            { type: "button", className: "btn-normal", name: "querywork", value: "查询" },
                            { type: "newcolumn" },
                            { type: "button", name: "work_Reset", className: "normal", value: "重置" }
                        ]
                    },
                    {
                        type: "block", className: "layui-col-md6 right",
                        list: [
                            { type: "button", className: "btn-normal", name: "work_Reset2", offsetLeft: 10, value: "保存" }
                        ]
                    }
                ]
            }
        ],
        beforeLoadData: function (res) {
            res.data.list.forEach((item, index) => {
              item.INDEX = index + "";
            });
            return res;
        },

        url: UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubAddress/queryPubAddress", //数据接口
        type: "post", //数据提交方式，默认为get
        contentType: "application/json",
        params: "{}", //查询提交参数，分页参数默认为pageNum,pageSize
        page: true, //是否启用分页
        multiselect: false,
        totalCount: "totalCount" //总记录数字段，默认totalCount
    };
    //分页参数 pageSize pageNum
    grid = new PlgGrid(opts);
    grid.renderTo("customerCoordinates_div2A");
    //分组拆分条件查询
    grid.loadData();

    //按钮添加方法
    grid.attachToolBarEvent("onButtonClick", function(name) {
        //查询
        if (name == "querywork") {
            var fdata = grid.getToolBarForm().getFormData();
            grid.setParams(JSON.stringify(fdata));
            grid.reload();
        }
        //重置
        if (name == "work_Reset") {
            grid.getToolBarForm().getDForm().setText("consignorcode1","");
            grid.getToolBarForm().clear();
        }
        //保存
        if (name == "work_Reset2") {
            let data = grid.getSelectedRowId();
            if(data == null || data == ""){
                layer.msg("请选择一行数据");
                return;
            }
            data = grid.getRowData(data);
            let fromData = PoSingle_from1.getFormData();
            data.newLongitude = fromData.newLongitude;
            data.newLatitude = fromData.newLatitude;
            data.newAddress = fromData.newAddress;
            data.province = fromData.province;
            data.city = fromData.city;
            data.district = fromData.district;
            data.town = fromData.town;
            utilAjaxGJ(UPCLOUD_RDC_TMS_MAINDATA_SERVICE+"/pubAddress/addPubAddress", "post", JSON.stringify(data), ()=>{
                layer.msg("成功");
                grid.reload();
            }, "application/json");
        }
    });
    //单击事件
    grid.on("onRowSelect", function (rid) {
        let rd = grid.getRowData(rid);
        PoSingle_from1.setFormData(rd);
        setPlace(rd.address);
        // createMarker({lng: rd.longitude,lat: rd.latitude});
    });

    let PoSingle_div1 = {
        renderer: "customerCoordinates_div2B",
        items: [
            { type: "settings", PoSingle: "label-left", labelWidth: 90 },
            { type: "input", name: "longitude", label: "当前经度:", width: 175,readonly: true },
            { type: "newcolumn" },
            { type: "input", name: "latitude", label: "当前纬度:", width: 175,readonly: true},
            { type: "newcolumn" },
            { type: "input", name: "address", label: "当前地址:", width: 448 ,readonly: true},
            { type: "newcolumn" },
            { type: "input", name: "newLongitude", label: "新经度:", width: 175,readonly: true },
            { type: "newcolumn" },
            { type: "input", name: "newLatitude", label: "新纬度:", width: 175,readonly: true },
            { type: "newcolumn" },
            { type: "input", name: "newAddress", label: "新地址:", width: 448,readonly: true },
            { type: "hidden", name: "province", label: "省:"},
            { type: "hidden", name: "city", label: "市:"},
            { type: "hidden", name: "district", label: "区:"},
            { type: "hidden", name: "town", label: "县:"}
        ]
    };
    PoSingle_from1 = new PlgForm(PoSingle_div1);

    //初始化方法
    function loadData() {

    }

    //#region 百度地图相关代码
    function loadDefulatMap(callback) {
        var point = new BMap.Point(116.404, 39.915); // 创建点坐标
        map.centerAndZoom(point, 15); // 初始化地图，设置中心点坐标和地图级别
        map.addControl(new BMap.NavigationControl());
        map.addControl(new BMap.ScaleControl());
        map.addControl(new BMap.OverviewMapControl());
        //map.addControl(new BMap.MapTypeControl()); //不同类型的百度地图
        map.setCurrentCity("北京"); // 仅当设置城市信息时，MapTypeControl的切换功能才能可用
        //地图加载完成后加载数据
        callback();
    }
    //地图选点点击事件
    function clickCoordinate(e) {
        var point = e.point;
        //请先选择省市区
        //var area = $(".store_Area").val();
        //if (area == null || area == "") {
        //    alert(baiduParam.SelectRegion_Error);
        //    return;
        //}
        createMarker(point);
    }
    function setPlace(value) {
        var local = new BMap.LocalSearch(map, { //智能搜索
            onSearchComplete: myFun
        });
        function myFun() {
            if (local.getResults().getPoi(0)) {
                var point = local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
                createMarker(point);
            }
 else {
                alert("未搜索到结果，请重新输入");
            }
        }
        local.search(value);
    }

    var baiduParam = {
        oldPoint: null,//记录旧值,用于地图拖拽失败后回到原来位置
         Exceed_Error: "定位地址失败，您搜索或定位超出县级范围，请重新选择定位",
         SelectRegion_Error: "定位地址失败，您搜索或定位超出县级范围，请先选择省市区",
         Location_Div: "<div id='descConten'>已将坐标定位为<hr/>{address}<br/><small style='color: #858585;line-height: 24px;'>地址：{title}</small><br/><br/><input type='button' value='确定' id='saveLngLat' style=' background: rgb(135,205,208);border: none;color: white;height: 30px;width: 60px;border-radius: 4px;' ></div> ",
         Location_Sure_Div: "<img style='width:20px;top: 5px;position: relative;'  src='img/success.png' />已将坐标定位为<hr/>{address}<br/><small style='color: #858585;line-height: 24px;'>地址：{title}</small><br/><br/>"
    };

    function createMarker(point, isLoad) {
        //反向解析地址
        myGeo.getLocation(point, function (rs) {
            map.clearOverlays();//清除之前所有的标志

            //红点开始
            var marker = new BMap.Marker(point);// 创建标注
            map.addOverlay(marker); // 将标注添加到地图中
            marker.enableDragging();//可拖拽 自定义拖拽
            //拖拽前事件
            marker.addEventListener("dragstart", function (e) {
                baiduParam.oldPoint = e.point;
            });
            //拖拽完成事件
            marker.addEventListener("dragend", function (e) {
                createMarker(e.point);
            });
            //红点完成

            baiduParam.oldPoint = null;
            /******** 图层初始化 ********/
            /**图层样式文字处理开始**/
            var html = baiduParam.Location_Div;
            if (isLoad == true) {
                map.centerAndZoom(point, map.getZoom()); //重置地图位置
                html = baiduParam.Location_Sure_Div;
            }
            //解析地址
            var rsaddress = rs.address;
            var rstitle = rs.surroundingPois[0] != null ? rs.surroundingPois[0].title : "";
            html = html.replace("{address}", rsaddress).replace("{title}", rstitle);
            /**图层样式文字处理结束**/
            let dataItem = {
                newLongitude: point.lng,
                newLatitude: point.lat,
                newAddress: rsaddress,
                province: rs.addressComponents.province,
                city: rs.addressComponents.city,
                district: rs.addressComponents.district,
                town: rs.addressComponents.street
            };
            PoSingle_from1.setFormData(dataItem);
            var infoWindow = new BMap.InfoWindow(html, { offset: { width: 0, height: -25 } });
            // 创建信息窗口对象
            map.openInfoWindow(infoWindow, point); //开启信息窗口
            //确定事件绑定
            infoWindow.addEventListener("open", function () {
                $("#saveLngLat").unbind("click");
                $("#saveLngLat").click(function () {
                    infoWindow.setContent("<img style='width:20px;top: -2px;position: relative;' src='img/success.png' />已将坐标定位为<hr/>" + rs.address + "<br/><small style='color: #858585;line-height: 24px;'>地址：" + (rs.surroundingPois[0] != null ? rs.surroundingPois[0].title : "") + "</small><br/><br/>");
                    $(".store_Lng").val(rs.point.lng);
                    $(".store_Lat").val(rs.point.lat);
                });
            });
            infoWindow.redraw(function () {
                $("#saveLngLat").unbind("click");
                $("#saveLngLat").click(function () {
                    infoWindow.setContent("<img style='width:20px;top: -2px;position: relative;'  src='img/success.png' />已将坐标定位为<hr/>" + rs.address + "<br/><small style='color: #858585;line-height: 24px;'>地址：" + (rs.surroundingPois[0] != null ? rs.surroundingPois[0].title : "") + "</small><br/><br/>");
                    $(".store_Lng").val(rs.point.lng);
                    $(".store_Lat").val(rs.point.lat);
                });
            });
            /******** 图层初始化 ********/
        });
    }
    //#region /****查询控件类****/
    function BigZoomControl() {
        // 设置默认停靠位置和偏移量
        this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
        this.defaultOffset = new BMap.Size(150, 20);
    }
    setTimeout(() => {
    // 通过JavaScript的prototype属性继承于BMap.Control
    BigZoomControl.prototype = new BMap.Control();
    // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
    // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
    BigZoomControl.prototype.initialize = function (map) {
        // 创建一个DOM元素
        var div = document.createElement("div");
        // 设置样式
        div.style.cursor = "pointer";
        div.style.margin = "0 auto";
        div.style.backgroundColor = "white";
        div.innerHTML = "<div><input type='text' id = 'baiduAddress' name = 'baiduAddress' style='width: 350px;height: 33px;text-indent:1em;float:left;border: 1px solid #D2D2D2!important;border-right:none;' placeholder='输入门店详细地址, 越详细定位越精准' /><div  class='searchMap' style='border:1px solid #f50;background-color:#f50;width:60px;height:33px;float:left;'></div><img  class='searchMap' src='img/search.png' style='height: 22px;position: absolute;right: 18px;top: 7px;'/><div style='clear:both'></div></div>";
        // 添加DOM元素到地图中
        map.getContainer().appendChild(div);
        // 将DOM元素返回
        return div;
    };
    //#endregion
    //#endregion

    //#region 百度地图初始化
    /****************百度地图初始化开始****************/
     map = new BMap.Map("customerCoordinatesmyMap");
    map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
    // 创建地址解析器实例
    myGeo = new BMap.Geocoder();
    loadDefulatMap(loadData);//初始化地图以及加载初始化数据
    // 创建控件
    var myZoomCtrl = new BigZoomControl();
    //// 查询控件类到地图当中
    map.addControl(myZoomCtrl);
    //查询控件的点击事件
    $(".searchMap").click(function () {
        setPlace($("#baiduAddress").val());
    });
    bindEvent();
    function bindEvent() {
        //查询百度地图
        map.addEventListener("click", clickCoordinate); //地图点击事件
    }
    /****************百度地图初始化完成****************/
    }, 1000);
};
