var ryData = [];
var map = {
    getMap: function(data){
        var options = {
            subdistrict: 0,
            extensions: 'all',
            level: 'province'
        };
        var district = new AMap.DistrictSearch(options);
        district.search(publicData.province, function(status, result) { 
            var bounds = result.districtList[0]['boundaries'];
            var mask = [];
            for(var i =0;i<bounds.length;i++){
                mask.push([bounds[i]]);
            }
            var map = new AMap.Map("map", {
                mask: mask,
                expandZoomRange:true,
                zoom: 7,
                zooms: [5, 20],
                mapStyle: 'amap://styles/d3ce37d9fe39b7cc5f08f48af52802a2',
                resizeEnable: true,
                viewMode: '3D',
                showLabel: true
            });
            map.setCity(publicData.province,function(e){
                map.setZoom(8)
            })
            var district = null;
            var polygons=[];
            // function drawBounds() {
            //     if(!district){
            //         var opts = {
            //             subdistrict: 0,
            //             extensions: 'all',
            //             level: 'district'
            //         };
            //         district = new AMap.DistrictSearch(opts);
            //     }
            //     //行政区查询
            //     district.setLevel('district')
            //     district.search(publicData.area, function(status, result) {
            //         map.remove(polygons)//清除上次结果
            //         polygons = [];
            //         var bounds = result.districtList[0].boundaries;
            //         if (bounds) {
            //             for (var i = 0, l = bounds.length; i < l; i++) {
            //                 var polygon = new AMap.Polygon({
            //                     strokeWeight: 1,
            //                     path: bounds[i],
            //                     fillOpacity: 0.4,
            //                     fillColor: '#80d8ff',
            //                     strokeColor: '#0091ea'
            //                 });
            //                 polygons.push(polygon);
            //             }
            //         }
            //         map.add(polygons)
            //         map.setFitView(polygons);//视口自适应
            //     });
            // }
            // drawBounds();
            var infoWindow = new AMap.InfoWindow({
                offset: new AMap.Pixel(0, -30)
            });
            if(data.op_list){
                for(var i = 0; i < data.op_list.length; i++) {
                    var item = data.op_list[i];
                    if(item.is_testing == 1){
                        var marker = new AMap.Marker({
                            position: [item.mapx, item.mapy],
                            icon: new AMap.Icon({
                                size: new AMap.Size(25, 28),
                                image: "../static/images/icon/icon_gcdw.png"
                            }),
                            map: map
                        });
                    }else{
                        var marker = new AMap.Marker({
                            position: [item.mapx, item.mapy],
                            icon: new AMap.Icon({
                                size: new AMap.Size(25, 28),
                                image: "../static/images/icon/icon_zjgc.png"
                            }),
                            map: map
                        });
                    }
                    marker.content=`<div class='marker-info'>
                        <div class='marker-top'>
                            <p class='title'>${item.op_name}&nbsp;${item.op_mobile}</p>
                            <p class='detail' onclick="map.getDetail(${item.SceneTask_id})">检测详情</p>
                        </div>
                        <div class='marker-main'>
                            <div class="item">
                                <div class="img">
                                    <img src="${item.Portrait}" />
                                </div>
                                <div class="info">
                                    <div><p>检测项目：</p>${item.jc_item}</div>
                                    <div><p>工程名称：</p>${item.project_name}</div>
                                </div>
                            </div>
                        </div>
                    </div>`;
                    marker.on('mouseover', infoOpen);
                    marker.on('click', newMAp);
                }
                // map.setZoomAndCenter(7, [Number(data.op_list[0].mapx), Number(data.op_list[0].mapy)]);
                map.setZoomAndCenter(7, publicData.xy);
            }else{
                map.setZoomAndCenter(7, publicData.xy);
            }
            function newMAp(e) {
                var infoWindow = new AMap.InfoWindow({
                    offset: new AMap.Pixel(0, -30)
                });
                infoWindow.setContent(e.target.content);
                infoWindow.open(map, e.target.getPosition());
            }

            function infoOpen(e) {
                infoWindow.setContent(e.target.content);
                infoWindow.open(map, e.target.getPosition());
            }

            $("#xcry-data .panel").click(function(){
                var mapx = $(this).attr('data-mapx');
                var mapy = $(this).attr('data-mapy');
                var index = Number($(this).attr('data-index'));
                var item = ryData[index];
                if(mapx && mapy){
                    map.setZoomAndCenter(12, [Number(mapx), Number(mapy)]);
                    infoWindow.setContent(`
                        <div class='marker-info'>
                        <div class='marker-top'>
                            <p class='title'>${item.op_name}&nbsp;${item.op_mobile}</p>
                            <p class='detail' onclick="map.getDetail(${item.SceneTask_id})">检测详情</p>
                        </div>
                        <div class='marker-main'>
                            <div class="item">
                                <div class="img">
                                    <img src="${item.Portrait}" />
                                </div>
                                <div class="info">
                                    <div><p>检测项目：</p>${item.jc_item}</div>
                                    <div><p>工程名称：</p>${item.project_name}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                    `);
                    infoWindow.open(map, {Q: Number(mapy),R: Number(mapx),lat: Number(mapy),lng: Number(mapx)});
                }else{
                    map.setZoom(7);
                }
            })

            map.setMapStyle('amap://styles/d3ce37d9fe39b7cc5f08f48af52802a2');
        })
    },
    getDetail: function(SceneTask_id){
        $.ajax({
            url: URL + 'AppModules/CommonFiles/Scene/XCJC_Detail.aspx?id='+SceneTask_id,
            type: "get",
            success: function(data) {
                map.setDetail(data);
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setDetail: function(data){
        $("#popup-info").html(data);
        layer.open({
            type: 1, 
            shadeClose: true,
            maxmin: true,
            title: "<p class='popup-title'>工程检测情况</p>",
            area: ['9rem', '6rem'],
            content: $('#popup-info'),
            end: function(){
                $("#popup-info").html('');
                $("#popup-info").css('display', 'none');
            }
        }); 
    }
}
/**
 * 现场人员
 */
var xcry = {
    init: function(){
        $("#xcry-date").html(getDate());
        this.get_data();
    },
    get_data: function(){
        let _this = this;
        $.ajax({
            url: baseURL+'UnitXCJC/GetSceneTestInfo.ashx',
            type: "post",
            data: {
                date: $("#xcry-date").html(),
                jc_item: $("#lselect").val(),
                keywords: $("#xcry-keywords").val()
            },
            success: function(data) {
                data =  JSON.parse(data);
                map.getMap(data.data);  
                jcxmList.init();
                if(data.data.op_count){
                    _this.set_data(data.data);
                }else{
                    $("#xcry-count").html(0);
                    $("#xcry-data").html('<div class="nodata">暂无数据</div>');
                }
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    set_data: function(data){
        $("#xcry-count").html(data.op_count);
        $("#xcry-data").html('');
        ryData = data.op_list;
        var str = '';
        for(var i=0; i<data.op_list.length; i++){
            var item = data.op_list[i];
            str += `
                <div class="panel" data-mapx="${item.mapx}" data-mapy="${item.mapy}" data-index="${i}">
                    <div class="img">
                        <img src="${item.Portrait}" />
                    </div>
                    <div class="info">
                        <div class="title"><div class="name">${item.op_name}</div>${item.op_mobile}</div>
                        <div class="item">
                            <div class="key">检测项目：</div>
                            <div class="value">${item.jc_item}</div>
                        </div>
                        <div class="item">
                            <div class="key">工程名称：</div>
                            <div class="value">${item.project_name}</div>
                        </div>
                    </div>
                </div>
            `;
        }
        $("#xcry-data").html(str);
    }
}
$("#xcry-keywords").keydown(function (event) {
    if (event.keyCode == 13) {
        xcry.get_data();
    }
});


/**
 * 检测计划
 */
var jcjh = {
    init: function(){
        $("#jcjh-date").html(getDate());
        this.get_data();
    },
    get_data: function(){
        let _this = this;
        $.ajax({
            url: baseURL+'UnitXCJC/GetSceneTestInfo.ashx',
            type: "post",
            data: {
                date: $("#jcjh-date").html(),
                jc_item: $("#jcjh-item").val(),
                keywords: ''
            },
            success: function(data) {
                data =  JSON.parse(data);
                if(data.data.op_count){
                    _this.set_data(data.data);
                }else{
                    $("#jcjh-count").html(0);
                    $("#jcjh-data").html('<div class="nodata">暂无数据</div>');
                }
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    set_data: function(data){
        $("#jcjh-count").html(data.op_count);
        $("#jcjh-data").html('');
        var str = '';
        for(var i=0; i<data.op_list.length; i++){
            var item = data.op_list[i];
            str += `
                <div class="list-info flex-item">
                    <div class="item1">【${item.project_no}】${item.location}</div>
                    <div class="item2">${item.jc_item}</div>
                    <div class="item3">${item.op_name}</div>
                    <div class="item4">${item.test_begin_datetime}</div>
                    <div class="item5">${item.test_end_datetime}</div>
                    ${item.test_step == 1? '<div class="item6 green">开始检测</div>':''}
                    ${item.test_step == 2? '<div class="item6 green">检测中</div>':''}
                    ${item.test_step == 3? '<div class="item6 yellow">已离场</div>':''}
                    ${item.test_step == 4? '<div class="item6 green">已返场</div>':''}
                    ${item.test_step == 5? '<div class="item6 green">检测完成</div>':''}
                    
                </div>
            `;
        }
        $("#jcjh-data").html(str);
    }
}
$("#jcjh-item").keydown(function (event) {
    if (event.keyCode == 13) {
        jcjh.get_data();
    }
});

/**
 * 检测项目分析
 */
var jcxm = {
    init: function(){
        this.check(1);
    },
    check: function(type){
        $("#jcxm-tab .item").removeClass("active");
        $("#jcxm-tab .item"+type).addClass("active");
        this.get_data(type);
    },
    get_data: function(type){
        let _this = this;
        $.ajax({
            url: baseURL+'UnitXCJC/GetItemAnalysis.ashx',
            type: "post",
            data: {
                date: '',
                date_type: type //0近一年 1近一月
            },
            success: function(data) {
                data =  JSON.parse(data);
                if(data.data.item_info){
                    _this.set_data(data.data);
                }else{
                    $("#jcxm-data").html('<div class="nodata">暂无数据</div>');
                }
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    set_data: function(data){
        $("#jcxm-data").html('');
        var str = '';
        for(var i=0; i<data.item_info.length; i++){
            var item = data.item_info[i];
            str += `
            <div class="list-info flex-item">
                <div class="item1">${item.jc_item}</div>
                <div class="item2">${item.total_count}</div>
                <div class="item3">${item.unqualified_count}</div>
                <div class="item4 ${item.unqualified_rate<50?'blue':item.unqualified_rate<80?'yellow':'orange'}">${item.unqualified_rate}%</div>
            </div>
            `;
        }
        $("#jcxm-data").html(str);
    }
}

/**
 * 本月检测情况
 */
var byjc = {    
    init: function(){
        $("#byjc-date").val(getMonth());
        this.get_data();
        this.get_chart_data();
    },
    get_data: function(){
        let _this = this;
        $.ajax({
            url: baseURL+'UnitXCJC/GetItemAnalysis.ashx',
            type: "post",
            data: {
                date: $("#byjc-date").val(),
                date_type: 0
            },
            success: function(data) {
                data =  JSON.parse(data);
                if(data.data.test_info){
                    _this.set_data(data.data);
                }else{
                    $("#byjc-data").html('<div class="nodata">暂无数据</div>');
                }
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    set_data: function(data){
        $("#byjc-data").html('');
        var item = data.test_info;
        var str = `
            <div class="item">
                <div class="key">检测总数</div><div class="number blue-deep">${item.total_count}</div>
            </div>
            <div class="item">
                <div class="key">合格数量</div><div class="number cyan">${item.qualified_count}</div>
            </div>
            <div class="item">
                <div class="key">不合格数量</div><div class="number orange">${item.unqualified_count}</div>
            </div>
            <div class="item">
                <div class="key">合格率</div><div class="number blue">${item.qualified_rate}%</div>
            </div>
            <div class="item">
                <div class="key">不合格率</div><div class="number yellow">${item.unqualified_rate}%</div>
            </div>
        `;
        $("#byjc-data").html(str);
    },
    get_chart_data: function(){
        let _this = this;
        echarts.init(document.getElementById('chart')).dispose();
        $.ajax({
            url: baseURL+'UnitXCJC/GetItemStatistics.ashx',
            type: "post",
            data: {
                date: $("#byjc-date").val(),
            },
            success: function(data) {
                data =  JSON.parse(data);
                _this.set_chart_data(data.data.day_info);
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    set_chart_data: function(data){
        var dateArr = [];
        var total_countArr = [];
        var unqualified_countArr = [];
        for(var i=0; i<data.length;i++){
            dateArr.push(data[i].date);
            total_countArr.push(data[i].total_count);
            unqualified_countArr.push(data[i].unqualified_count);
        }
        echarts.init(document.getElementById('chart')).dispose();
        var dom = document.getElementById('chart');
        var myChart = echarts.init(dom);
        var option;
        option = {
            color: ['#02FFFC', '#FF6000'],
            legend: {
                itemHeight: 8,
                itemGap: 40,
                data: [{
                    name:'合格数量',
                    textStyle:{
                        fontSize:12,
                        color:'#02FFFC'
                    },
                    
                    icon:'circle'
                },
            {
                name:'不合格数量',
                textStyle:{
                    fontSize:12,
                    color:'#FF6000'
                },
                icon:'circle'
            }]
            },
            tooltip: {
                show: true,
                trigger: "axis",
                backgroundColor: 'rgba(0, 0, 0, .2)',
                textStyle: {
                    color: '#fff'
                },
                borderColor: 'rgba(0, 0, 0, .2)',
            },
            grid: {
                top: "15%",
                bottom: "5%",
                left: "5%",
                right: "5%",
                containLabel:true
            },
            xAxis: {
                type: 'category',
                interval: 3,
                data: dateArr,
                axisLine:{
                    show: false,
                },
                axisLabel: {
                    textStyle: {
                        color: 'rgba(255, 255, 255, .8)',
                        fontSize : 12
                    }
                },
                axisTick: {
                    show: false
                },   
            },
            yAxis: {
                type: 'value',
                axisLine:{
                    show: false,
                },
                axisLabel: {
                    textStyle: {
                        color: 'rgba(255, 255, 255, .8)',
                        fontSize : '12'
                    }
                },
                splitLine: {
                    "show": true,
                    lineStyle:{
                        color:'rgba(255, 255, 255, .5)',
                        type: 'dashed',
                        width: 1.5
                    }
                },
            },
            series: [{
                name: '合格数量',
                type: 'line',
                symbol: "none",
                data: total_countArr,
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[{
                            offset: 0, color: 'rgba(51, 255, 255, .8)'
                        }, {
                            offset: 0.6, color: 'rgba(51, 255, 255, .4)'
                        }, {
                            offset: 1, color: 'rgba(51, 255, 255, 0)'
                        }]
                    ),
                },
                smooth: true
            },{
                name: '不合格数量',
                type: 'line',
                symbol: "none",
                data: unqualified_countArr,
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[{
                            offset: 0, color: 'rgba(255, 96, 0, .8)'
                        }, {
                            offset: 0.6, color: 'rgba(255, 96, 0, .4)'
                        }, {
                            offset: 1, color: 'rgba(255, 96, 0, 0)'
                        }]
                    ),
                },
            }
        ]};
        myChart.setOption(option);
        $(function(){ 
            window.onresize = function () {
                myChart.resize();
            }
        })
    }
}
// $("#byjc-date").change(function(){
//     byjc.get_data();
//     byjc.get_chart_data();
// })

/**
 * 检测项目列表
 */
var jcxmList = {
    init: function(){
        this.get_data();
    },
    get_data: function(){
        let _this = this;
        $.ajax({
            url: baseURL+'UnitXCJC/GetTestItemList.ashx',
            type: "post",
            data: {
                date: $("#xcry-date").html(),
            },
            success: function(data) {
                data =  JSON.parse(data);
                _this.set_data(data.data);
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    set_data: function(data){
        var arr = [];
        for(var i=0; i<data.length; i++){
            arr.push({title: data[i].jc_item,id: i});
        }
        inst.reload({
            show: false //重载即显示
            ,data: arr
        });
    }
}


var dropdown = layui.dropdown
var inst = dropdown.render({
    elem: '#lselect'
    ,click: function(obj){
        if(obj.title){
            lselect.value = obj.title;
            xcry.get_data();
        }
    }
});

init();
function init(){
    getHeadData().then(() =>{
        // $("#header #tab .item:nth-child(2)").addClass('active');
        xcry.init();
    })
    jcjh.init();
    jcxm.init();
    byjc.init();

    layui.use(['layer', 'laydate'],function(){
        var laydate = layui.laydate;
        laydate.render({ 
            elem: '#xcry-date'
            ,btns: ['confirm']
            ,done: function(){
                xcry.get_data();
            }
        });
        laydate.render({ 
            elem: '#jcjh-date'
            ,btns: ['confirm']
            ,done: function(){
                jcjh.get_data();
            }
        });
        laydate.render({ 
            elem: '#byjc-date'
            ,type: 'month'
            ,btns: ['confirm']
            ,done: function(){
                byjc.get_data();
                byjc.get_chart_data();
            }
        });
    });
}
