var laydateObj;
var taskList = {
    data: [],
    init: function () {
        this.getData();
    },
    getData: function () {
        let _this = this;
        $.ajax({
            url: baseURL_htjc + "GetTaskList.ashx",
            type: "post",
            dataType: "json",
            data: {
                keywords: $("#rw-keywords").val(),
                date: $("#rw-date").val(),
                page: 1,
                limit: 100
            },
            success: function (data) {
                if (data.data && data.data.length > 0) {
                    _this.data = data.data;
                    _this.setData(data.data);
                    map.getMap(data.data);
                } else {
                    map.getMap([]);
                    $("#rwList").html('<div class="noData">暂无数据</div>');
                }
            },
            error: function (jqXHR) {
                map.getMap([]);
                $("#rwList").html('<div class="noData">暂无数据</div>');
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setData: function (data) {
        var str = '';
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            str += `
                <div class="panel-item">
                    <div class="panel-head">${item.project_no ? '【' + item.project_no + '】' : ''}${item.project_name}</div>
                    <div class="panel-info">
            `;
            for (var j = 0; j < item.task_list.length; j++) {
                var item2 = item.task_list[j];
                str += `
                    <div class="info-item">
                        <div id="rwInfo-${i}-${j}">
                            <div class="item-head" onclick="listClick('rwInfo-${i}-${j}')" data-mapx="${item2.mapx}" data-mapy="${item2.mapy}" data-index="${i}">
                                <div class="flex-item">
                                    <div class="icon ${item2.abnormal_count > 0 ? 'showTip' : ''}"><img src="../static/images/icon_rwd.png"/></div>
                                    任务单：${item2.task_no}
                                </div>
                                <div class="flex-item">
                                    <div class="number"><p><span>${item2.test_count}</span>&nbsp;/</p>&nbsp;${item2.total_count}</div>
                                    <div class="icon icon2"><img src="../static/images/jiantou.png"/></div>
                                </div>
                            </div>
                            <div class="item-main hidden">
                                ${item2.sample_list.map((item3) => {
                    return (`<div class="flex-item"><p>${item3.sample_name}</p><p class="desc ${item3.test_status == 1 ? 'green' : item3.test_status == 2 ? 'red' : ''}">${item3.test_status_str}</p></div>`); //0未检测 1已检测 2强度不达标
                }).join('')
                    }
                            </div>
                        </div>
                    </div>
                `;
            }
            str += `
                    </div>
                </div>
            `;
        }
        $("#rwList").html(str);
    },
    prevDate() {
        $("#rw-date").val(getNextDate(($("#rw-date").val()), -1));
        laydateObj.config.value = getNextDate(($("#rw-date").val(), new Date()), -1);
        this.getData();
    },
    nextDate() {
        $("#rw-date").val(getNextDate(($("#rw-date").val()), 1));
        laydateObj.config.value = getNextDate(($("#rw-date").val(), new Date()), 1);
        this.getData();
    }
}
$("#rw-keywords").keydown(function (event) {
    if (event.keyCode == 13) {
        taskList.getData();
    }
});

var testCount = {
    init: function () {
        this.getData();
    },
    getData: function () {
        let _this = this;
        $.ajax({
            url: baseURL_htjc + "GetTestCount.ashx",
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.data && data.data.length > 0) {
                    _this.setData(data.data);
                } else {
                    $("#zjgc").html('0');
                    $("#ycgc").html('0');
                    $("#yjbw").html('0');
                    $("#bdb").html('0');
                }
            },
            error: function (jqXHR) {
                $("#zjgc").html('0');
                $("#ycgc").html('0');
                $("#yjbw").html('0');
                $("#bdb").html('0');
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setData: function (data) {
        console.log(data)
        $("#zjgc").html(data[0].today_project_count);
        $("#ycgc").html(data[0].today_abnormal_project_count);
        $("#yjbw").html(data[0].today_test_count);
        $("#bdb").html(data[0].today_abnormal_test_count);
    }
}

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,
                zoom: 7,
                zooms: [5, 20],
                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) {
                district.search('濮阳市', 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.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    for (let y = 0; y < data[i].task_list.length; y++) {
                        let item2 = data[i].task_list[y]
                        var img = '../static/images/icon_huang.gif';
                        /**
                         * abnormal_count > 0 ----- 异常
                         * test_count == total_count ----- 已检
                         * test_count < total_count -----在检
                         */
                        if (item2.abnormal_count > 0) {
                            img = 'icon_hong.gif';
                        } else if (item2.test_count == item2.total_count) {
                            img = 'icon_lv.gif';
                        } else if (item2.test_count < item2.total_count) {
                            img = 'icon_huang.gif';
                        }
                        var marker = new AMap.Marker({
                            position: [item2.mapx, item2.mapy],
                            icon: new AMap.Icon({
                                size: new AMap.Size(28, 28),
                                image: '../static/images/' + img
                            }),
                            map: map
                        });
                        marker.content = `<p class="info-item" onclick="detail.getData('${data[i].project_id}')">${data[i].project_name}</p>`;
                        marker.on('mouseover', infoOpen);
                        marker.on('click', newMAp);
                    }
                }
                map.setZoomAndCenter(7, [Number(data[0].task_list[0].mapx), Number(data[0].task_list[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());
            }

            $("#rwList .item-head").click(function () {
                var mapx = $(this).attr('data-mapx');
                var mapy = $(this).attr('data-mapy');
                var index = Number($(this).attr('data-index'));
                var item = taskList.data[index];
                if (mapx && mapy) {
                    map.setZoomAndCenter(12, [Number(mapx), Number(mapy)]);
                    infoWindow.setContent(`<p class="info-item" onclick="detail.getData('${item.project_id}')">${item.project_name}</p>`);
                    infoWindow.open(map, { Q: Number(mapy), R: Number(mapx), lat: Number(mapy), lng: Number(mapx) });
                }
            })
            map.setMapStyle('amap://styles/d3ce37d9fe39b7cc5f08f48af52802a2');
        })
    },
}

var detail = {
    data: [],
    ysjl_list: [],
    getData: function (project_id) {
        let _this = this;
        $.ajax({
            url: baseURL_htjc + "GetTaskInfo.ashx",
            type: "post",
            dataType: "json",
            data: {
                project_id
            },
            success: function (data) {
                if (data.data && data.data.length > 0) {
                    _this.setLeftData(data.data);
                } else {
                    $("#subrwList").html('<div class="noData">暂无数据</div>');
                }
            },
            error: function (jqXHR) {
                $("#subrwList").html('<div class="noData">暂无数据</div>');
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setLeftData: function (data) {
        this.data = data;
        var str = '';
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            str += `
                <div class="info-item">
                    <div id="subrwInfo-${i}">
                        <div class="item-head" onclick="detail.setRightData('${i}', 'subrwInfo-${i}')">
                            <div class="flex-item">
                                <div class="icon ${item.abnormal_count > 0 ? 'showTip' : ''}"><img src="../static/images/icon_rwd.png"/></div>
                                任务单：${item.task_no}
                            </div>
                            <div class="flex-item">
                                <div class="icon icon2"><img src="../static/images/jiantou.png"/></div>
                            </div>
                        </div>
                        <div class="item-tab"><div>已检测：${item.test_count}</div><div>强度不达标：${item.abnormal_count}</div><div>未检测：${item.untest_count}</div></div>
                   
                        <div class="item-main hidden">
                            ${item.sample_list.map((item2, index2) => {
                return (`<div class="flex-item" onclick="detail.getsubRightData('${item2.sample_id}', '${i}','${index2}')"><p>${item2.sample_name}</p><p class="desc ${item2.test_status == 1 ? 'green' : item2.test_status == 2 ? 'red' : ''}">${item2.test_status_str}</p></div>`); //0未检测 1已检测 2强度不达标
            }).join('')
                }
                        </div>
                    </div>
                </div>
            `;
        }
        $("#popup-info .left-item").html(str);
        this.setRightData(0, 'subrwInfo-0');
        this.showPopup();
    },
    setRightData(index, id) {
        sublistClick(id);
        var item = this.data[index];
        $("#subrwList .info-item").removeClass("active");
        $("#subrwList .flex-item").removeClass("active");
        $("#popup-info .info-item:nth-child(" + (index + 1) + ")").addClass("active");
        $("#popup-info .head").html(`${item.project_no ? '【' + item.project_no + '】' : ''}${item.project_name}`);
        $("#popup-info .right-item1").html(`
            <div class="main-item1">
                <div class="flex-item"><div class="value">任务单号：${item.task_no}</div><div class="value">检测单位：${item.customer_name}</div></div>
                <div class="flex-item"><div class="value">开始时间：${item.test_begin_datetime}</div><div class="value">最近数据上传：${item.test_end_datetime}</div></div>
                ${item.report_file && `<div class="flex-item"><div class="value">回弹文件：<a href="${item.report_file}" style="color:#C0D3E6">点击查看</a></div></div>`
            }
                <div class="flex-item flex-item2 over-flex">
                    ${item.faceimg_list.map((item2) => {
                return (`
                                <div class="box">
                                    <div class="img">
                                        <img src="${item2.image_url}" />
                                    </div>
                                    <div class="item">
                                        <div class="type"><p class="name">人脸识别</p><p>${item2.op_name}</p></div>
                                        <div class="time">${item2.datatime}</div>
                                    </div>
                                </div>
                            `);
            }).join('')
            }
                </div>
            </div>
            <div class="main-item">
                <div class="ma-i">
                    ${item.flow_list.length > 0 ?
                item.flow_list.map((item2, index2) => {
                    return (`
                                <div class="item">
                                    <div class="value">
                                        <div class="blue">第${index2 + 1}步 / ${item2.flowpath_no_str}</div>
                                        <div>检测人员：${item2.op_name}</div>
                                        <div>${item2.create_time}</div>
                                    </div>
                                    <div class="imgArr">
                                        ${item2.file_list.map((item3, index3) => {
                        return (`
                                                    <img src="${item3.file_path}" onclick="detail.imgView('${index}','${index2}','${index3}')"/>
                                                `);
                    }).join('')
                        }
                                    </div>
                                </div>
                            `);
                }).join('')
                : '<div class="noData">暂无数据</div>'
            }
                </div>
            </div>
        `);
        $("#popup-info .right-item2").addClass("hiddenImportant");
        $("#popup-info .right-item1").removeClass("hiddenImportant");
    },
    getsubRightData(sample_id, index, index2) {
        console.log(sample_id, index, index2);
        let _this = this;
        $.ajax({
            url: baseURL_htjc + "GetPartInfo.ashx",
            type: "post",
            dataType: "json",
            data: {
                sample_id
            },
            success: function (data) {
                if (data.data) {
                    _this.setsubRightData(index, index2, data.data);
                } else {
                    // $("#subrwList").html('<div class="noData">暂无数据</div>');
                }
            },
            error: function (jqXHR) {
                // $("#subrwList").html('<div class="noData">暂无数据</div>');
                console.log("发生错误：" + jqXHR.status);
            }
        })
    },
    setsubRightData(index, index2, data) {
        console.log(index, index2);
        console.log(data);
        $("#subrwList .info-item").removeClass("active");
        $("#subrwList .flex-item").removeClass("active");
        $("#subrwList .info-item:nth-child(" + (index + 1) + ") .flex-item:nth-child(" + (index2 + 1) + ")").addClass("active");
        $("#popup-info .right-item1").addClass("hiddenImportant");
        $("#popup-info .right-item2").removeClass("hiddenImportant");
        var item = data[0];
        this.ysjl_list = item.ysjl_list;
        $("#popup-info .right-item2").html(`
            <div class="flex-item"><div class="value">任务单号：${item.task_no}</div><div class="value">检测单位：${item.customer_name}</div></div>
            <div class="name-item">${item.sample_name}</div>
            <div class="info-item">
                <div class="desc"><p>设计强度：${item.sjqd}</p><p>强度推定值MPa：${item.tdz} / <span class="${item.test_status == 1 ? 'green' : item.test_status == 2 ? 'red' : ''}">${item.test_status_str}</span></p></div>
                <div class="bw-item">
                    ${item.ysjl_list.length > 0 ?
                item.ysjl_list.map((item2, index2) => {
                    return (`
                                <div class="item" onmouseover="mouseover(${index2}, event)" onmouseout="mouseout()">${item2.jc_data21}</div>
                            `);
                }).join('')
                : '<div class="noData">暂无数据</div>'
            }
                </div>
                <div class="sub-desc"><p>检测人员：${item.op_name || '/'}</p><p>检测时间：${item.test_datetime || '/'}</p><p>检测设备：${item.equ_no || '/'}</p></div>
            </div>
        `);
    },
    showPopup: function () {
        layer.open({
            type: 1,
            shadeClose: true,
            maxmin: true,
            title: "<p class='popup-title'>工程回弹数据详情</p>",
            area: ['13rem', '75%'],
            content: $('#popup-info'),
            end: function () {
                $("#popup-info").css('display', 'none');
            }
        });
    },
    imgView(index, index2, index3) {
        var arr = this.data[index].flow_list[index2].file_list;
        $("#swiper .swiper-wrapper").html("");
        $("#swiper").removeClass("hidden");
        for (var i = 0; i < arr.length; i++) {
            $("#swiper .swiper-wrapper").append('<div class="swiper-slide"><img src="' + arr[i].file_path + '" /></div>');
        }
        var mySwiper = new Swiper('.swiper-container', {
            navigation: {
                nextEl: '.swiper-button-next',
                prevEl: '.swiper-button-prev',
            },
            observer: true,
            observeParents: true,
            initialSlide: index3
        });
    },
    swiperHide() {
        $("#swiper").addClass("hidden");
    }
}

function mouseover(index, e) {
    var arr = [];
    for (i in detail.ysjl_list[index]) {
        if (i != 'jc_data21' && i != 'test_status') {
            arr.push(detail.ysjl_list[index][i]);
        }
    }
    $("#hoverInfo").html(`
        ${arr.map(item2 => {
        return (`
                    <div>${item2}</div>
                `);
    }).join('')
        }
    `);
    setTimeout(() => {
        var divW = $("#hoverInfo").width();
        var screenW = $(window).width();
        if (e.clientX + divW > screenW) {
            $("#hoverInfo").css("left", 'auto').css("right", 0).css("top", e.clientY + 10 + 'px').removeClass("hidden");
        } else {
            $("#hoverInfo").css("left", e.clientX + 10 + 'px').css("right", 'auto').css("top", e.clientY + 10 + 'px').removeClass("hidden");
        }
    }, 50);
}
function mouseout() {
    setTimeout(() => {
        $("#hoverInfo").addClass("hidden").css("left", 0).css("right", 0).css("top", 0);
    }, 50);
}

function listClick(id) {
    var flag = $("#" + id + " .item-main").hasClass("hidden");
    $("#rwList .item-head").removeClass("active");
    $("#" + id + " .item-head").addClass("active");
    if (flag) {
        $("#rwList .item-main").addClass("hidden");
        $("#rwList .item-head").removeClass("headHover");
        $("#" + id + " .item-head").addClass("headHover");
        $("#" + id + " .item-main").removeClass("hidden");
    } else {
        $("#rwList .item-head").removeClass("headHover");
        $("#rwList .item-main").addClass("hidden");
    }
}

function sublistClick(id) {
    var flag = $("#" + id + " .item-main").hasClass("hidden");
    if (flag) {
        $("#subrwList .item-main").addClass("hidden");
        $("#subrwList .item-head").removeClass("headHover");
        $("#" + id + " .item-head").addClass("headHover");
        $("#" + id + " .item-main").removeClass("hidden");
    } else {
        $("#subrwList .item-head").removeClass("headHover");
        $("#subrwList .item-main").addClass("hidden");
    }
}

init();
function init() {
    getHeader();
    layui.use(['layer', 'laydate'], function () {
        var laydate = layui.laydate;
        laydateObj = laydate.render({
            elem: '#rw-date'
            , value: getNextDate(dateFormat('YYYY-mm-dd', new Date()), 0)
            , done: function () {
                taskList.init();
            }
        });
    })
    taskList.init();
    testCount.init();
}