/* 饼图 */
(function() {

    /* 饼图初始化 */
    var myChartPie = echarts.init(document.querySelector(" .chart"));

    var placeHolderStyle = {
        normal: {
            color: '#fff',
            opacity: .1
        },
        emphasis: {
            color: '#fff',
            opacity: .1
        }
    }
    optionPie = {
        grid: {
            left: '4%',
            top: '4%',
            height: "100%",
            containLabel: true
        },


        textStyle: {
            fontSize: 16,
            color: '#40E7F4 '
        },

        tooltip: {
            trigger: 'item',
            formatter: "{a} :<br/>({d}%)"
        },
        color: ['#3FFFEA', '#FFFF00'],
        legend: {
            orient: 'horizontal',
            bottom: '0',
            left: '12%',
            data: ['失电', '低压'],
            textStyle: {
                color: '#40E7F4 ',
                fontSize: 12
            },
            formatter(name) {
                return name
            },
            itemWidth: 20,
            itemHeight: 10,
            itemGap: 10
        },
        series: [{
            name: '失电',
            type: 'pie',
            radius: ['70%', '80%'],
            center: ["50%", "40%"],

            label: false,
            startAngle: 90,
            clockWise: true, //顺时加载
            hoverAnimation: true,
            hoverOffset: 3,
            data: [{

                    value: 103,
                    name: '失电',

                },
                {
                    value: 242,
                    hoverAnimation: false, //鼠标移入变大
                    itemStyle: placeHolderStyle
                }

            ]
        }, {
            name: '低压',
            type: 'pie',
            radius: ['50%', '60%'],
            center: ["50%", "40%"],
            label: false,
            startAngle: 270,
            clockWise: true,
            hoverAnimation: true,
            hoverOffset: 3,
            data: [{
                    value: 242,
                    name: '低压',

                },
                {
                    value: 103,
                    hoverAnimation: false,
                    itemStyle: placeHolderStyle
                }
            ]
        }]
    };
    myChartPie.setOption(optionPie);
    window.addEventListener("resize", function() {
        myChartPie.resize();
    });

    // 数据统计ajax请求数据
    function getStatisticData2(queryParam = {}) {
        ajaxRequest(STATISTICS, "get", queryParam, function(result) {
            var data = result.data[0]


            myChartPie.setOption({
                series: [{


                    data: [{

                            value: data.powerLossAlarmNumber,
                            name: '失电',

                        },
                        {
                            value: data.lowPressureAlarmNumber,
                            hoverAnimation: false, //鼠标移入变大
                            itemStyle: placeHolderStyle
                        }

                    ]
                }, {


                    data: [{
                            value: data.lowPressureAlarmNumber,
                            name: '低压',

                        },
                        {
                            value: data.powerLossAlarmNumber,
                            hoverAnimation: false,
                            itemStyle: placeHolderStyle
                        }
                    ]
                }]
            })



        }, function(errorMsg) {
            alert("请求数据失败!");
        })
    }
    getStatisticData2()






})();

