{% load staticfiles %}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>新闻发布</title>
    <link rel="stylesheet" href="{% static '/lib/layui/css/layui.css' %}">
    <link rel="stylesheet" href="{% static '/lib/css/reset.css' %}">
    <script type="text/javascript"
        src="https://api.map.baidu.com/api?v=2.0&ak=EpbgpqakDpXGN9E3ejg6e93ffsi83b0t"></script>
    <!--加载鼠标绘制工具-->
    <script type="text/javascript"
        src="//api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="//api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
    <!--加载检索信息窗口-->
    <script type="text/javascript"
        src="//api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
    <link rel="stylesheet" href="//api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
    <style>
        .breadcrumbs {
            padding: 12px 0 12px 30px;
            border-bottom: 1px solid #dbdbdb;
        }

        .layui-breadcrumb>* {
            font-size: 16px;
        }

        .fixedDiv {
            position: fixed;
            width: 100%;
            z-index: 999;
            box-shadow: 0px 3px 5px 0px #ececec;
            background: #fff;
        }

        /* 发布类型 */

        .widget-title {
            position: relative;
            padding-left: 10px;
            font-size: 16px;
            padding: 5px 0 5px 10px;
        }

        .widget-title::after {
            position: absolute;
            content: '';
            left: 0;
            top: 9px;
            height: 15px;
            border-left: 5px solid #23a3ee;
            padding-left: 10px;
            font-size: 16px;
            padding: 5px 0 5px 10px;
        }

        .widget-title h2 {
            font-weight: 700;
            line-height: 33px;
        }

        .widget-title h2 span {
            font-size: 13px;
            font-weight: 100;
            margin-left: 20px;
            color: #333;
        }



        /* 上传详情 */

        .layui-form-item .layui-input-inline {
            width: 50%;
        }

        .uploadContent {
            /* border-top: 7px solid #f0f0f0; */
            padding: 25px;
        }

        .uploadUl>li {
            display: none;
        }

        .uploadUl>li:first-child {
            display: block;
        }

        .innerDiv {
            max-width: 500px;
        }

        /* 图片预览 */

        .layui-upload-img {
            width: 92px;
            height: 92px;
            margin: 0 10px 10px 0;
        }

        #progressBar {
            display: none;
        }

        /* 产品展厅上传多图 */

        .uploadParent {
            position: absolute;
            margin: 10px 0;
        }

        .uploadParent>div {
            display: inline-block;
            width: 92px;
            height: 92px;
            /* border: 1px solid #b8b8b8; */
            background: url(../../static/imgs/addicon.png) no-repeat center;
            background-size: 80% 80%;
            cursor: pointer;
            margin-right: 8px;
        }

        .uploadShowParent .layui-upload-list {
            display: inline-block;
        }

        /* 表单样式 */

        .layui-form-item .layui-input-inline {
            width: 50%;
        }

        .layui-form-item .layui-input-textarea {
            width: 50%;
        }

        .uploadImg {
            position: absolute;
            margin: 10px 0;
            width: 92px;
            height: 92px;
            background: none;
            border: 1px solid #b8b8b8;
            cursor: pointer;
        }

        .uploadImgIcon {
            background: url(../../static/imgs/uploadImgIcon.png) no-repeat center;
            background-size: 80% 80%;
        }

        /* 地图 */
        .layui-form-label {
            width: 102px;
        }

        .mapBox {
            display: flex;
        }

        .map {
            width: 55%;
            height: 400px;
            border: 1px solid #878787;
        }

        .locatPoint button {
            padding: 5px 10px;
            border-radius: 4px;
            margin: 10px 20px 5px;
            color: #fff;
        }

        .locatPoint button.sw {
            background-color: #ed9c22;
        }

        .locatPoint button.ne {
            background-color: #22a3ed;

        }

        .locatPoint button.center {
            background-color: #ed2289;

        }
    </style>
</head>

