var windowId, proName = window.location.pathname.split("/")[1],
var date = new Date();
var nowDate = date.getFullYear() + "-" + (date.getMonth() + 1);
var flag = true;
var pageSizeIn
    sysUrl = "http://" + window.location.host + "/" + proName, toEdit;
var records = [];it = 10;
var treeSelectId = "-1";
$(function () {
    $("#datetimeStart").datebox("setValue", $.getTodayStart(0, ""));
    $("#datetimeEnd").datebox("setValue", $.getTodayEnd(""));
    $("#lb").combobox({
        onChange: function (n, o) {
            if (n == "1") {
                $("#treediv").show();
                initTree();
            } else {
                $("#treediv").hide();
            }

        }
    });
    initGrid();
    initTree();
//	initCountTime();
  //  initXzNameTree();
});

//加载列表
function initGrid() {
    showList(null,null);
}

function initTree() {
    $.ajax({
        type: 'post',
        dataType: 'json',
        url: 'ptxzsAction!query_PtxzsTree.do',
        data: {
            order: " order by jdpx asc "
        },
        success: function (data) {
            var setting = {
                data: {
                    key: {title: "name"}
                },
                callback: {
                    onClick: zTreeOnClick
                }
            };
            if (data) {
                $.fn.zTree.init($("#xzTree"), setting, data);
            }
        }
    });

}

function zTreeOnClick(event, treeid, treeNode) {
    treeSelectId = treeNode.id;
}

//加载统计时间
function initCountTime() {
    var flag = false;
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var str = year + "年" + month + "月";
    var result = [12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1];
    result = result.filter(function (value) {
        if (month == value) {
            flag = true;
        }
        if (flag) {
            if (value < 10) {
                return "0" + value;
            } else {
                return "" + value;
            }
        }
    });
    $.each(result, function (i, v) {
        result[i] = year + "年" + result[i] + "月";
    });
    result.unshift("自定义时间");
    $('#countTime').combobox({
        data: $.obj2ary(result),
        textField: 1,
        valueField: 0,
        panelWidth: 148,
        value: str,
        onSelect: function (record) {
            var value = record[1].trim();
            if (value == '自定义时间') {
                $("#controlDate").show();
            } else {
                $("#controlDate").hide();
            }
        }
    });
}


//查询条件
function getQueryParams() {

    var sParam = {};

//	sParam.page = 1;
//	sParam.rows = 1000;
    var LIKEfaultdevicename = $('#LIKEfaultdevicename').val();
    sParam.order = "order by areanum desc,devicenum ,channelnum ";
    var datetimeStart = $('#datetimeStart').datebox("getValue");
    var datetimeEnd = $('#datetimeEnd').datebox("getValue");
    var range = $('#range').textbox("getValue");

    var tableparam = "";
    if (!(datetimeStart == null || datetimeStart == "" || datetimeStart == undefined)) {
        tableparam += " AND createtime  >= '" + datetimeStart + "'";
    }
    if (!(datetimeEnd == null || datetimeEnd == "" || datetimeEnd == undefined)) {
        tableparam += " AND createtime  <= '" + datetimeEnd + "'";
    }
    if (!(range == null || range == "" || range == undefined)) {
        sParam.range = range;
    }
    sParam.faultdevicetype = $("#lb").combobox('getValue');
    if ($("#lb").combobox('getValue') == "1") {
        sParam.videoTreeid = treeSelectId;
    }
    sParam.tableparam = tableparam;
    return sParam;
}

//列表展示
function showList(page, rows) {
    var  lb=$("#lb").combobox('getValue');
    if (lb=="0") {
        alert("请选择设备类型！");
        return;
    }
    $("#searchGridListDiv").show();
    $("#searchGridPicDiv").hide();
    displayType = "list";
    var params = getQueryParams();
    if (page == undefined || page == null) {       // 页码
        if ($('#pp .l-btn-selected .l-btn-text').text().trim()) {
            page = parseInt($('#pp .l-btn-selected .l-btn-text').text().trim());
        } else {
            page = 1;
        }
    }
    if (rows == undefined || rows == null) {       //每页10条
        if ($('#pp .pagination-page-list').val()) {
            rows = parseInt($('#pp .pagination-page-list').val());
        } else {
            rows = 10;
        }
    }
    params.page = page;
    params.rows = rows;
    var  url_str="";
    //监控
    if (lb=="1") {
      url_str=  'ywrepairjobinfoAction!countYwrepairjobinstent.do'
    }else  if (lb=="2") {
        url_str=  'ywrepairjobinfoAction!countYwrepairjobMachineInstent.do'
    }

    $.ajax({
        type: 'post',
        dateType: 'json',
        url: url_str,
        data: params,
        success: function (res) {
            renderTable(res, page, rows);
        }
    });
}