/* 地图 */
(function() {
    var mapStyle = 'amap://styles/659dc6c4753dc6e87c65c8a874c02133';
    var map1 = new AMap.Map('map1', {
        mapStyle: mapStyle, //样式URL
        viewMode: '3D',
        turboMode: false,
        resizeEnable: true,
        zoom: 11,
        center: [121.475644, 31.1857],
        features: ['bg', 'road', 'building'],
        pitch: 45,
        forceVector: true
    });

    var StatusStore = [{
        "address": "静安区万航渡路442号",
        "building_name": "宝辉冶金",
        "company_code": "11284",
        "company_name": "宝辉冶金",
        "d0": 0,
        "d0a": 0,
        "d0ac": 0,
        "d0o": 0,
        "d0oc": 0,
        "fulladdress": "上海市.上海市.静安区.静安区万航渡路442号",
        "lat": 31.34759,
        "lng": 121.3313,
        "phone": "13816977298",
        "username": "裘怡",
        "xmlx": "商业"
    }, {
        "address": "静安区万航渡路442号",
        "building_name": "永鑫汽车配件",
        "company_code": "11283",
        "company_name": "永鑫汽车配件",
        "d0": 0,
        "d0a": 0,
        "d0ac": 0,
        "d0o": 0,
        "d0oc": 0,
        "fulladdress": "上海市.上海市.静安区.静安区万航渡路442号",
        "lat": 31.37482,
        "lng": 121.26621,
        "phone": "13816977298",
        "username": "裘怡",
        "xmlx": "商业"
    }];

    var current_company_code = "";

    var clear_detail_info = function() {
        var d0 = 0,
            d0o = 0,
            d0oc = 0,
            d0a = 0,
            d0ac = 0;
        var d1 = 0,
            d1o = 0,
            d1oc = 0,
            d1a = 0,
            d1ac = 0;
        var d2 = 0,
            d2o = 0,
            d2oc = 0,
            d2a = 0,
            d2ac = 0;
        var d6 = 0,
            d6o = 0,
            d6oc = 0,
            d6a = 0,
            d6ac = 0;
        var d7 = 0,
            d7o = 0,
            d7oc = 0,
            d7a = 0,
            d7ac = 0;
        var detail_info = document.getElementById('detail_info');
        var real_time_alarm_div = document.getElementById('real_time_alarm_div');
        var parent = document.getElementById('map1');
        if (detail_info != undefined) {
            parent.removeChild(detail_info);
            current_company_code = "";
        } else if (real_time_alarm_div != undefined) {
            parent.removeChild(real_time_alarm_div);
        }
    }

    // //撒点图表弹窗
    var showInfo = function(e) {
        var pixel = e.pixel;
        var company_code = e.target.getExtData().company_code;
        var detail_info;
        var parent = document.getElementById('map1')
        for (var i = 0; i < StatusStore.length; i++) {
            if (StatusStore[i].company_code == company_code) {
                if (current_company_code == company_code)
                    return;
                clear_detail_info();
                current_company_code = company_code;
                var qobj = new Object();
                qobj.V_LOGINNAME = $("#V_LOGINNAME").val();
                qobj.V_PASSWORD = $("#V_PASSWORD").val();
                qobj.V_COMPANYID = company_code;
                qobj.I_COMMAND = 4;
                var qdata = "queryJson=" + JSON.stringify(qobj);
                var qurl = 'https://iot.usky.cn/YtIoT/cgi-bin/WebAction2.cgi';
                $.ajax({
                    type: 'POST',
                    url: qurl,
                    data: qdata,
                    success: function(result) {
                        var json = eval('(' + result + ')');
                        if (json.action == 'getAlarmList') {
                            $(".alarm_tab_area").remove();
                            if ((json.ALARM == undefined) || (json.ALARM.length == 0))
                                return;
                            var parent = document.getElementById('map1');
                            json.ALARM.sort(alarmSortByTime);
                            var area = document.createElement('div');
                            area.id = 'alarm_tab_area';
                            area.setAttribute('class', 'alarm_tab_area');
                            parent.appendChild(area);
                        }
                    }

                });
                detail_info = document.createElement('div');
                detail_info.id = 'detail_info';
                detail_info.style.position = 'absolute';
                detail_info.style.top = (pixel.getY() - 210) + 'px';
                detail_info.style.left = (pixel.getX() - 113) + 'px';
                detail_info.style.width = '227px';
                detail_info.style.height = '164px';
                detail_info.style.backgroundImage = 'url(../../res/img/03index/info_bg.png)';
                detail_info.style.zIndex = '500';
                parent.appendChild(detail_info);
                var info_title = document.createElement('div');
                info_title.id = 'info_title';
                info_title.setAttribute('class', 'info_title');
                info_title.innerHTML = '<div style="display:inline-block;vertical-align:middle;align-self:center;">' + StatusStore[i].company_name + '</div>';
                detail_info.appendChild(info_title);

                var info_body0 = document.createElement('div');
                info_body0.id = 'info_body0';
                info_body0.setAttribute('class', 'info_body0');
                // info_body0.innerHTML = '地址：' + StatusStore[i].address;
                info_body0.innerHTML = '<span class="info-text">地理名称：</span>' + StatusStore[i].building_name;
                detail_info.appendChild(info_body0);

                var info_body1 = document.createElement('div');
                info_body1.id = 'info_body1';
                info_body1.setAttribute('class', 'info_body1');
                info_body1.innerHTML = '<span class="info-text">所在位置：</span>' + StatusStore[i].address;
                // info_body1.innerHTML = '联系人：' + StatusStore[i].username;
                detail_info.appendChild(info_body1);

                var info_body2 = document.createElement('div');
                info_body2.id = 'info_body2';
                info_body2.setAttribute('class', 'info_body2');
                info_body2.innerHTML = '<span class="info-text">电压值：</span>' + StatusStore[i].phone;
                // info_body2.innerHTML = '联系电话：' + StatusStore[i].phone;
                detail_info.appendChild(info_body2);
                var info_btn = document.createElement('div');

                var info_body3 = document.createElement('div');
                info_body3.id = 'info_body3';
                info_body3.setAttribute('class', 'info_body3');
                info_body3.innerHTML = '<span class="info-text">采集时间：</span>' + StatusStore[i].phone;
                detail_info.appendChild(info_body3);
                var info_btn = document.createElement('div');


                // info_btn.id = 'info_btn';
                // info_btn.setAttribute('class', 'info_btn');
                // info_btn.innerHTML = '查看详情';
                // info_btn.company_code = company_code;
                // info_btn.onclick = function (e) {
                //     var event = e;
                //     location.href = baseUrl + 'view/frontpage/company.jsp?company_code=' + event.currentTarget.company_code;
                // }
                // detail_info.appendChild(info_btn);
                break;
            }
        }
    }

    //撒点
    var iconWidth = 28;
    var iconHeight = 28;
    var totalLng = 0;
    var totalLat = 0;
    var latngCount = 0;
    var markers = [];
    for (var i = 0; i < StatusStore.length; i++) {
        var obj = StatusStore[i];
        var iconurl = 'images/building_icon.png';
        // var iconurl = baseUrl + 'images/building_icon.png';

        if (obj.d0a != obj.d0ac)
            iconurl = 'images/building_alarm_icon.png';
        //iconurl = baseUrl + 'images/building_alarm_icon.png';

        if ((obj.lat > 30) && (obj.lat < 33) && (obj.lng > 120) && (obj.lng < 125)) {
            totalLng += obj.lng;
            totalLat += obj.lat;
            latngCount++;
            var marker = new AMap.Marker({
                icon: new AMap.Icon({
                    size: new AMap.Size(iconWidth, iconHeight),
                    image: iconurl,
                    imageSize: new AMap.Size(iconWidth, iconHeight)
                }),
                position: new AMap.LngLat(obj.lng, obj.lat),
                extData: {
                    icontype: 'company',
                    company_code: obj.company_code
                },
                offset: new AMap.Pixel(-(iconWidth / 2), -(iconHeight / 2)),
                draggable: false,
                raiseOnDrag: false,
                autoRotation: false,
                label: {
                    offset: new AMap.Pixel(-iconWidth - 5, -(iconHeight / 2) - 10),
                    content: "<div id='label_" + obj.company_code + "' class='info " + ('shown') + "'>" + obj.company_name + "</div>",
                    direction: 'right'
                }
            });
            // AMap.event.addListener(marker, 'click', showBuilding, this);
            AMap.event.addListener(marker, 'mouseover', showInfo, this);
            AMap.event.addListener(marker, 'mouseout', clear_detail_info, this);

            marker.setMap(map1);
            markers.push(marker);
            // if (!MapShow) {

            // }
        }
    }


})();