<body>
    <div class="content">
        <div class="floatNav">
            <!-- 导航 -->
            <div class="breadcrumbs">
                <span class="layui-breadcrumb">
                    <a target="BoardRight">首页</a>
                    <a>
                        <cite>首页设置</cite>
                    </a>
                </span>
            </div>
        </div>

        <!-- 内容 -->
        <div>
            <!-- 发布详情 -->
            <div class="uploadContent" id="uploadContent">
                <div class="widget-title">
                    <h2>我的定位
                        <span id="Uptime"></span>
                    </h2>
                </div>

                <div>
                    <form class="layui-form" action="" id="formDiv" lay-filter="newsFormDiv">
                        <div class="layui-form-item">
                            <label class="layui-form-label">地图图片：</label>
                            <div class="layui-input-inline">
                                <button type="button" class="uploadImg uploadImgIcon" id="newsUpImg"></button>
                                <!-- 隐藏的input -->
                                <input type="hidden" id="img_url" name="upload" value="" />
                                <div class="layui-upload-list">
                                    <img class="layui-upload-img" id="demo1" :src=''>
                                    <p id="demoText"></p>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">图片定位：</label>
                            <div class="layui-input-block">
                                <div class="mapBox">
                                    <div id="imgmap" class="map"></div>
                                    <div class="locatPoint">
                                        圈出当前图片展示位置
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">地图中心点：</label>
                            <div class="layui-input-block">
                                <div class="mapBox">
                                    <div id="centermap" class="map"></div>
                                    <div class="locatPoint">
                                        拖动标注，定位中心点
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
                                <!-- <button type="reset" class="layui-btn layui-btn-primary">重置</button> -->
                                <button class="layui-btn layui-btn-primary clearForm" type="button">取消</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>


    <script src="{% static '/lib/js/jquery-2.1.4.min.js'%}"></script>
    <script src="{% static '/lib/layui/layui.js'%}"></script>
    <script src="{% static 'lib/ckeditor/ckeditor.js'%}"></script>
    <script src="{% static 'lib/ckeditor/lang/zh-cn.js'%}"></script>
    <script src="{% static '/js/backstageNet/common.js'%}"></script>
    <script>
        var element, form, upload;
        layui.use(['element', 'form', 'upload', 'layer'], function () {
            element = layui.element;
            form = layui.form;
            upload = layui.upload;
            layer = layui.layer;
            //一些事件监听
            element.on('tab(demo)', function (data) {
                console.log(data);
            });

            //新闻图片上传
            var uploadInst = upload.render({
                elem: '#newsUpImg'
                , url: 'setMap'
                , field: 'upicture'
                , accept: 'images' //只允许上传图片
                // , acceptMime: 'image/*' //只筛选图片
                // ,exts: 'jpg|jpeg' 
                , size: 1024 * 2 //限定大小
                , xhr: function () { } //上传视频进度条
                , before: function (obj) {
                    $('.uploadImg').removeClass('uploadImgIcon')
                    //预读本地文件示例，不支持ie8
                    obj.preview(function (index, file, result) {
                        $('#demo1').attr('src', result); //图片链接（base64）
                    });
                }
                , done: function (res) {
                    //如果上传失败
                    if (res.code == 0) {
                        //上传成功
                        document.getElementById("img_url").value = res.data.src;
                    } else {
                        return layer.msg('上传失败');
                    }


                }
                , error: function () {
                    //演示失败状态，并实现重传
                    var demoText = $('#demoText');
                    demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                    demoText.find('.demo-reload').on('click', function () {
                        uploadInst.upload();
                    });
                }
            });

            // 百度地图API功能
            var map = new BMap.Map("imgmap", { mapType: BMAP_NORMAL_MAP, minZoom: 4 });//BMAP_HYBRID_MAP  卫星地图
            map.centerAndZoom(new BMap.Point(119.604114, 26.09877), 13);
            // 添加带有定位的导航控件
            var navigationControl = new BMap.NavigationControl({
                // 靠左上角位置
                anchor: BMAP_ANCHOR_TOP_LEFT,
                // LARGE类型
                type: BMAP_NAVIGATION_CONTROL_LARGE,
                // 启用显示定位
                enableGeolocation: true
            });
            map.addControl(navigationControl);

            map.enableScrollWheelZoom(); //启用鼠标滚动对地图放大缩小
            var styleOptions = {
                strokeColor: "red",    //边线颜色。
                fillColor: "red",      //填充颜色。当参数为空时，圆形将没有填充效果。
                strokeWeight: 3,       //边线的宽度，以像素为单位。
                strokeOpacity: 0.5,       //边线透明度，取值范围0 - 1。
                fillOpacity: 0.1,      //填充的透明度，取值范围0 - 1。
                strokeStyle: 'solid' //边线的样式，solid或dashed。
            }
            //实例化鼠标绘制工具
            var drawingManager = new BMapLib.DrawingManager(map, {
                isOpen: false, //是否开启绘制模式
                drawingControl: false,
                draggable: false,
                enableDrawingTool: true, //是否显示工具栏
                drawingToolOptions: {
                    anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
                    offset: new BMap.Size(5, 40), //偏离值
                    drawingModes: [
                        BMAP_DRAWING_RECTANGLE
                    ]
                },
                polygonOptions: styleOptions //多边形的样式
            });

            document.getElementsByClassName('BMapLib_rectangle')[0].addEventListener('click', e => {
                // 这里是你的执行操作
                clearAll()
            })

            //鼠标绘制完成回调方法   获取各个点的经纬度
            var overlays = [];
            var swneLatLng = [];
            var overlaycomplete = function (e) {
                drawingManager.close();
                swneLatLng = [];
                overlays.push(e.overlay);

                swneLatLng.push(e.overlay.zo[1])
                swneLatLng.push(e.overlay.zo[3])

                e.overlay.enableEditing();
            };

            //添加鼠标绘制工具监听事件，用于获取绘制结果
            drawingManager.addEventListener('overlaycomplete', overlaycomplete);
            function clearAll() {

                for (var i = 0; i < overlays.length; i++) {
                    map.removeOverlay(overlays[i]);
                }
                overlays.length = 0

            }

            var centermap = new BMap.Map("centermap", { mapType: BMAP_NORMAL_MAP, minZoom: 4 });
            centermap.centerAndZoom(new BMap.Point(119.604114, 26.09877), 13);
            // 添加带有定位的导航控件
            var navigationControl = new BMap.NavigationControl({
                // 靠左上角位置
                anchor: BMAP_ANCHOR_TOP_LEFT,
                // LARGE类型
                type: BMAP_NAVIGATION_CONTROL_LARGE,
                // 启用显示定位
                enableGeolocation: true
            });
            centermap.addControl(navigationControl);

            centermap.enableScrollWheelZoom(); //启用鼠标滚动对地图放大缩小
            var point = new BMap.Point(119.604114, 26.09877);
            var swIcon = new BMap.Icon("../static/imgs/homeIcon1.png", new BMap.Size(21, 25), { imageSize: new BMap.Size(21, 25) });
            var centermapMarker = new BMap.Marker(point, { icon: swIcon });// 东北
            centermap.addOverlay(centermapMarker);
            centermapMarker.enableDragging();

            function GetBasePolygon() {

                var polygon = "";

                for (var i = 0; i < overlays.length; i++) {
                    var path = overlays[i].getPath();//Array<Point> 返回多边型的点数组 
                    var str = "";

                    for (var j = 0; j < path.length; j++) {

                        if (str != "")
                            str += ";";

                        str += path[j].lng + "," + path[j].lat;
                        // console.log("overlays" + i + "::lng:" + path2[j].lng + "\n lat:" + path2[j].lat);
                    }

                    if (str != "") {
                        if (polygon != "")
                            polygon += "|";

                        polygon += str;
                    }
                }

                console.log('polygon');
                return polygon;
            }

            //监听提交
            form.on('submit(formDemo)', function (data) {
                console.log(swneLatLng)
                var contentLngLat = [];
                var allOverlay = centermap.getOverlays();
                for (var i = 0; i < allOverlay.length; i++) {
                    if (allOverlay[i].Pa) {
                        contentLngLat.push(allOverlay[i].point.lng)
                        contentLngLat.push(allOverlay[i].point.lat)
                    }
                }
                var img_url = $('#img_url').val();
                console.log(contentLngLat)
                console.log(img_url)
                

                if (!img_url) {
                    layer.msg("请上传地图底图", { icon: 5 });
                    return false;
                }

                if (!swneLatLng.length) {
                    layer.msg("请绘制图片展示区域", { icon: 5 });
                    return false;
                }
                var polygon = GetBasePolygon();
                console.log(polygon)
                
                $.ajax({
                    url: 'pic_locat',
                    data: {
                        "locat1": JSON.stringify(swneLatLng[0]),
                        "locat2": JSON.stringify(swneLatLng[1]),
                        "pic_center":JSON.stringify(contentLngLat),
                        "locat_info": polygon,
                        "addr": img_url
                    },
                    type: 'post',
                    success: function (data) {
                        if (data == 1) {
                            layer.msg("修改成功", { icon: 1 });
                            clearForm()
                        }else{
                            layer.msg("修改失败", { icon: 2 });
                        }
                    },
                    error: function (type) {

                    }
                })
                return false;

            });

            $('.clearForm').on('click', function () {
                clearForm()
            })

            function clearForm() {
                form.val('newsFormDiv', {
                    "title": "",
                    "writer": "",
                    "intro": ""
                });
                $('#img_url').val('');
                $('.uploadImg').addClass('uploadImgIcon');
                $('#demo1').removeAttr('src'); //图片链接（base64）
                clearAll()
                swneLatLng = ''
            }
        });








        windowAddMouseWheel();
        function windowAddMouseWheel() {
            var scrollFunc = function (e) {
                e = e || window.event;
                var top = $(window).scrollTop();
                if (e.wheelDelta) {  //判断浏览器IE，谷歌滑轮事件
                    if (e.wheelDelta > 0) { //当滑轮向上滚动时
                        if (top < 60) {
                            if ($(".floatNav").hasClass("fixedDiv")) {
                                $(".floatNav").removeClass("fixedDiv");
                                $(window).scrollTop(0)
                            }
                        }
                    }
                    if (e.wheelDelta < 0) { //当滑轮向下滚动时
                        if (top >= 60) {
                            $(".floatNav").addClass("fixedDiv");
                        }
                    }
                } else if (e.detail) {  //Firefox滑轮事件
                    if (e.detail > 0) { //当滑轮向上滚动时
                        if (top < 60) {
                            if ($(".floatNav").hasClass("fixedDiv")) {
                                $(".floatNav").removeClass("fixedDiv");
                                $(window).scrollTop(0)
                            }
                        }
                    }
                    if (e.detail < 0) { //当滑轮向下滚动时
                        if (top >= 60) {
                            $(".floatNav").addClass("fixedDiv");
                        }
                    }
                }
            };
            //给页面绑定滑轮滚动事件
            if (document.addEventListener) {
                document.addEventListener('DOMMouseScroll', scrollFunc, false);
            }
            //滚动滑轮触发scrollFunc方法
            window.onmousewheel = document.onmousewheel = scrollFunc;
        }

    </script>
</body>

</html>