function renderTable(res, page, limit) {
    var table = '';
    if (res) {
        var rows = res.rows;
        $("#timeTJ").text("制表时间：" + getCurrtentTime())
        var monitorSum = 0, invalidlalSum = 0, laldefectSum = 0, lalcompleteSum = 0, nolalSum = 0;
        if (rows.length > 0) {
            for (var i = 0; i < rows.length; i++) {
                table += '<tr>\
				<td>' + ((page - 1) * limit + (i + 1)) + '</td>\
				<td>' + transformateEmpty(rows[i].xzbh) + '</td>\
				<td>' + transformateEmpty(rows[i].xzmc) + '</td>\
                <td>' + transformateEmpty(rows[i].sbbh) + '</td>\
				<td>' + transformateEmpty(rows[i].tdmc) + '</td>\
                <td>' + transformateEmpty(rows[i].cnt) + '</td>\
                <td>' + transformateEmpty(rows[i].uncnt) + '</td>\
				<td>' + getpercent(rows[i].cnt, rows[i].uncnt) + '</td>\
				<tr>'
            }
        } else {
            table += '<tr> <td colspan="8">暂无数据</td> <tr>';
        }
    }

    function getpercent(cnt, uncnt) {
        if (cnt != "0") {
            var curNum = cnt == null ? 0 : parseFloat(cnt);
            var curunNum = uncnt == null ? 0 : parseFloat(uncnt);
            var totalNum = curNum + curunNum;
            return totalNum <= 0 ? '0%' : (Math.round(curNum / totalNum * 10000) / 100.00 + '%');
        } else {
            return '0%'
        }
    }

    $("#searchGridList").html(table);
    var total = 0;
    if (res && res.total > 0) {
        total = res.total;
    }
    $('#pp').pagination({
        total: total,
        showRefresh: true,
        pageSize: pageSizeInit,
        pageList: [10, 20, 30, 50, 100],
        onSelectPage: function (pageNumber, pageSize) {
            $(this).pagination('loading');
            $(this).pagination('loaded');
            showList(pageNumber, pageSize)
            pageSizeInit = pageSize;
        }
    });
}

function transStr2Int(str) {
    if (str) {
        return parseInt(str);
    } else {
        return 0;
    }
}

//导出
function doExport(type) {
    var model = getQueryParams();
//	execExport();
    $.ajax({
        type: 'post',
        dateType: 'json',
        url: 'ywcountvideoappraiseAction!count_Ywcountvideoappraise.do',
        data: model,
        success: function (res) {
            if (res) {
                countExport(res, type);
            } else {
                $.showMsg("暂无数据");
            }
        }
    });
}

// 导出传参条件
function countExport(totalSize, type) {
    var limit = 5000;
    if (totalSize > 5000) {
        top.$.dlg.confirm('记录过多支持前5000条,确定要将记录导出Excel为表格吗?', function () {
            execExport(type);
        });
    } else {
        top.$.dlg.confirm('确认导出?', function () {
            execExport(type);
        })
    }
}

// 调用后台
function execExport(type) {
    var downParams = JSON.stringify(getQueryParams());
    if (type == "pdf") {
        document.excelForm.action = 'ywcountvideoappraiseAction!expPDF_Ywcountvideoappraise_online.do?downParam=' + encodeURIComponent(downParams);
    } else {
        document.excelForm.action = 'ywcountvideoappraiseAction!exp_Ywcountvideoappraise_online.do?downParam=' + encodeURIComponent(downParams);
    }
    document.excelForm.submit();
}

function getCurrtentTime() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    if (hour < 10) {
        hour = "0" + hour;
    }
    if (minute < 10) {
        minute = "0" + minute;
    }
    if (second < 10) {
        second = "0" + second;
    }
    console.log(year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second);
    return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
}

function transformateEmpty(str) {
    if (!str || str == null || str == "null") {
        return "-";
    }
    return str;
}

