<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <base th:href="${#request.getContextPath() + '/'}">
    <meta charset="utf-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="assets/fonts/font-awesome/css/font-awesome.css"/>
    <link rel="stylesheet" href="assets/layuiadmin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="assets/layuiadmin/style/admin.css" media="all">
    <style>
        .layui-form-label-up {width: 100% !important; height: 30px !important; line-height: 30px !important; border: none !important; padding: 0px !important; font-size: 15px; background-color: transparent !important; text-align: left !important;}
        .layui-input-block-down {margin: 0px !important; left: 0px !important;}
        .layui-input-block-down .layui-form-select .layui-edge {top: 74%;}
        .select-area {position: relative;}
        .select-area #areaName {width: 64%}
        .select-area .select-btn {position: absolute; top: 30px; right: 0px; width: 36%; border-color: #e6e6e6;}
        .select-area .select-btn button {height: 38px; width: 50%;}
    </style>
</head>
<body>
<div class="layui-fluid layui-anim layui-anim-fadein">
    <div class="layui-card">
        <div class="layui-card-header">
            <span class="layui-breadcrumb" lay-filter="breadcrumb" style="visibility: visible;">
              <a class="close" href="javascript:void(0);">上级列表</a><span lay-separator="">/</span>
              <a href="javascript:void(0);"><cite>新增内容</cite></a>
            </span>
        </div>
        <div class="layui-card-body" style="padding: 15px; position: relative; overflow: hidden;">
            <form class="layui-form layui-form-pane" lay-filter="dataForm">
                <div class="layui-row layui-col-space15">
                    <div id="formContainer" class="layui-col-xs2">
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-label-up">网格组</label>
                            <div class="layui-input-block layui-input-block-down layui-form" id="gridGroupIdTemplateBox" lay-filter="gridGroupIdTemplateBox"></div>
                            <script id="gridGroupIdTemplate" type="text/html">
                                <select id="gridGroupId" name="gridGroupId" lay-filter="gridGroupId">
                                    <option value="">选择网格组</option>
                                    {{# for(var i = 0, item; item = d[i++];) { }}
                                    <option value="{{item.gridGroupId}}">{{item.gridGroupName}}</option>
                                    {{# } }}
                                </select>
                            </script>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-label-up">网格名称</label>
                            <div class="layui-input-block layui-input-block-down">
                                <input type="text" id="gridName" name="gridName" class="layui-input" value="" placeholder="请输入网格名称" maxlength="255" lay-verify="required">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-label-up">网格描述</label>
                            <div class="layui-input-block layui-input-block-down">
                                <input type="text" id="gridSummary" name="gridSummary" class="layui-input" value="" placeholder="请输入网格描述" maxlength="255">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-label-up">网格职责</label>
                            <div class="layui-input-block layui-input-block-down">
                                <input type="text" id="gridDuty" name="gridDuty" class="layui-input" value="" placeholder="请输入网格职责" maxlength="255">
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-label-up">选择地区</label>
                            <div class="layui-input-block layui-input-block-down select-area">
                                <input type="hidden" id="areaCode" name="areaCode">
                                <input type="text" id="areaName" name="areaName" class="layui-input" value="" placeholder="请选择地区" maxlength="255" lay-verify="required" readonly>
                                <div class="layui-btn-group select-btn">
                                    <button type="button" id="areaSelectBtn" class="layui-btn layui-btn-sm layui-btn-primary" title="选择区域">
                                        <i class="fa fa-circle-thin"></i>
                                    </button>
                                    <button type="button" id="areaCleanBtn" class="layui-btn layui-btn-sm layui-btn-primary" title="删除区域">
                                        <i class="fa fa-times-circle"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label layui-form-label-up">添加人员</label>
                            <div class="layui-input-block layui-input-block-down">
                                <input type="hidden" id="userIds" name="userIds">
                                <input type="text" id="userNames" name="userNames" class="layui-input" value="" placeholder="选择人员" maxlength="255" readonly>
                            </div>
                        </div>
                        <div class="layui-form-item layui-layout-admin">
                            <div class="layui-input-block">
                                <div class="layui-footer" style="left: 0;">
                                    <button id="confirmBtn" type="button" class="layui-btn" lay-submit lay-filter="submitForm">提交编辑</button>
                                    <button type="button" class="layui-btn layui-btn-primary close">返回上级</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-xs10">
                        <div id="baiduMapContainer"></div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script type="text/javascript" src="http://api.map.baidu.com/api?v=3.0&ak=mlfOah4gWM1FjEo9CmlI64zK6MhyiMPW"></script>
<script type="text/javascript" src="static/baidu-map/baidu-map-1.0.0.min.js"></script>
<script src="assets/layuiadmin/layui/layui.js"></script>
<script th:inline="javascript">
    layui.config({
        base: 'assets/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'laydate', 'laytpl'], function(){
        var $ = layui.$;
        var $win = $(window);
        var form = layui.form;
        var laytpl = layui.laytpl;
        var laydate = layui.laydate;
        var centerPoint = {
            lng: [[${baiduMapProperties.centerLng}]],
            lat: [[${baiduMapProperties.centerLat}]]
        }

        var baiduMap = null;
        var gridMember = {
            users: [],
            gridArray: []
        }

        function closeBox() {
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        }

        function initSelectRadioCheckboxTemplate(templateId, templateBoxId, data, callback) {
            laytpl(document.getElementById(templateId).innerHTML).render(data, function(html) {
                document.getElementById(templateBoxId).innerHTML = html;
            });
            form.render('select', templateBoxId);
            if(callback) {
                callback();
            }
        }

        // 初始化网格组下拉选择
        function initGridGroupSelect(selectValue) {
            top.restAjax.get(top.restAjax.path('api/grid-group/list', []), {
            }, null, function(code, data, args) {
                initSelectRadioCheckboxTemplate('gridGroupIdTemplate', 'gridGroupIdTemplateBox', data, function() {
                    var selectObj = {};
                    selectObj['gridGroupId'] = selectValue;
                    form.val('dataForm', selectObj);
                });
            }, function(code, data) {
                top.dialog.msg(data.msg);
            });
        }

        function initMap() {
            $('#formContainer').css({
                height: ($win.height() - 145) +'px',
                overflow: 'auto'
            })
            $('#baiduMapContainer').css({
                width: '100%',
                height: ($win.height() - 145) +'px'
            });
            baiduMap = new BaiduMap('baiduMapContainer', {
                single: true,
                onGridStartEdit: function(baiduMap) {
                    if(!$('#areaCode').val()) {
                        top.dialog.msg('请选择地区');
                        return false;
                    }
                    $('#confirmBtn').hide();
                },
                onGridStopEdit: function(gridArray) {
                    gridMember.gridArray = gridArray;
                    $('#confirmBtn').show();
                }
            });
            baiduMap.setCenterAndZoom(centerPoint, [[${baiduMapProperties.zoom}]]);
            var mapTypeControl = new BMap.MapTypeControl({
                mapTypes: [BMAP_NORMAL_MAP, BMAP_SATELLITE_MAP, BMAP_HYBRID_MAP],
            });
            baiduMap.getMap().addControl(mapTypeControl);
            baiduMap.setBoundary([[${baiduMapProperties.boundary}]]);
            baiduMap.setDefaultConfig();
            baiduMap.initGridOption();
            baiduMap.initGridOptionEvent();
            baiduMap.initColorOption();
        }

        // 初始化内容
        function initData() {
            initGridGroupSelect();
            initMap();
        }
        initData();

        // 初始化网格背景
        function initGridBG(areaCode) {
            baiduMap.clearMap();
            var layIndex;
            top.restAjax.get(top.restAjax.path('api/grid/list-all-with-point/area-code/{areaCode}', [areaCode]), {}, null, function(code, data) {
                var gridArray = [];
                for(var i = 0, item; item = data[i++];) {
                    var pointArray = [];
                    for(var j = 0, jItem; jItem = item.pointArray[j++];) {
                        pointArray.push(new BaiduMap.Point(jItem.lng, jItem.lat));
                    }
                    gridArray.push({
                        id: item.gridId,
                        label: item.gridName,
                        fillColor: '#ffffff',
                        pointArray: pointArray
                    })
                }

                baiduMap.initBackgroundGrid({
                    gridArray: gridArray
                });
            }, function(code, data) {
                top.dialog.msg(data.msg);
            }, function () {
                layIndex = top.dialog.msg(top.dataMessage.loading, {icon: 16, time: 0, shade: 0.3});
            }, function () {
                top.dialog.close(layIndex);
            });
        }

        // 初始化编辑网格
        function initEditGrid(areaCode, userIds) {
            baiduMap.clearMap();
            var layIndex;
            top.restAjax.get(top.restAjax.path('api/grid/list', []), {
                areaCode: areaCode,
                userIds: userIds ? userIds : ''
            }, null, function(code, data) {
                var grids = [];
                for(var i = 0, item; item = data[i++];) {
                    grids.push(item.grid);
                }
                // 设置编辑网格
                baiduMap.setGridArray(grids);
            }, function(code, data) {
                top.dialog.msg(data.msg);
            }, function () {
                layIndex = top.dialog.msg(top.dataMessage.loading, {icon: 16, time: 0, shade: 0.3});
            }, function () {
                top.dialog.close(layIndex);
            });
        }

        // 区域选择
        (function() {
            $('#areaSelectBtn').on('click', function() {
                top.dialog.open({
                    title: '选择地区',
                    url: top.restAjax.path('route/area/get-select?areaName={areaName}', [encodeURI($('#areaName').val())]),
                    width: '600px',
                    height: '225px',
                    onClose: function() {
                        var selectedAreaArray = top.dialog.dialogData.selectedAreaArray;
                        if(selectedAreaArray.length > 0) {
                            var areaCode = '';
                            var areaName = '';
                            areaCode = selectedAreaArray[selectedAreaArray.length - 1].areaCode;
                            for(var i = 0, item; item = selectedAreaArray[i++];) {
                                if(areaName) {
                                    areaName += '/';
                                }
                                areaName += item.areaName;
                            }
                            initGridBG(areaCode);
                            $('#areaCode').val(areaCode);
                            $('#areaName').val(areaName);
                        }
                    }
                })
            });
            $('#areaCleanBtn').on('click', function () {
                $('#areaCode').val('');
                $('#areaName').val('');
            })
        })();


        $('#userNames').on('click', function() {
            top.dialog.dialogData.selectedUserIds = $('#userIds').val();
            top.dialog.open({
                url: top.restAjax.path('route/department/user/select-user', []),
                title: '选择用户',
                width: '500px',
                height: '500px',
                onClose: function() {
                    var selectedUsers = top.dialog.dialogData.selectedDepartmentUsers;
                    // 这里写处理逻辑
                    var userIds = '';
                    var userNames = '';
                    if(selectedUsers && selectedUsers.length > 0) {
                        var relationArray = [];
                        for(var i = 0, item; item = selectedUsers[i++];) {
                            if(userIds) {
                                userIds += '_';
                            }
                            if(userNames) {
                                userNames += ',';
                            }
                            userIds += item.userId;
                            userNames += item.userName;
                            relationArray.push(new BaiduMap.Relation(item.userId, item.userName));
                        }
                        gridMember.users = relationArray;
                    }
                    $('#userIds').val(userIds);
                    $('#userNames').val(userNames);
                }
            })
        });

        // 提交表单
        form.on('submit(submitForm)', function(formData) {
            if(gridMember.gridArray.length == 0) {
                top.dialog.msg('请添加网格');
                return;
            }
            formData.field.grid = gridMember.gridArray[0];
            var relationIdArray = [];
            for(var i = 0, item; item = gridMember.users[i++];) {
                relationIdArray.push(item.id);
            }
            formData.field.grid.relationIdArray = relationIdArray;
            top.dialog.confirm(top.dataMessage.commit, function(index) {
                top.dialog.close(index);
                var loadLayerIndex;
                top.restAjax.post(top.restAjax.path('api/grid/save', []), formData.field, null, function(code, data) {
                    var layerIndex = top.dialog.msg(top.dataMessage.commitSuccess, {
                        time: 0,
                        btn: [top.dataMessage.button.yes, top.dataMessage.button.no],
                        shade: 0.3,
                        yes: function(index) {
                            top.dialog.close(index);
                            window.location.reload();
                        },
                        btn2: function() {
                            closeBox();
                        }
                    });
                }, function(code, data) {
                    top.dialog.msg(data.msg);
                }, function() {
                    loadLayerIndex = top.dialog.msg(top.dataMessage.committing, {icon: 16, time: 0, shade: 0.3});
                }, function() {
                    top.dialog.close(loadLayerIndex);
                });
            });
            return false;
        });

        $('.close').on('click', function() {
            closeBox();
        });

        // 校验
        form.verify({
        });
    });
</script>
</body>
</html>