@{
    ViewBag.Title = "客户信息";
    Layout = "~/Views/Shared/_LayoutTable.cshtml";
}
<style>
    a {
        color: #000000;
    }

        a:hover, a:focus {
            color: #3d84db;
        }
</style>
<body style="background-color: white">

    <div class="container-fluid">
        <div class="row-fluid">
            <div class="col-md-3" style="margin-top:68px;">
                <ul id="demo1" style="overflow-y: auto;height: 525px;background-color:rgb(248, 248, 248);border-radius:10px"></ul>
            </div>
            <div class="col-md-9" style="margin-top:20px">
                <div id="toolbar">
                    <button id="btnManyReslt" class="btn btn-default" onclick="ManyResolution()"><i class="glyphicon glyphicon-record"></i> 批量解析</button>&nbsp;&nbsp;&nbsp;
                    <button id="btnHelp" class="btn btn-default" onclick="help()"><i class="glyphicon glyphicon-paperclip"></i> 获取经纬度帮助</button>
                </div>
                <table id="CustomersTable" data-mobile-responsive="true"></table>
                <input id="rowIndex" type="hidden" />
                <input id="hidLong" type="hidden" />
                <input id="hidLat" type="hidden" />
            </div>
        </div>
    </div>

    <script type="text/javascript">
        $.ajax({
            url: "../WLTManage/GetCustomerInformationTreeList",
            dataType: "json",
            data: {},
            type: "post",
            success: function (data) {//删除成功后刷新table
                if (data.length > 0) {
                    layui.use(['tree', 'layer'], function () {
                        var layer = layui.layer
                        , $ = layui.jquery;

                        //生成一个模拟树
                        var createTree = function (node, start) {
                            node = node || function () {
                                var nd = [];
                                for (var i = 0; i < data.length; i++) {
                                    if (data[i].LEVEAL== 1) {
                                        nd.push(data[i]);
                                    }
                                }
                                return nd;
                            }();
                            start = start || 1;
                            layui.each(node, function (index, item) {
                                var cd = [];
                                for (var i = 0; i < data.length; i++) {
                                    if (data[i].PARID == item.TYPEID) {
                                        cd.push(data[i]);
                                    }
                                }
                                node[index].children = cd;
                                createTree(cd, index + start + 1);
                            });
                            return node;
                        };

                        layui.tree({
                            skin: 'shihuang',
                            elem: '#demo1', //指定元素
                            nodes: createTree(),
                            click: function (node) {
                                var parid = node.TYPEID;
                                var tosonnum = "";
                                if (node.SONNUM != "0") {
                                    tosonnum = node.SONNUM;
                                }
                                $('#CustomersTable').bootstrapTable('refresh', {
                                    url: '../WLTManage/GetCustomersTableList?LoginID=' + '@ViewBag.LoginID' + '&typeid=' + parid + '&leveal=' + tosonnum
                                })
                            }
                        });
                    });
                } else {
                    document.getElementById("isornoptype").style.display = "inline";
                }
            },
            error: function (data) {
                layer.msg(data, { time: 2000 });
            },
        });
    </script>

    <script type="text/javascript">
        var scount = 0;//记录解析成功的条数
        var ecount = 0;//记录解析失败的条数
        var noneed = 0;//记录无需解析的条数
        var index = 0;
        var map = new BMap.Map("allmap");
        var myGeo = new BMap.Geocoder();
        var selectRows = 0;

        function ShowMap(longitude, latitude) {//查看地图
            layer.open({
                type: 2,
                title: '<i class="glyphicon glyphicon-picture"></i> 查看地图',
                shadeClose: false,
                shade: 0.5,
                area: ['90%', '95%'],
                content: '../WLTManage/ShowMap?longitude=' + longitude + '&latitude=' + latitude
            });
        }

        function Resolution(index, row, address, btypeid, longitude, latitude) {//地址解析
            if ($.trim(address) == "") {
                layer.msg("您选择的地址没有解析到结果", { time: 2000 }); return;
            }
            if (longitude != "" && longitude != "null" && latitude != "" && latitude != "null") {
                layer.msg("地址已存在，无需解析！", { time: 2000 }); return;
            }
            // 百度地图API功能
            var map = new BMap.Map("allmap");
            var point;
            var lng;//X
            var lat;//Y
            map.centerAndZoom(point, 12);
            // 创建地址解析器实例
            var myGeo = new BMap.Geocoder();
            // 将地址解析结果显示在地图上,并调整地图视野
            myGeo.getPoint("" + address + "", function (point) {
                if (point) {
                    //map.centerAndZoom(point, 16);
                    //map.addOverlay(new BMap.Marker(point));
                    lng = point.lng;
                    lat = point.lat;
                    $.ajax({
                        url: "../WLTManage/SingleAddressResolution",
                        data: {
                            lng: lng,
                            lat: lat,
                            btypeid: btypeid
                        },
                        datatype: "text",
                        type: "post",
                        success: function (data) {
                            if (data == "解析成功！") {
                                $('#CustomersTable').bootstrapTable('refresh');
                                layer.msg(data, { time: 2000 });
                            } else {
                                layer.msg(data, { time: 2000 });
                            }
                        }
                    })
                } else {
                    layer.msg("您选择的地址没有解析到结果", { time: 2000 });
                }
            }, "");
        }

        function ManyResolution() {//批量解析
            scount = 0;
            ecount = 0;
            noneed = 0;
            index = 0;
            selectRows = $('#CustomersTable').bootstrapTable('getSelections');
            if (selectRows.length <= 0) {
                layer.msg("请选择要解析的地址！"); return false;
            }
            // 百度地图API功能
            var point;
            var btypeid;//
            map.centerAndZoom(point, 12);
            GeocodeByone();
        }

        //修改经纬度
        function UpdateMap(btypeid,long,lat)
        {
            $("#rowIndex").val(btypeid);
            $("#hidLat").val(lat);
            $("#hidLong").val(long);
            layer.open({
                type: 2,
                title: '修改经纬度',
                shadeClose: false,
                shade: 0.5,
                area: ['40%', '30%'],
                content: '../WLTManage/UpdateMap',
                cancel: function (index) {
                    layer.close(index);
                    return false;
                }
            });
        }

        //获取经纬度帮助
        function help() {
            window.open("http://www.gpsspg.com/maps.htm", "_blank");
        }

        function GeocodeByone() {
            var lng;//X
            var lat;//Y
                if (index < selectRows.length) {
                    var btypeid = selectRows[index]["BTYPEID"];
                    if (selectRows[index]["ADDRESS"].length > 0 && !(selectRows[index]["LONGITUDE"])) {
                        myGeo.getPoint("" + selectRows[index]["ADDRESS"] + "", function (point) {
                            if (point) {
                                index++;
                                lng = point.lng;
                                lat = point.lat;
                                $.ajax({
                                    url: "../WLTManage/SingleAddressResolution",
                                    data: {
                                        lng: lng,
                                        lat: lat,
                                        btypeid: btypeid
                                    },
                                    async: false,
                                    datatype: "text",
                                    type: "post",
                                    success: function (data) {
                                        if (data == "解析成功！") {
                                            scount++;
                                        } else {
                                            ecount++;
                                        }
                                        GeocodeByone();
                                    }
                                })
                            }
                            else {
                                index++;
                                ecount++;
                                GeocodeByone();
                            }
                        }, "");
                    } else {
                        index++;
                        ecount++;
                        GeocodeByone();
                    }
                }
                else {
                    if (scount > 0) {
                        layer.msg("批量解析完成，共选中" + selectRows.length + "条；成功：" + scount + "条；失败：" + ecount + "条", { time: 2000 });
                        $('#CustomersTable').bootstrapTable('refresh');
                    }
                    else if (scount <= 0) {
                        layer.msg("批量解析完成！", { time: 2000 });
                    }
                }
        }

        $(function () {
            $('#CustomersTable').bootstrapTable({
                url: '../WLTManage/GetCustomersTableList',         //请求后台的URL（*）
                method: 'post',                      //请求方式（*）
                toolbar: '',                //工具按钮用哪个容器
                striped: false,                      //是否显示行间隔色
                pagination: true,                   //是否显示分页（*）
                sortOrder: "asc",                   //排序方式
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 20, 50],        //可供选择的每页的行数（*）
                minimumCountColumns: 2,  //最少允许的列数
                //height: $(window).height()-70,               //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
                uniqueId: "",            //每一行的唯一标识，一般为主键列
                clickToSelect: true,              //是否启用点击选中行
                sortable: true,                     //是否启用排序
                silentSort: true,
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
                strictSearch: false,
                paginationFirstText: '首页',
                paginationLastText: '末页',
                paginationPreText: '上一页',
                paginationNextText: '下一页',
                showColumns: false,            //是否显示所有的列
                showRefresh: false,              //是否显示刷新按钮
                showToggle: false,                     //是否显示详细视图和列表视图的切换按钮
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                //rowStyle: function (row, index) {
                //    //这里有5个取值代表5中颜色['active', 'success', 'info', 'warning', 'danger'];
                //    var strclass = "";
                //    if (!(row.Longitude) && !(row.Latitude)) {
                //        strclass = 'danger';//还有一个active
                //    }
                //    else {
                //        strclass = 'info';
                //    }
                //    return { classes: strclass }
                //},
                queryParams: function (params) {
                    return {
                        pagesize: params.limit,//页面大小
                        page: params.offset //页码
                    };
                },//传递参数（*）
                columns: [
                    { checkbox: true },
                    {
                        field: "BFULLNAME", title: "客户名称"
                    },
                    { field: 'BTYPEID', title: 'BTYPEID' },
                    { field: 'PERSON', title: '联系人' },
                    { field: 'TEL', title: '联系电话' },
                    { field: 'ADDRESS', title: '地址' },
                    { field: 'LATITUDE', title: 'LATITUDE' },
                    { field: 'LONGITUDE', title: 'Longitude' },
                    { field: 'NEWDATE', title: '最近更新时间' },
                    {
                        field: 'Resolution', title: '地址解析', align: 'center', formatter: function (value, row, index) {
                            if (!(row.LONGITUDE) && !(row.LATITUDE))
                            {
                                var strhtml = '<a style="color:red" onclick="UpdateMap(\'' + row.BTYPEID + '\',\'' + row.LONGITUDE + '\',\'' + row.LATITUDE + '\')">未解析</a>';
                                return strhtml;
                            } else {
                                var strhtml = '<a style="color:green" onclick="UpdateMap(\'' + row.BTYPEID + '\',\'' + row.LONGITUDE + '\',\'' + row.LATITUDE + '\')">' + row.LONGITUDE + ',' + row.LATITUDE + '</a>';
                                return strhtml;
                            }
                        }
                    },
                    {
                        field: 'Edit', title: '查看', formatter: function (value, row, index) {
                            var strhtml = '<button id="btnShowMap" class="btn btn-sm" onclick="ShowMap(\'' + row.LONGITUDE + '\',\'' + row.LATITUDE + '\')"><i class="glyphicon glyphicon-map-marker"></i> 查看</button> <button id="btnResolution" class="btn btn-sm" onclick="Resolution(\'' + index + '\',\'' + row + '\',\'' + row.ADDRESS + '\',\'' + row.BTYPEID + '\',\'' + row.LONGITUDE + '\',\'' + row.LATITUDE + '\')"><i class="glyphicon glyphicon-record"></i> 地址解析</button>';
                            return strhtml;
                        }
                    }
                ]

            });
            $(window).resize(function () {
                $('#CustomersTable').bootstrapTable('resetView');
            });
            $('#CustomersTable').bootstrapTable('hideColumn', 'BTYPEID');
            $('#CustomersTable').bootstrapTable('hideColumn', 'LATITUDE');
            $('#CustomersTable').bootstrapTable('hideColumn', 'LONGITUDE');
        });
    </script>
</body>