function dayin() {
    var userAgent = navigator.userAgent.toLowerCase(); //取得浏览器的userAgent字符串
    if (userAgent.indexOf("trident") > -1) {
        alert("请使用google或者360浏览器打印");
        return false;
    } else if (userAgent.indexOf('msie') > -1) {
        var onlyChoseAlert = simpleAlert({
            "content": "请使用Google或者360浏览器打印",
            "buttons": {
                "确定": function () {
                    onlyChoseAlert.close();
                }
            }
        })
        alert("请使用google或者360浏览器打印");
        return false;
    } else {//其它浏览器使用lodop

        var params = getQueryParams();
        var data = {};
        params.rows = 10000;
        params.page = 1;
        $.ajax({
            type: 'post',
            dateType: 'json',
            url: 'ywcountvideoappraiseAction!listYwcountvideoappraiseByPage.do',
            data: params,
            async: false,
            success: function (res) {
//				console.log("打印：",res);
                if (res == null) {
                    $.showMsg("暂无数据！");
                    return;
                } else {
                    if (res.total > 0) {
                        data = res;
                    } else {
//						console.log("返回");
                        $.showMsg('暂无记录!');
                        return;
                    }
                }

            }
        })


        var res = data;
        total = res.total;

        var table = '';
        if (res && res.total > 0) {
            table = '<table  cellspacing="0"  width="100%"  cellpadding="0"  border="1"  align="center"  style="text-align:center;margin:0 auto;	border:1px solid #827d7d;font-size:12px;">' +
                '<thead>' +
                '<tr>' +
                '<td colspan="6" style="font-size:14px;font-weight:bold;border:none">离线时长统计</td>' +
                '</tr>' +
                '<tr style="border-top: 1px solid #827d7d;">' +
                '<td id="timeTJ" colspan="6" style="text-align:right;border:none;padding: 15px;">制表时间：2018-12-28 14:11:49</td>' +
                '</tr>' +
                '<tr>' +
                '<th >序号</th>' +
                '<th >监控点名称</th>' +
                '<th >行政区划</th>' +
                '<th >IP地址</th>' +
                '<th >离线时间（小时）</th>' +
                '<th >离线开始时间</th>' +
                '</tr>' +
                '</thead>';

            var rows = res.rows;
            $("#timeTJ").text("制表时间：" + getCurrtentTime())
            var monitorSum = 0, invalidlalSum = 0, laldefectSum = 0, lalcompleteSum = 0, nolalSum = 0;
            for (var i = 0; i < rows.length; i++) {

                table += '<tr>\
					<td>' + (i + 1) + '</td>\
					<td>' + transformateEmpty(rows[i].videoname) + '</td>\
					<td>' + transformateEmpty(rows[i].areaname) + '</td>\
					<td>' + transformateEmpty(rows[i].ipaddress) + '</td>\
					<td>' + rows[i].lxsc + '</td>\
					<td>' + transformateEmpty(rows[i].lxstarttime) + '</td>\
					<tr>'
            }

        } else {
            return;
        }
        table += '</tbody></table>'

        var headstr = "<html><head><title></title></head><body>";
        var footstr = "</body></html>";

        var wind = window.open("", "newwin", "toolbar=no,scrollbars=yes,menubar=no");
        wind.document.body.innerHTML = headstr + table + footstr;
        wind.print();

        wind.close();

    }

}

function showGraph() {
    $("#searchGridPicDiv").show();
    $("#searchGridListDiv").hide();
    var  lb=$("#lb").combobox('getValue');
    var  url_str="";
    if (lb=="1") {
        url_str=  'ywrepairjobinfoAction!countYwrepairjobinstent.do'
    }else  if (lb=="2") {
        url_str=  'ywrepairjobinfoAction!countYwrepairjobMachineInstent.do'
    }
    $.ajax({
        type: 'post',
        dateType: 'json',
        url:url_str,
        data: getQueryParams(),
        success: function (res) {
            if (res) {
                $("#noData").css("display", "none");
                $("#searchGridGraph").css("display", "block");
                var x = [];
                var recordnormalnum = [];
                var recordabnormalnum = [];
                var totalnum = [];
                var rows = res.rows
                for (var i = 0; i < rows.length - 1; i++) {
                    x.push(transformateEmpty(rows[i].xzmc));
                    recordnormalnum.push(transStr2Int(rows[i].cnt));
                    recordabnormalnum.push(transStr2Int(rows[i].uncnt));
//					totalnum.push(transStr2Int(rows[i].totalNum));
                }
                var data = {
                    "title": "及时维护率统计",
                    xAxis: x,//["监控","NVR","服务器","应用系统"],
                    "legend": [
//						          {"name":"在线数", "data":zxnum,"color":"yellow"},
//						          {"name":"录像总数","data":totalnum,"color":"blue"},
                        {"name": "及时维护数", "data": recordnormalnum, "color": "green"},
                        {"name": "未及时维护数", "data": recordabnormalnum, "color": "gray"},
                    ]
                };
                EchartsBase.barChart({
                    id: "searchGridGraph",
                    data: data
                });
            } else {
                $("#noData").css("display", "block");
                $("#searchGridGraph").css("display", "none");
            }
        }
    });
}