/* 数据统计 */
(function() {
    // 数据统计ajax请求数据
    function getStatisticData(queryParam = {}) {
        ajaxRequest(STATISTICS, "GET", queryParam, function(result) {
            var data = result.data[0]

            $('#alarmNumber').html(data.alarmNumber)
            $('#processedAlarmNumber').html(data.processedAlarmNumber)
            $('#unprocessedAlarmNumber').html(data.unprocessedAlarmNumber)
            $('#powerLossAlarmNumber').html(data.powerLossAlarmNumber)
            $('#lowPressureAlarmNumber').html(data.lowPressureAlarmNumber)
            $('#siteNumber').html(data.siteNumber)

        }, function(errorMsg) {
            alert("请求数据失败!");
        })
    }
    getStatisticData()
})();



/* 设备列表 */
(function() {

    // 设备列表查询ajax请求数据
    function getListData(queryParam = {}) {

        ajaxRequest(DEVICE_LIST, "POST", queryParam, function(result) {

            if (result.code) {
                var data = result.data
                console.log('data')
                console.log(data)
                var items = '';
                data.forEach(function(item, key) {
                    var deviceStatusClassName = item.deviceStatus == '在线' ? 'online' : 'offline';
                    items += ` <tr data-id=${item.deviceCode} class="detail">
                        <td>${item.deviceName}</td>
                        <td class="${deviceStatusClassName}">${item.deviceStatus}</td>
                        <td>${item.deviceAdress}</td>
                    </tr>`;
                })
                $('#deviceListBox').html(items)

            } else {
                alert('errorMSG')
            }


        }, function(errorMsg) {
            alert("请求数据失败!");
        }, 2)
    }
    getListData({ 'deviceCode': '1' })

    //按钮搜索
    $('#deviceButtonClick').on('click', function() {
        getListData(getSearchParamObj());
    })

    //拼接搜索条件
    function getSearchParamObj() {

        let queryParam = {};
        let deviceStatus = $('#deviceStatus').val();
        queryParam.deviceStatus = deviceStatus;
        return queryParam;
    }


    //设备详情弹框
    $(document).on('dblclick', 'tr.detail', function() {

        let dataId = $('.scroll tbody').find('.selected').data('id');
        // console.log('dataId')
        alert(dataId);

        ajaxRequest(DEVICE_INFO_LIST, "POST", { "deviceCode": dataId }, function(result) {

            if (result.code) {
                var data = result.data[0]
                console.log('data')
                console.log(data)
                var items = ` <ul class="leftUl">
                        <li>${data.Uab}</li>
                        <li>${data.Ubc}</li>
                        <li style="margin-bottom:50px">${data.Uca}</li>
                        <li>${data.F}</li>
                    </ul>
                    <ul class="rightUl">
                        <li>${data.Ia}</li>
                        <li>${data.Ib}</li>
                        <li style="margin-bottom:50px">${data.Ic}</li>
                        <li>${data.P}</li>
                        <li>${data.Q}</li>
                        <li>${data.COS}</li>
                    </ul>`;

                $('#txt-box').html(items)

            } else {
                alert('errorMSG')
            }


        }, function(errorMsg) {
            alert("请求数据失败!");
        }, 2)






        $('.deviceDetailOut').show()
    })
    $('.clsBtn,.cancel').click(function() {
        $('.deviceDetailOut').hide()
    })









})();



