var projectData = '';
var map = {
    getMap: function(data){
        var options = {
            subdistrict: 0,
            extensions: 'all',
            level: 'province'
        };
        var district = new AMap.DistrictSearch(options);
        district.search('杭州市', 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,
                mapStyle: 'amap://styles/d3ce37d9fe39b7cc5f08f48af52802a2',
                resizeEnable: true,
                viewMode: '3D',
                showLabel: true
            });
            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($("#area").html(), 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.data){
                for(var i = 0; i < data.data.length; i++) {
                    var item = data.data[i];
                    if(item.is_testing == 1){
                        var marker = new AMap.Marker({
                            position: [item.mapx, item.mapy],
                            icon: new AMap.Icon({
                                size: new AMap.Size(28, 28),
                                image: "../static/images/icon_dwi_yi.png"
                            }),
                            map: map
                        });
                    }else{
                        var marker = new AMap.Marker({
                            position: [item.mapx, item.mapy],
                            icon: new AMap.Icon({
                                size: new AMap.Size(28, 28),
                                image: "../static/images/icon_dwi_er.png"
                            }),
                            map: map
                        });
                    }
                    marker.content=`<div class='marker-info'>
                        <div class='icon_font icon-icon_zs-01'></div>
                        <div class='icon_font icon-icon_ys-01'></div>
                        <div class='icon_font icon-icon_zx-01'></div>
                        <div class='icon_font icon-icon_yx-01'></div>
                        <div class='marker-top'>
                            <p class='title'>${item.customer_name}</p>
                            <p class='detail' onclick="map.getDetail(${item.SceneTask_id})">详情<span class='icon_font icon-jiantou_xiangyouliangci_o'></span></p>
                        </div>
                        <div class='marker-main'>
                            <div class="item">
                                <div class="img">
                                    <img src="${item.Portrait}" />
                                </div>
                                <div class="info">
                                    <p>检测人员：${item.op_name} / ${item.op_mobile}</p>
                                    <p>所属单位：${item.customer_name}</p>
                                    <p>检测项目：${item.jc_item}</p>
                                </div>
                                <div class="icon">
                                    <p class="icon_font icon-icon_splx-01" onclick="getLeftData.videoConnection('${item.op_code}')"></p>
                                </div>
                            </div>
                        </div>
                    </div>`;
                    marker.on('mouseover', infoOpen);
                    marker.on('click', newMAp);
                }
                map.setZoomAndCenter(12, [Number(data.data[0].mapx), Number(data.data[0].mapy)]);
            }
            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());
            }

            $(".content .left-item .panel1 .panel-info .layui-timeline-item").click(function(){
                var mapx = $(this).attr('data-mapx');
                var mapy = $(this).attr('data-mapy');
                var index = Number($(this).attr('data-index'));
                var item = projectData[index];
                if(mapx && mapy){
                    map.setZoomAndCenter(18, [Number(mapx), Number(mapy)]);
                    infoWindow.setContent(`
                        <div class='marker-info'>
                            <div class='icon_font icon-icon_zs-01'></div>
                            <div class='icon_font icon-icon_ys-01'></div>
                            <div class='icon_font icon-icon_zx-01'></div>
                            <div class='icon_font icon-icon_yx-01'></div>
                            <div class='marker-top'>
                                <p class='title'>${item.customer_name}</p>
                                <p class='detail' onclick="map.getDetail(${item.SceneTask_id})">详情<span class='icon_font icon-jiantou_xiangyouliangci_o'></span></p>
                            </div>
                            <div class='marker-main'>
                                <div class="item">
                                    <div class="img">
                                        <img src="${item.Portrait}" />
                                    </div>
                                    <div class="info">
                                        <p>检测人员：${item.op_name} / ${item.op_mobile}</p>
                                        <p>所属单位：${item.customer_name}</p>
                                        <p>检测项目：${item.jc_item}</p>
                                    </div>
                                    <div class="icon">
                                        <p class="icon_font icon-icon_splx-01" onclick="getLeftData.videoConnection('${item.op_code}')"></p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `);
                    infoWindow.open(map, {Q: Number(mapy),R: Number(mapx),lat: Number(mapy),lng: Number(mapx)});
                }else{
                    map.setZoom(11);
                }
            })

            map.setMapStyle('amap://styles/d3ce37d9fe39b7cc5f08f48af52802a2');
        })
    },
    getDetail: function(SceneTaskID){
        $.ajax({
            url: '/AppModules/CommonFiles/Scene/XCJC_Detail.aspx?id='+SceneTaskID,
            type: "get",
            success: function(data) {
                map.setDetail(data);
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setDetail: function(data){
        // layer.open({
        //     type: 1,
        //     shadeClose: true,
        //     maxmin: true,
        //     title: "<p class='popup-title'>工程检测情况</p>",
        //     area: ['50%', '65%'],
        //     content: data
        // }); {
        $("#popup-info").html(data);
        showPopup('', '工程检测情况');
    }
}

var getLeftData = {
    init: function(){
        this.getSceneTestInfo();
    },
    // 检测计划
    getSceneTestInfo(jc_item=''){
        $.ajax({
            url: baseURL_xcjc+"GetSceneTestInfo.ashx?jc_item="+jc_item,
            type: "post",
            dataType: "json",
            success: function(data) {
                projectData = data.data;
                getLeftData.setSceneTestInfo(data);
                getLeftData.set_xcjcry(data);
                map.getMap(data);
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setSceneTestInfo(data){
        $(".content .left-item .panel1 .panel-info .layui-timeline").html('');
        if(data.data){
            $(".content .left-item .panel1 .panel-info .layui-timeline").append(`
                ${
                    data.data.map((item, index) => {
                        return(`
                            <li class="layui-timeline-item" data-mapx="${item.mapx}" data-mapy="${item.mapy}" data-index=${index}>
                                <i class="layui-icon layui-timeline-axis">&#xe63f;</i>
                                <div class="layui-timeline-content">
                                    <div class="layui-timeline-title">${item.create_time}</div>
                                    <div class="info">
                                    <p>检测单位：${item.customer_name}</p>
                                    <p>参与人员：${item.op_name}</p>
                                    <p>检测项目：${item.project_name}</p>
                                    </div>
                                </div>
                            </li>
                        `)
                    }).join('')
                }
            `);
        }else{
            $(".content .left-item .panel1 .panel-info .layui-timeline").html('<div class="noData">暂无数据</div>');
        }
    },
    // 现场检测人员
    set_xcjcry(data){
        $(".content .left-item .panel2 .panel-info").html('');
        if(data.data){
            $(".content .left-item .panel2 .panel-info").append(`
                ${
                    data.data.map(item => {
                        return(`
                            <div class="item">
                                <div class="img">
                                    <img src="${item.Portrait}" />
                                </div>
                                <div class="info">
                                    <p>检测人员：${item.op_name} / ${item.op_mobile}</p>
                                    <p>所属单位：${item.customer_name}</p>
                                    <p>检测项目：${item.jc_item}</p>
                                </div>
                                <div class="icon">
                                    <p class="icon_font icon-icon_splx-01" onclick="getLeftData.videoConnection('${item.op_code}')"></p>
                                </div>
                            </div>
                        `)
                    }).join('')
                }
            `);
        }else{
            $(".content .left-item .panel2 .panel-info").html('<div class="noData">暂无数据</div>');
        }
    },
    // 视频通话
    videoConnection(target_op_code){
<<<<<<< static/js/xcjc.js
        window.open('https://detect.cnjsjd.net/VideoConnection.aspx?target_op_code='+target_op_code);
        // showPopup('http://detect.cnjsjd.net/VideoConnection.aspx?target_op_code='+target_op_code, '视频通话');
=======
        window.open('https://detect.cnjsjd.net/VideoConnection.aspx?target_op_code=' + target_op_code);
>>>>>>> static/js/xcjc.js
    }
}

var getCenterData = {
    init: function(){
        this.getTestItemList();

    },
    getTestItemList: function(){
        $.ajax({
            url: baseURL_xcjc+"GetTestItemList.ashx",
            type: "post",
            dataType: "json",
            success: function(data) {
                getCenterData.setTestItemList(data);
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setTestItemList: function(data){
        $(".content .center-item .card2").html('<div class="item active">全部</div>');
        $(".content .center-item .card2").append(`
            ${
                data.data.map(item => {
                    return(`
                        <div class="item" data-name='${item.jc_item}'>${item.jc_item}</div>
                    `)
                }).join('')
            }
        `);
        this.toggleItem();
    },
    toggleCard: function(){
        var flag = $(".center-item .card1").attr("data-toggle");
        if(flag == 'true'){
            flag = 'false';
            $(".center-item .card2").addClass('hidden');
        }else{
            flag = 'true';
            $(".center-item .card2").removeClass('hidden');
        }
        $(".center-item .card1").attr("data-toggle", flag);
    },
    toggleItem: function(){
        $(".center-item .card2 .item").click(function(){
            $(".center-item .card2 .item").removeClass('active');
            $(this).addClass('active');
            $(".center-item .card1 .item").html($(this).html());
            var name = $(this).attr('data-name');
            if(name){
                getLeftData.getSceneTestInfo(name);
            }else{
                getLeftData.getSceneTestInfo();
            }
        })
    }
}

var getBottomData = {
    init: function(){
        this.toggle();
        this.getItemAnalysis();
        this.getItemStatistics();
    },
    getItemAnalysis: function(type){
        $.ajax({
            url: baseURL_xcjc+"GetItemAnalysis.ashx",
            type: "post",
            dataType: "json",
            success: function(data) {
                if(type == 'chart'){
                    getBottomData.setItemCount(data);
                    getBottomData.setItemStatistics(data, 0);
                }else{
                    getBottomData.setItemAnalysis(data);
                }
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setItemAnalysis: function(data){
        $(".content .bottom-item .panel-info .list .table-body tbody").html('');
        $(".content .bottom-item .panel-info .list .table-body tbody").append(`
            ${
                data.data.item_info.map(item => {
                    return(`
                            <tr>
                                <td width="30%">${item.jc_item}</td>
                                <td width="20%">${item.total_count}</td>
                                <td width="20%">${item.unqualified_count}</td>
                                <td width="30%" style="color: #FFAA23;">${item.unqualified_rate}%</td>
                            </tr>
                    `)
                }).join('')
            }
        `);
    },
    getItemStatistics(){
        $.ajax({
            url: baseURL_xcjc+"GetItemStatistics.ashx",
            type: "post",
            dataType: "json",
            success: function(data) {
                getBottomData.setItemCount(data);
                getBottomData.setItemStatistics(data, 1);
            },
            error: function(jqXHR) {
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setItemCount: function(data){
        $(".bottom-item .panel-info .chart .chart-value").html(`
            <p>检测总数<span class="number blue-text">${data.data.total_count}</span></p>
            <p><span class="icon_font icon-vertical_line"></span></p>
            <p>合   格<span class="number green-text">${data.data.qualified_count}</span><span class="percent green-text">${(data.data.qualified_count/data.data.total_count*100).toFixed(2)}%</span></p>
            <p><span class="icon_font icon-vertical_line"></span></p>
            <p>不合格<span class="number red-text">${data.data.unqualified_count}</span><span class="percent red-text">${(data.data.unqualified_count/data.data.total_count*100).toFixed(2)}%</span></p>
        `);
    },
    setItemStatistics: function(data, type){
        echarts.init(document.getElementById('chart')).dispose();
        var dom = document.getElementById('chart');
        var myChart = echarts.init(dom);
        var option;
        option = {
            color: ['rgba(0, 192, 255, 0.4)', 'rgba(255, 100, 100, .8)'],
            tooltip: {
                show: true,
                trigger: "axis",
                backgroundColor: 'rgba(0, 0, 0, .2)',
                textStyle: {
                    color: '#fff'
                },
                borderColor: 'rgba(0, 0, 0, .2)',
                formatter: (params)=> {
                    if(type == 1){
                        return  `<p><p class='tooltips-time'>${data.data.day_info[params[0].dataIndex].date}</p>检测量：<span class='blue-text'>${params[0].value}</span></p><p>不合格：<span class='red-text'>${params[1].value}  /  ${(params[1].value/params[0].value * 100).toFixed(2)}%</span></p>`;
                    }else{
                        return `<p><p class='tooltips-time'>${params[0].axisValue}</p>检测量：<span class='blue-text'>${params[0].value}</span></p><p>不合格：<span class='red-text'>${data.data.item_info[params[0].dataIndex].unqualified_rate}%</span></p>`;
                    }
                }
            },
            grid: {
                top: "5%",
                bottom: "5%",
                left: "5%",
                right: "5%",
                containLabel:true
            },
            xAxis: {
                type: 'category',
                interval: 3,
                data: [],
                axisLine:{
                    show: true,
                    symbol: ['none','path://M250 150 L150 350 L350 350 Z'],
                    lineStyle:{
                        color:'#245887'
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#A5B5C5',
                        fontSize : 12
                    }
                },
                axisTick: {
                    show: false
                },
            },
            yAxis: {
                type: 'value',
                axisLine:{
                    show: true,
                    symbol: ['none','path://M250 150 L150 350 L350 350 Z'],
                    lineStyle:{
                        color:'#245887'
                    }
                },
                axisLabel: {
                    textStyle: {
                        color: '#A5B5C5',
                        fontSize : '12'
                    }
                },
                splitLine: {
                    "show": false
                },
                splitArea: {
                    show: true,
                    areaStyle:{
                        color: ['', '#0a2b45']
                    }
                }
            },
            series: [{
                name: '检测量',
                type: 'line',
                symbol: "none",
                data: [],
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[{
                            offset: 0, color: 'rgba(0, 192, 255, .3)'
                        }, {
                            offset: 0.6, color: 'rgba(0, 192, 255, .1)'
                        }, {
                            offset: 1, color: 'rgba(0, 192, 255, 0)'
                        }]
                    ),
                },
                smooth: true
            },{
                name: '不合格',
                type: 'line',
                symbol: "none",
                data: [],
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1,[{
                            offset: 0, color: 'rgba(255, 100, 100, .6)'
                        }, {
                            offset: 0.6, color: 'rgba(255, 100, 100, .3)'
                        }, {
                            offset: 1, color: 'rgba(255, 100, 100, 0)'
                        }]
                    ),
                },
            }
        ]};

        if(type == 1){
            data.data.day_info.forEach(item => {
                option.xAxis.data.push(item.day);
                option.series[0].data.push(item.total_count);
                option.series[1].data.push(item.unqualified_count);
            });
        }else{
            data.data.item_info.forEach(item => {
                option.xAxis.data.push(item.jc_item);
                option.series[0].data.push(item.total_count);
                option.series[1].data.push(item.unqualified_count);
            });
        }

        myChart.setOption(option);
        $(function(){
            window.onresize = function () {
                myChart.resize();
            }
        })
    },
    toggle: function(){
        $(".bottom-item .tab p").click(function(){
            $(".bottom-item .tab p").removeClass('active');
            $(this).addClass('active');
        })
    }
}


getHeader();
getLeftData.init();
getCenterData.init();
getBottomData.init();