/* 告警列表 */
(function() {
    // 告警列表查询ajax请求数据
    function getListData(queryParam = {}) {
        ajaxRequest(ALARM_LIST, "POST", queryParam, function(result) {
            // console.log(result)
            if (result.code) {
                var data = result.RESULT
                console.log('告警列表')
                console.log(data)
                var items = '';
                data.forEach(function(item, key) {
                    var digitalValueClassName = item.digitalValue == '动作' ? 'color-red' : 'color-orange';
                    var handleStatusClassName = item.handleState == '已处理' ? 'processed' : 'unprocess';
                    // var timeConsuming = item.timeConsuming == '--' ? '--' : item.timeConsuming.hours;

                    items += "<tr data-id=" + item.id + " data-alarm='" + JSON.stringify(item) + "'>" +
                        "<td>" + item.companyName + "</td>" +
                        "<td>" + item.companyAdress + "</td>" +
                        "<td class='" + digitalValueClassName + "'>" + item.digitalValue + "</td>" +
                        "<td>" + item.measDesc + "</td>" +
                        "<td>" + item.sendingTime + "</td>" +
                        "<td>" + item.timeConsuming + "</td>" +
                        "<td class='" + handleStatusClassName + "'>" + item.handleState + "</td>" +
                        "</tr>"


                })
                $('#alarmListBox').html(items)

            } else {
                alert('errorMSG')
            }


        }, function(errorMsg) {
            alert("请求数据失败!");
        }, 2)
    }
    getListData()

    //按钮搜索
    $('#alarmButtonClick').on('click', function() {
        getListData(getAlarmSearchParamObj());
    })

    //拼接搜索条件
    function getAlarmSearchParamObj() {

        let queryParam = {};

        let digitalValue = $('#digitalValue').val()
        let startTime = $('#startTime').val();
        let endTime = $('#endTime').val();

        queryParam.digitalValue = digitalValue;
        queryParam.startTime = startTime;
        queryParam.endTime = endTime;

        return queryParam;
    }


    //处置弹框
    $(document).on('dblclick', '.alarm-table tbody tr', function() {
        let alarmInfo = $('.scroll tbody').find('.selected').data('alarm');
        // console.log('alarmInfo')
        // console.log(alarmInfo)
        $('.alarmHanleOut input[name=companyName]').val(alarmInfo.companyName);
        $('.alarmHanleOut input[name=companyAdress]').val(alarmInfo.companyAdress);
        $('.alarmHanleOut input[name=measDesc]').val(alarmInfo.measDesc);

        $('.alarmHanleOut input[name=deviceCode]').val(alarmInfo.deviceCode);
        $('.alarmHanleOut input[name=handleContent]').val(alarmInfo.handleContent);

        //$('.alarmHanleOut input[name=handleMisinformation]').val(alarmInfo.handleMisinformation);
        $('.alarmHanleOut input[name=alarmId]').val(alarmInfo.alarmId);


        if (alarmInfo.handleState == "已处理") {
            //         $("#inc1").removeAttr("checked");
            //         $("#inc0").attr("checked","checked");
            //         $("#inc0").prop("checked", "checked");
            //         $("input[name='handleMisinformation']").each(function() {
            //          if ($(this).val() != alarmInfo.handleMisinformation) {
            //          $(this).removeAttr("checked");
            //          } else {
            //          $(this).prop("checked", "checked");
            //          }
            //         });
            $('.alarmHanleOut input[name=handleMisinformation]').val(alarmInfo.handleMisinformation);

            if (alarmInfo.handleMisinformation == 0) {
                $("#no").prop("checked", true);
            } else {
                $("#yes").prop("checked", true);
            }

            layui.use(['form'], function() {
                var form = layui.form;
                form.render('radio');
            });

        }



        $('.alarmHanleOut').show()
    })
    $('.clsBtn,.cancel').click(function() {
        $('.alarmHanleOut').hide()
        $("tbody tr").removeClass("selected");
    })

    /* 处理发送请求 */
    $('#dataUpdate').click(function() {
        //获取表单的值 并转换成对象
        let allParam = serializeArrayToObj($("#alarmHandleForm").serializeArray());

        //验证数据是否为空
        let res = validParamIsEmpty(allParam, {
            // "ownerMan": "请填写单位负责人",
        });

        if (res.code == -1) {
            alert(res.msg);
            return;
        }


        //验证图片是否为空
        // var uploadImgSrc = $('#drop_area img').attr('src')
        // if (uploadImgSrc == 'images/upload.png') {
        //     alert('请上传图片')

        // }



        //验证通过 请求ajax
        ajaxRequest(ALARM_HANDLE, "POST", allParam, function(result) {
            // if (result.code) {
            //     alert('修改成功')

            // } else {
            //     alert('修改失败')
            // }
            $('.alarmHanleOut').hide()
            getListData();


        }, function(errorMsg) {
            alert("异常错误!");

        }, 2)


    })

})()