var height = $(window).height();
var arr = [];//选中的设备id
var devNameArr = [];
var percent; //进度条
var devarr = [] //当前后台有返回的装置集合
var edArr = [] //版本ig集合
var succee = 0;//升级成功的终端数量
var fail = 0;
var cancel = 0;
var dataTable;
var restartNum; //重启的装置数量
var restartSuccedNum;//重启成功的装置数量
var websocket = window.parent.parent.webSocket
var edId;
var restartArr = [];//重启装置id数组
var devEdHisAndNow = [];//升级装置的历史版本
var dateUp = [];//用于存储版本日期
var restartLoad = null; //重启loading控制
var hasEndDev;
$(function () {
    $(".div_height").css("height", height - 70);
    getDeviceType()
    getDeviceSeries()

    refresh();

    $("[data-toggle='popover']").popover();

    $('#progress').removeClass('running');

    $('.trigger').click(function () {
        $('#progress').removeClass('running').delay(10).queue(function (next) {
            $(this).addClass('running');
            next();
        });
        return false;
    });


    websocket.onmessage = function (evnt) {

        if (evnt.data != "") {
            //data数据体后的长度
            var info = JSON.parse(evnt.data)
            console.log(info)
            if (info.type == 180) {

                $('.loading-div').remove()
                if (info.resultcode == 10000) {
                    let da = info.data
                    if (info.data === undefined) {

                    } else {
                        //存在关闭游览器后重新打开和正常操作两种情况
                        if (percent == null) {
                            showPercent()
                        }

                        /*  let flag = devarr.find(function (value) {
                              return value == da.devIndex
                          })
                          if (!flag) {
                              devarr.push(da.devIndex)
                              let str = '<div class="row">' +
                                  '<label class="col-sm-4" style="padding-right: 0px;">' + da.devName.substring(0, 12) + '</label>' +
                                  '<div class="col-sm-6" style="padding: 2px 5px 0px 3px">' +
                                  '<div class="process-bar">' +
                                  '<div class="pb-wrapper">' +
                                  '<div class="pb-highlight"></div>' +
                                  '<div class="pb-container">' +
                                  '<div class="pb-text">1%</div>' +
                                  '<div value="' + da.devIndex + '" flag="0" perce="0" class="pb-value themeBGColor" style="width:1%"></div>' +
                                  '</div>' +
                                  '</div>' +
                                  '</div>' +
                                  '</div>' +
                                  '<div class="col-sm-2 cancelSet" style="padding-left: 0px;padding-right: 5px; padding-top:1.5px;display: none"><a href="#" data-toggle="popover" title=""><span onclick="startCancel(' + da.devIndex + ')" value="' + da.devIndex + '" class="glyphicon glyphicon-minus-sign"  style="color:rgb(255,170,0); font-size: 14px;"></span></a></div>' +
                                  '<div class="col-sm-2 errorSet" style="padding-left: 0px;padding-right: 5px; padding-top:1.5px;display: none"><a href="#" data-toggle="popover" title=""><span class="glyphicon glyphicon-question-sign"  style="color: rgb(255,0,0); font-size: 14px;"></span></a></div>' +
                                  '</div>'
                              $('#loading').append(str)
                          }*/


                        $('.process-bar').each(function () {
                            if ($(this).find('.pb-value').attr('value') == da.devIndex) {
                                $(this).find('.pb-value').css('width', da.percent + '%')
                                $(this).find('.pb-text').text(da.percent + '%')
                                $(this).find('.pb-value').attr('perce', da.percent)
                                if (da.state == 0) {
                                    $('#title').empty()
                                    $('#title').text('正在预加载......')
                                } else if (da.state == 1) {
                                    $(this).find('.pb-value').attr("flag", 1)
                                    $('#title').empty()
                                    $('#title').text('正在下装版本......')
                                    if (da.percent == 99) {
                                        //校验阶段
                                        $('#title').text(da.devName + '正在校验......')
                                    }


                                    //展示取消按钮
                                    if (da.percent > 0 && da.percent < 90) {
                                        $(this).parent().parent().find('.cancelSet').show()
                                        if (fail == 0 && succee == 0 && cancel == 0) {
                                            $('#batchCancel').show();
                                        }
                                        $('.process-bar').each(function () {
                                            let that = this
                                            let per = $(that).find('.pb-value').attr('perce')
                                            if (per == 0 || per >= 90) {
                                                $('#batchCancel').hide();
                                            }
                                        })
                                    } else {
                                        $('#batchCancel').hide();
                                        $(this).parent().parent().find('.cancelSet').hide()
                                    }


                                } else if (da.state == 2) {
                                    $(this).find('.pb-value').attr("flag", 2)
                                    succee++;
                                    $(this).parent().parent().find('.cancelSet').hide()
                                } else if (da.state == 3) {
                                    $(this).find('.pb-value').attr("flag", 3)
                                    temptPercent(info.data, '出错了')
                                }


                            }
                        })
                    }
                } else if (info.resultcode == -10000) {
                    hasEndDev += info.data.length
                    if(arr.length ==hasEndDev ){
                        //后台返回程序升级流程结束
                        let fails = arr.length - succee - cancel
                        $('#title').empty()
                        $('#title').html('<sapn style="font-size: 12px;font-weight: 500;font-family: normal">' + '成功：' + '<span style="color: #0c7cb5">' + succee + '</span>' + '台 失败: ' + '<span style="color: red">' + fails + '</span>' + '台' + '</span>')
                        $('#buttons').empty()
                        $('#buttons').css('padding', '3px').append('<button type="button" id="closeId" onclick="closePercent()" class="btn btn-primary mb5">重新升级</button>')

                        if (succee > 0) {
                            $('#buttons').append('<button type="button" id="reload" onclick="reloadController()" class="btn btn-primary ml10 mb5">重启</button>')
                        }
                    }



                } else if (info.resultcode == 100 || info.resultcode == 101 || info.resultcode == 102) {

                    let dataArr = info.data
                    if (percent == null) {
                        showPercent()
                    }

                    /* for (let i = 0; i < dataArr.length; i++) {

                         let flag = devarr.find(function (value) {
                             return value == dataArr[i].devIndex
                         })
                         if (!flag) {
                             devarr.push(dataArr[i].devIndex)
                             let str = '<div class="row">' +
                                 '<label class="col-sm-4" style="padding-right: 0px;font-size:10px ">' + dataArr[i].devName.substring(0, 12) + '</label>' +
                                 '<div class="col-sm-6" style="padding: 2px 5px 0px 3px">' +
                                 '<div class="process-bar">' +
                                 '<div class="pb-wrapper">' +
                                 '<div class="pb-highlight"></div>' +
                                 '<div class="pb-container">' +
                                 '<div class="pb-text">1%</div>' +
                                 '<div value="' + dataArr[i].devIndex + '" flag="3" class="pb-value themeBGColor" style="width:1%"></div>' +
                                 '</div>' +
                                 '</div>' +
                                 '</div>' +
                                 '</div>' +
                                 '<div class="col-sm-2 errorSet" style="padding-left: 0px;padding-right: 5px;display: none"><a href="#" data-toggle="popover" title=""><span class="glyphicon glyphicon-question-sign"  style="color: rgb(255, 0, 0); font-size: 14px;"></span></a></div>' +
                                 '</div>'
                             $('#loading').append(str)

                         }

                     }*/


                    $('.process-bar').each(function () {
                        let that = this
                        dataArr.forEach(function (item) {

                            if ($(that).find('.pb-value').attr('value') == item.devIndex) {
                                $(that).find('.pb-value').attr('flag', 3)
                                if ($(that).find('.pb-value').attr('flag') == 3) {
                                    $(that).parent().parent().find('.errorSet').show()
                                    $(that).parent().parent().find('.errorSet').find('a').attr('title', '连接前置机异常')
                                }
                                fail++
                            }
                        })

                    })
                    $('.loading-div').remove()
                    $('.cancelSet').hide()
                } else if (info.resultcode == 99990) {
                    let da = info.data
                    temptPercent(da, '终端重启文件校验重复,联系管理员修改')
                } else if (info.resultcode == 99999) {
                    //超时
                    let da = info.data
                    temptPercent(da, '超时')
                } else if (info.resultcode == 99991) {
                    //CRC校验异常
                    let da = info.data
                    temptPercent(da, 'CRC校验异常')
                } else if (info.resultcode == 99992) {
                    //未知异常
                    let da = info.data
                    temptPercent(da, '未知异常')
                } else if (info.resultcode == 99993 || info.resultcode == 99995) {
                    //文件传送异常
                    let da = info.data
                    temptPercent(da, '文件传送异常')
                } else if (info.resultcode == 99994) {
                    //超时
                    let da = info.data
                    temptPercent(da, '文件传送异常')
                } else if (info.resultcode == 99996) {
                    //超时
                    let da = info.data
                    temptPercent(da, '预升级异常')
                } else if (info.resultcode == 99997) {
                    //超时
                    let da = info.data
                    temptPercent(da, '读取数据库失败')
                } else if (info.resultcode == 99998) {
                    //超时
                    let da = info.data
                    temptPercent(da, '数据库读取无数据')
                } else if (info.resultcode == 99989) {
                    let da = info.data
                    temptPercent(da, '版本类型与终端类型不一致')
                } else if (info.resultcode == 10003) {
                    layer.msg("JSON字符串解析出错", {
                        icon: 5,
                        time: 3000
                    });
                } else if (info.resultcode == 10004) {
                    layer.msg("socket处理出现异常", {
                        icon: 5,
                        time: 3000
                    });
                } else if (info.resultcode == 10005) {
                    let da = info.data
                    temptPercent(da, '对应ID装置未找到')
                } else if (info.resultcode == 10008) {
                    layer.msg('当前存在终端正在升级，请勿重复操作', {icon: 2, time: 2000})
                } else if (info.resultcode == 10009) {
                    layer.msg('存在正在升级程序,请勿重复操作')
                } else if (info.resultcode == 99988) {
                    let da = info.data
                    temptPercent(da, '通讯超时')
                } else if (info.resultcode == 77777) {
                    layer.msg("socket连接超时，请联系管理员排查", {
                        icon: 5,
                        time: 3000
                    });
                } else {
                    layer.msg("socket连接异常", {
                        icon: 5,
                        time: 3000
                    });
                }

                if (fail != 0 || succee != 0 || cancel != 0) {
                    //已经全部加载出来放开全部取消按钮
                    $('#batchCancel').hide();
                }

                $('.process-bar').each(function () {
                    let that = this
                    if ($(that).find('.pb-value').attr('flag') != 1) {
                        $('#batchCancel').hide();
                    }

                })


            } else if (info.type == 181) {
                //重启命令

               // console.log(info.data.devName + "重启成功")
                if (percent != null) {
                    layer.close(percent)
                }

                let html = "<tr devIndex =\"{{3}}\" devName = \"{{2}}\"><td style='padding: 0px 20px 0px 20px;width: 280px'><div style='padding: 5px 15px 5px 15px;margin-bottom: 10px' class=\"alert alert-success\">\n" +
                    "\t<strong>{{1}}</strong>" +
                    "</div></td></tr>"
                let htmls = "<tr devIndex =\"{{3}}\" devName = \"{{2}}\"><td style='padding: 0px 20px 0px 20px;width: 280px'><div style='padding: 5px 15px 5px 15px;margin-bottom: 10px' class=\"alert alert-danger\">\n" +
                    "\t<strong>{{1}}</strong>" +
                    "</div></td></tr>"


                if (info.resultcode == 10000) {
                    if (restartLoad == null) {
                        restartLoad = layer.open({
                            type: 1
                            , title: false //不显示标题栏
                            , closeBtn: false
                            , area: '300px;'
                            , shade: 0.8
                            , id: 'LAY_Id' //设定一个id，防止重复弹出
                            , btnAlign: 'c'
                            , moveType: 1 //拖拽模式，0或者1
                            , content: '<div  style="padding: 5px 10px 10px 5px"><div class="loading-div">' +
                                '<i class="fa fa-spinner fa-pulse fa-3x fa-fw "></i>' +
                                '<span id="reTitle">正在重启装置...</span>' +
                                '</div><table id="msgInfo"></table><div style="text-align: center"><button class="btn-primary btn" id="aeert" onclick="closeAndRefrsh()" style="display: none">确认</button></div></div>'
                        });
                    }
                    $('#msgInfo').append(html.replace('{{1}}', info.data.devName + '正在重启').replace('{{2}}', info.data.devName).replace('{{3}}', info.data.devIndex))
                    restartNum++;
                    restartArr.push(info.data.devIndex)
                } else if (info.resultcode == 10001) {
                    restartSuccedNum++;
                    console.log("重启成功-------------" + info.data.devIndex)
                    $('#msgInfo').find("tr").each(function () {
                        let that = this
                        let devIndex = $(that).attr('devIndex')
                        if (devIndex == info.data.devIndex) {
                            $(that).find("td").find("strong").text(info.data.devName + "装置重启成功")
                        }
                    })
                } else if (info.resultcode == 99988) {
                    restartSuccedNum++;
                    $('#msgInfo').find("tr").each(function () {
                        let that = this
                        let devIndex = $(that).attr('devIndex')
                        if (devIndex == info.data.devIndex) {
                            $(that).find("td").find("strong").text(info.data.devName + "装置重启超时")
                            $(that).find("td").find("div").attr("class", "alert alert-danger")
                        }
                    })
                } else {
                    $('#msgInfo').append(htmls.replace('{{1}}', info.resultmsg))
                }


                if (restartNum != 0) {
                    if (restartNum == restartSuccedNum) {
                        console.log("全部重启成功,进行判断是否版本升级成功")

                        window.setTimeout(function () {
                            $.ajax({
                                method: "post",
                                url: "/pqs9900/version/upFlag",
                                data: JSON.stringify(restartArr),
                                dataType: 'json',
                                contentType: 'application/json;charset=UTF-8',
                                beforeSend: function () {

                                },
                                success: function (data) {
                                    if (data.code == 200) {
                                        let da = data.body
                                        let devUpDetail = []


                                        $('#msgInfo').find("tr").each(function () {
                                            let that = this
                                            let devIndex = $(that).attr('devIndex')
                                            for (let i = 0; i < da.length; i++) {
                                                if (da[i].devIndex == devIndex) {
                                                    let edHis = null;
                                                    devEdHisAndNow.forEach(function (item) {
                                                        if (item.dev == devIndex) {
                                                            edHis = item.ed
                                                        }
                                                    })

                                                    let name = $(that).attr("devName")
                                                    let obj;
                                                    if (da[i].edIndex != edHis) {
                                                        obj = {
                                                            dev: devIndex,
                                                            hisEd: edHis,
                                                            nowEd: edId,
                                                            state: 2
                                                        }
                                                        $(that).find("td").find("strong").html(name + "装置升级成功")
                                                    } else {
                                                        obj = {
                                                            dev: devIndex,
                                                            hisEd: edHis,
                                                            nowEd: edId,
                                                            state: 3
                                                        }
                                                        $(that).find("td").find("strong").html(name + "装置升级失败")
                                                        $(that).find("td").find("div").attr("class", "alert alert-danger")
                                                    }
                                                    devUpDetail.push(obj)

                                                    break;

                                                }
                                            }
                                        })
                                        $('.loading-div').hide()
                                        if (devUpDetail.length != 0) {
                                            //记录日志
                                            $.ajax({
                                                method: "post",
                                                url: "/pqs9900/version/logsPush",
                                                data: JSON.stringify(devUpDetail),
                                                dataType: 'json',
                                                contentType: 'application/json;charset=UTF-8',
                                                beforeSend: function () {

                                                },
                                                success: function (data) {

                                                }

                                            })

                                            $('#aeert').show()
                                        } else {

                                        }
                                    }
                                }

                            })

                        }, 10000)


                    }
                }


            } else if (info.type == 182) {
                //取消升级
                if (info.resultcode == 10000) {
                    delUpPro(info.data)
                    $('#batchCancel').hide();
                    cancel++;
                    if (cancel + fail + succee == devarr.length) {
                        $('#buttons').empty()
                        $('#buttons').css('padding', '3px').append('<button type="button" id="closeId" onclick="closePercent()" class="btn btn-primary mb5">确认</button>')
                    }
                } else {
                    console.log(info.data.devName + "取消升级")
                }

            }
        }
    }
})

//单点取消
function startCancel(devIndex) {
    let arr = []
    if (devIndex) {
        arr.push(devIndex)
        $.ajax({
            url: '/pqs9900/version/cancelUp',
            type: 'post',
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify(arr),
            dataType: 'json',
            beforeSend: function () {
                indexi = ityzl_SHOW_LOAD_LAYER();
            },
            success: function (data) {
                if (data.code == 200) {

                } else {
                    layer.msg(data.message, {icon: 2})
                }
                //***********关闭loading
                ityzl_CLOSE_LOAD_LAYER(indexi);
            }
        })
    }
}

//批量取消升级
function batchCancel() {
    console.log("进来了")
    let arr = []
    $('.process-bar').each(function () {
        let that = this;
        let flag = $(that).find('.pb-value').attr('flag');
        console.log("flag" + flag)
        let real = $(that).find('.pb-value').attr('perce');
        console.log(real)
        if (real > 0 && real < 90 && flag == 1) {
            let val = $(that).find('.pb-value').attr('value');
            arr.push(val)
        }

    })
    if (arr.length > 0) {
        let index;
        //发送重启请求
        $.ajax({
            method: "post",
            url: "/pqs9900/version/cancelUp",
            data: JSON.stringify(arr),
            dataType: 'json',
            contentType: 'application/json;charset=UTF-8',
            beforeSend: function () {
                index = ityzl_SHOW_LOAD_LAYER();
            },
            success: function (data) {
                if (data.code == 200) {
                    console.log("成功取消" + arr)
                } else {

                }
                //***********关闭loading
                ityzl_CLOSE_LOAD_LAYER(index);
            }

        })


    }
}

//取消装置升级
function delUpPro(data) {
    $('.process-bar').each(function () {
        let that = this;
        if ($(that).find('.pb-value').attr('value') == data.devIndex) {
            $('#title').text(data.devName + ' -升级取消')
            $(that).find('.pb-value').css("background", "#808080")
            $(that).parent().parent().find('.errorSet').hide()
            $(that).parent().parent().find('.cancelSet').hide()
        }

    })

}

//点击查询按钮
$("#query").on("click", function () {
    refresh();
});

//终端版本维护
$("#manager").on("click", function () {
    layer.open({
        type: 2,
        title: '终端版本维护',
        area: ['100%', '100%'],
        content: 'versionmanger',
        scrollbar: false,
        end: function () {
            refresh();
        }
    })
});

//批量升级
$("body").on('click', '#batch_up', function () {
    arr = []; //选中的设备
    devNameArr = []
    edArr = [];
    devEdHisAndNow = [];
    dateUp = []
    //首先判断webSocket是否连接
    if (websocket.readyState != 1) {
        layer.msg('webSocket连接关闭,请联系管理人员', {icon: 2})
        return;
    }
    var checkdiv = $("[name=checkboxs]:checked")
    console.log(checkdiv)
    var len = checkdiv.length
    if (len == 0) {
        layer.msg('请至少选择一台终端', {icon: 2})
        return
    }
    let one = checkdiv.eq(0).attr('series')
    for (var i = 0; i < len; i++) {

        if (one != checkdiv.eq(i).attr('series')) {
            layer.msg('请选择相同系列装置', {icon: 2})
            return
        }
    }

    for (var i = 0; i < len; i++) {
        let edIndex = checkdiv.eq(i).attr('edIndex')
        let devName = checkdiv.eq(i).attr('obj')
        arr.push(checkdiv.eq(i).val())
        if (edIndex != null) {
            edArr.push(checkdiv.eq(i).attr('edIndex'))
        }

        devEdHisAndNow.push({dev: checkdiv.eq(i).val(), ed: edIndex})
        dateUp.push(checkdiv.eq(i).attr('eddate'))
        devNameArr.push({devName: devName, devIndex: checkdiv.eq(i).val()})
    }

    console.log(devNameArr)

    layer.open({
        type: 2,
        title: '版本选择',
        area: ['25%', '60%'],
        content: 'deviceversionup?devSeries=' + one,
        scrollbar: false,
    })
});


//全选
$('#all_checked').on("click", function () {
    let that = this
    $('[name=checkboxs]:checkbox').each(function () {
        if (!$(this).attr('disabled')) {
            $(this).prop('checked', that.checked)
        }
    })

})

//进度条判断（失败情况）
function temptPercent(da, err) {
    /*if (percent == null) {
        showPercent()
    }

    let flag = devarr.find(function (value) {
        return value == da.devIndex
    })
    if (!flag) {
        devarr.push(da.devIndex)
        let str = '<div class="row">' +
            '<label class="col-sm-4" style="padding-right: 0px;">' + da.devName.substring(0, 12) + '</label>' +
            '<div class="col-sm-6" style="padding: 2px 5px 0px 3px">' +
            '<div class="process-bar">' +
            '<div class="pb-wrapper">' +
            '<div class="pb-highlight"></div>' +
            '<div class="pb-container">' +
            '<div class="pb-text">0%</div>' +
            '<div value="' + da.devIndex + '" flag="3" class="pb-value themeBGColor" style="width:0%"></div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<div class="col-sm-2 errorSet" style="padding-left: 0px;padding-right: 5px; padding-top:1.5px;display: none"><a href="#" data-toggle="popover" title=""><span class="glyphicon glyphicon-question-sign"  style="color: rgb(255, 0, 0); font-size: 14px;"></span></a></div>' +
            '</div>'
        $('#loading').append(str)

    }*/

    $('.process-bar').each(function () {
        let that = this
        if ($(that).find('.pb-value').attr('value') == da.devIndex) {
            $(that).parent().parent().find('.errorSet').show()
            $(that).parent().parent().find('.cancelSet').hide()
            $(that).parent().parent().find('.errorSet').find('a').attr('title', err)
        }
    })
    fail++;
}

/**
 * 初始化获取后台数据
 */
function refresh() {
    var statue = $('#comm_state').val()
    var devtype = $('#decice_model').val()
    var devseries = $('#devSeries').val()
    var upIsNo = $('#upIsNo').val()
    var indexi;
    $.ajax({
        type: "get",
        url: "/pqs9900/version/getTerminalList",
        dataType: "json",
        data: {
            status: statue,
            devType: devtype,
            devSeries: devseries,
            upIsNo: upIsNo
        },
        beforeSend: function () {
            indexi = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 200) {
                //初始化表格
                initTransactionTable(data.body);
            } else {
                layer.msg(data.message, {icon: 2, time: 2000})
                initTransactionTable(null);
            }
            ityzl_CLOSE_LOAD_LAYER(indexi);
        }
    })
}


//初始化表格数据
function initTransactionTable(tableData) {
    let tableHeight = height - 140
    var length = Math.floor(tableHeight / 32) - 1;
    if (length < 1) {
        length = 1;
    }
    var tableCellHeight = tableHeight;
    dataTable = $("#deviceTable").DataTable();
    dataTable.clear().draw();
    dataTable = $('#deviceTable').DataTable({
        order: [10, 'desc'],
        columnDefs: [
            {
                orderable: false,
                targets: [0, 12]
            }
        ],
        columns: [
            {
                width: "15px", data: "devIndex", render: function (data, type, full, meta) {
                    if (full.status == 0 || full.edName == '/') {
                        return "<input type ='checkbox' value='" + data + "' eddate='" + full.edDate + "' edIndex='" + full.edIndex + "' series='" + full.devSeries + "' obj='" + full.name + "' name='checkboxs' class='icheckbox_minimal' disabled>";
                    } else {
                        return "<input type ='checkbox' value='" + data + "' eddate='" + full.edDate + "' edIndex='" + full.edIndex + "' series='" + full.devSeries + "' obj='" + full.name + "' name='checkboxs' class='icheckbox_minimal' >";
                    }
                }
            },
            {width: "110px", data: "name"},
            {width: "60px", data: "edName"},
            {width: "60px", data: "proTocol"},
            {width: "60px", data: "edDate"},
            {width: "70px", data: "devSeriesName"},
            {width: "110px", data: "devType"},
            {width: "100px", data: "gdName"},
            {
                width: "130px", data: "bdName", render: function (data) {
                    let value = data;
                    if (data != null && data.length > 12) {
                        value = data.substring(0, 12) + "..";
                        value = "<span title=" + data + ">" + value + "</span>";
                    }
                    return value;
                }
            },
            {
                width: "50px", data: "status", render: function (data) {
                    switch (data) {
                        case 0:
                            return '中断';
                        case 1:
                            return '正常';
                    }
                }
            },
            {
                width: "100px", data: "updateTime", render: function (data) {
                    return formatTime(data, 1)
                }
            },
            {width: "80px", data: "updateUser"},
            {
                width: "180px",
                data: "devIndex", render: function (data, type, full, meta) {
                    if (full.status == 0 || full.edName == '/') {
                        return "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='viewTransactionDetail(\"" + full.devIndex + "\",\"" + full.name + "\",\"" + full.devSeries + "\",\"" + full.edIndex + "\")' disabled>升级</button>" +
                            "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='upDetails(\"" + full.devIndex + "\",\"" + full.name + "\")'>升级日志</button>";
                    } else {
                        return "<button  type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='viewTransactionDetail(\"" + full.devIndex + "\",\"" + full.name + "\",\"" + full.devSeries + "\",\"" + full.edIndex + "\",\"" + full.edDate + "\")' >升级</button>" +
                            "<button type='button' class='btn themeBGColor' style='margin-right:10px;' href='javascript:void(0);'  onclick='upDetails(\"" + full.devIndex + "\",\"" + full.name + "\")'>升级日志</button>";
                    }

                }
            }
        ],
        destroy: true,
        data: tableData,
        lengthChange: false,
        searching: true,
        dom: 'rtip',
        scrollY: tableCellHeight,
        scrollX: true,
        autoWidth: true,
        lengthMenu: [length],
        language: {
            url: '/pqs9900/json/chine.json'
        },
        createdRow: function (row, data, index) {
            if (data.status == 1) {
                $('td', row).eq(9).css('color', '#22B14C')
            } else if (data.status == 0) {
                $('td', row).eq(9).css('color', '#ED1C24')
            }
        },
        fnDrawCallback: function (oTable) {
            $("#deviceTable_info").addClass("fl");
            $("#deviceTable_paginate").addClass("fr");
            $("#deviceTable_paginate").append("<div style='float:right;padding-top:4px;padding-left:10px'>到第 <input type='text' id='changePage' class='input-text' style='width:50px;height:28px;'> 页  <button class='btn btn-primary' id='dataTable-btn'>确定</button></div>");
            var table = $("#deviceTable").dataTable();
            $('#dataTable-btn').click(function (e) {
                if ($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });
        }

    });
    new $.fn.dataTable.Buttons(dataTable, {
        buttons: [
            {
                extend: 'csv',//导出格式
                title: '终端版本详情导出',//导出csv名称
                exportOptions: {
                    columns: [0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],//导出需要的列
                    format: {
                        body: function (data, rid, cid) {//对导出内容的筛选 data 表格内容 rid 行索引 cid 列索引
                            if (cid === 0) {
                                return rid + 1;
                            }else if(cid == 8){
                                if (data.indexOf("title") > 0) {
                                    return data.substring(data.indexOf("=") + 1, data.indexOf(">"));
                                } else {
                                    return data
                                }
                            }else {
                                return data
                            }

                        }
                    }
                }
            }
        ]
    });
    modifyCss(dataTable)


}

function modifyCss(dataTable) {
    dataTable.buttons().container().css("display", "inline-block");
    dataTable.buttons().container().css("float", "right");
    dataTable.buttons().container().css("margin-left", "10px");
    dataTable.buttons().container().appendTo('#queryAndExport');
}

//搜索表中的数据
function searchResult(value) {
    dataTable.search(value).draw();
}


//查看升级日志
function upDetails(devIndex, name) {
    layer.open({
        type: 2,
        title: name + ' _#终端升级日志查看',
        maxmin: false,
        area: ['80%', '60%'],
        content: 'toupdetail?devIndex=' + devIndex,
        scrollbar: false,
    })
}

//点击升级按钮事件
function viewTransactionDetail(devIndex, name, devSeries, edIndex, edDate) {
    //首先判断webSocket是否连接
    if (websocket.readyState != 1) {
        layer.msg('webSocket连接关闭,请联系管理人员', {icon: 2})
        return;
    }
    arr = []
    devNameArr = []
    edArr = []
    devEdHisAndNow = [];
    arr.push(devIndex)
    devNameArr.push({devName: name, devIndex: devIndex})
    edArr.push(edIndex)
    devEdHisAndNow.push({dev: devIndex, ed: edIndex})
    dateUp.push(edDate)
    layer.open({
        type: 2,
        title: '版本选择',
        maxmin: false,
        area: ['25%', '60%'],
        content: 'deviceversionup?devSeries=' + devSeries,
        scrollbar: false,
    })
}

//获取所有装置类型
function getDeviceType() {
    $.ajax({
        type: 'post',
        url: '/pqs9900/device/getselect',
        data: {dictypeName: '装置类型'},
        dataType: 'json',
        success: function (data) {
            $('#decice_model').empty()
            var html = '<option value="">全部</option>'
            data.forEach(function (item) {
                let op = '<option value="' + item.dicIndex + '">' + item.dicName + '</option>'
                html += op;
            })
            $('#decice_model').append(html)
        }

    })
}

//加载所有装置系列
function getDeviceSeries() {
    $.ajax({
        type: 'post',
        url: '/pqs9900/device/getselect',
        data: {dictypeName: '装置系列'},
        dataType: 'json',
        success: function (data) {
            $('#devSeries').empty()
            var html = '<option value="">全部</option>'
            data.forEach(function (item) {
                let op = '<option value="' + item.dicIndex + '">' + item.dicName + '</option>'
                html += op;
            })
            $('#devSeries').append(html)
        }

    })
}


var devarr = [] //正在升级的设备
var openid;
var username = $('#username').val()
var resetName = ''
//回调
window.sendWebSocket = function (edIndex, type) {
    if (type == 1) {
        passwordLocalIndentity(username, resetName, function () {
            openid = layer.open({
                type: 2,
                title: '升级确认',
                area: ['90%', '90%'],
                content: 'terminalupdetail?edIndex=' + edIndex,
                scrollbar: false,
            })
        })
    } else {
        restartLoad = null;
        devarr = []
        restartArr = [];
        $('#loading').empty()
        succee = 0;
        fail = 0;
        cancel = 0;
        restartNum = 0; //重启的装置数量
        restartSuccedNum = 0;
        percent = null;
        edId = edIndex;
        var indexi;
        let map = {indexlist: arr, nodeIndex: edIndex}
        //获取端口号
        $.ajax({
            url: '/pqs9900/version/getTemplet',
            type: 'post',
            contentType: 'application/json;charset=UTF-8',
            data: JSON.stringify(map),
            dataType: 'json',
            beforeSend: function () {
                indexi = ityzl_SHOW_LOAD_LAYER();
            },
            success: function (data) {
                if (data.code == 200) {
                    layer.close(openid)
                    hasEndDev = 0;
                    showPercent()
                } else {
                    layer.msg(data.message, {icon: 2})
                }
                //***********关闭loading
                ityzl_CLOSE_LOAD_LAYER(indexi);
            }
        })


        //用于单机调试
        /*

         layer.close(openid)
                showPercent()
                ityzl_CLOSE_LOAD_LAYER(indexi);
                let testcc = [{
                    data: {
                        devIndex: "260",
                        code: "",
                        json: "",
                        state: "1",
                        devName: "882A_ED01",
                        percent: 5
                    },
                    resultmsg: "Updata",
                    resultcode: "10000",
                    type: "180"
                },{
                    data: {
                        devIndex: "260",
                        code: "",
                        json: "",
                        state: "1",
                        devName: "882A_ED01",
                        percent: 50
                    },
                    resultmsg: "Updata",
                    resultcode: "10000",
                    type: "180"
                },{
                    data: {
                        devIndex: "261",
                        code: "",
                        json: "",
                        state: "1",
                        devName: "882A_ED02",
                        percent: 10
                    },
                    resultmsg: "Updata",
                    resultcode: "10000",
                    type: "180"
                },{
                    data: {
                        devIndex: "261",
                        code: "",
                        json: "",
                        state: "3",
                        devName: "882A_ED02",
                        percent: 60
                    },
                    resultmsg: "Updata",
                    resultcode: "10000",
                    type: "180"
                },{
                    data: {
                        devIndex: "260",
                        code: "",
                        json: "",
                        state: "1",
                        devName: "882A_ED01",
                        percent: 80
                    },
                    resultmsg: "Updata",
                    resultcode: "10000",
                    type: "180"
                },{
                    data: {
                        devIndex: "260",
                        code: "",
                        json: "",
                        state: "2",
                        devName: "882A_ED01",
                        percent: 100
                    },
                    resultmsg: "Updata",
                    resultcode: "10000",
                    type: "180"
                }]


                let l = 0;
             let bbb =   window.setInterval(function () {



                    let aa = JSON.stringify(testcc[l])

                    if (aa != "") {
                        //data数据体后的长度
                        var info = JSON.parse(aa)
                        if (info.type == 180) {
                            console.log(info)
                            $('.loading-div').remove()
                            if (info.resultcode == 10000) {
                                let da = info.data
                                if (info.data === undefined) {

                                } else {
                                    //存在关闭游览器后重新打开和正常操作两种情况
                                    if (percent == null) {
                                        showPercent()
                                    }

                                    let flag = devarr.find(function (value) {
                                        return value == da.devIndex
                                    })
                                    if (!flag) {
                                        devarr.push(da.devIndex)
                                        let str = '<div class="row">' +
                                            '<label class="col-sm-4" style="padding-right: 0px;">' + da.devName.substring(0, 10) + '</label>' +
                                            '<div class="col-sm-6" style="padding: 2px 5px 0px 3px">' +
                                            '<div class="process-bar">' +
                                            '<div class="pb-wrapper">' +
                                            '<div class="pb-highlight"></div>' +
                                            '<div class="pb-container">' +
                                            '<div class="pb-text">1%</div>' +
                                            '<div value="' + da.devIndex + '" class="pb-value themeBGColor" style="width:1%"></div>' +
                                            '</div>' +
                                            '</div>' +
                                            '</div>' +
                                            '</div>' +
                                            '<div class="col-sm-2 cancelSet" style="padding-left: 0px;padding-right: 5px;display: none"><a href="#" data-toggle="popover" title=""><span onclick="startCancel(' + da.devIndex + ')" value="' + da.devIndex + '" class="glyphicon glyphicon-minus-sign"  style="color: rgb(0, 255, 0); font-size: 14px;"></span></a></div>' +
                                            '<div class="col-sm-2 errorSet" style="padding-left: 0px;padding-right: 5px;display: none"><a href="#" data-toggle="popover" title=""><span class="glyphicon glyphicon-question-sign"  style="color: rgb(255, 0, 0); font-size: 14px;"></span></a></div>' +
                                            '</div>'
                                        $('#loading').append(str)
                                    }


                                    $('.process-bar').each(function () {
                                        if (da.percent > 0 && da.percent < 100) {
                                            if($(this).find('.pb-value').attr('value') == da.devIndex) {
                                                $(this).parent().parent().find('.cancelSet').show()
                                            }
                                        } else {
                                            $(this).parent().parent().find('.cancelSet').hide()
                                        }

                                        if ($(this).find('.pb-value').attr('value') == da.devIndex) {
                                            $(this).find('.pb-value').css('width', da.percent + '%')
                                            $(this).find('.pb-text').text(da.percent + '%')
                                            if (da.state == 0) {
                                                $('#title').empty()
                                                $('#title').text('正在预加载......')
                                            } else if (da.state == 1) {
                                                $('#title').empty()
                                                $('#title').text('正在升级......')
                                                if (da.percent == 99) {
                                                    //重启阶段
                                                    $('#title').text(da.devName + '正在重启,请耐心等待......')
                                                }

                                            } else if (da.state == 2) {
                                                succee++;
                                                $(this).parent().parent().find('.cancelSet').hide()
                                            } else if (da.state == 3) {
                                                temptPercent(info.data, '出错了')
                                            }

                                        }
                                    })
                                }
                            } else if (info.resultcode == 10003) {
                                layer.msg("JSON字符串解析出错", {
                                    icon: 5,
                                    time: 3000
                                });
                            } else if (info.resultcode == 10004) {
                                layer.msg("socket处理出现异常", {
                                    icon: 5,
                                    time: 3000
                                });
                            } else if (info.resultcode == 10005) {
                                layer.msg("未找到ID为对应的设备", {
                                    icon: 5,
                                    time: 3000
                                });
                            } else if (info.resultcode == 10008) {
                                layer.msg('当前存在终端正在升级，请勿重复操作', {icon: 2, time: 2000})
                            } else if (info.resultcode == 10009) {
                                layer.msg('存在正在升级程序,请勿重复操作')
                            } else if (info.resultcode == 100 || info.resultcode == 101 || info.resultcode == 102) {
                                let dataArr = info.data
                                if (percent == null) {
                                    showPercent()
                                }

                                for (let i = 0; i < dataArr.length; i++) {

                                    let flag = devarr.find(function (value) {
                                        return value == dataArr[i].devIndex
                                    })
                                    if (!flag) {
                                        devarr.push(dataArr[i].devIndex)
                                        let str = '<div class="row">' +
                                            '<label class="col-sm-4" style="padding-right: 0px;font-size:10px ">' + dataArr[i].devName.substring(0, 10) + '</label>' +
                                            '<div class="col-sm-6" style="padding: 2px 5px 0px 3px">' +
                                            '<div class="process-bar">' +
                                            '<div class="pb-wrapper">' +
                                            '<div class="pb-highlight"></div>' +
                                            '<div class="pb-container">' +
                                            '<div class="pb-text">1%</div>' +
                                            '<div value="' + dataArr[i].devIndex + '" class="pb-value themeBGColor" style="width:1%"></div>' +
                                            '</div>' +
                                            '</div>' +
                                            '</div>' +
                                            '</div>' +
                                            '<div class="col-sm-2 errorSet" style="padding-left: 0px;padding-right: 5px;display: none"><a href="#" data-toggle="popover" title=""><span class="glyphicon glyphicon-question-sign"  style="color: rgb(255, 0, 0); font-size: 14px;"></span></a></div>' +
                                            '</div>'
                                        $('#loading').append(str)

                                    }
                                    fail++
                                }


                                $('.process-bar').each(function () {
                                    let that = this
                                    dataArr.forEach(function (item) {

                                        if ($(that).find('.pb-value').attr('value') == item.devIndex) {
                                            $(that).parent().parent().find('.errorSet').show()
                                            $(that).parent().parent().find('.errorSet').find('a').attr('title', '连接前置机异常')
                                        }
                                    })

                                })
                                $('.loading-div').remove()

                            } else if (info.resultcode == 99990) {
                                let da = info.data
                                temptPercent(da, '终端重启文件校验重复,联系管理员修改')
                            } else if (info.resultcode == 99999) {
                                //超时
                                let da = info.data
                                temptPercent(da, '超时')
                            } else if (info.resultcode == 99991) {
                                //CRC校验异常
                                let da = info.data
                                temptPercent(da, 'CRC校验异常')
                            } else if (info.resultcode == 99992) {
                                //未知异常
                                let da = info.data
                                temptPercent(da, '未知异常')
                            } else if (info.resultcode == 99993 || info.resultcode == 99995) {
                                //文件传送异常
                                let da = info.data
                                temptPercent(da, '文件传送异常')
                            } else if (info.resultcode == 99994) {
                                //超时
                                let da = info.data
                                temptPercent(da, '文件传送异常')
                            } else if (info.resultcode == 99996) {
                                //超时
                                let da = info.data
                                temptPercent(da, '预升级异常')
                            } else if (info.resultcode == 99997) {
                                //超时
                                let da = info.data
                                temptPercent(da, '读取数据库失败')
                            } else if (info.resultcode == 99998) {
                                //超时
                                let da = info.data
                                temptPercent(da, '数据库读取无数据')
                            } else if (info.resultcode == 99989) {
                                let da = info.data
                                temptPercent(da, '版本类型与终端类型不一致')
                            } else {
                                layer.msg("socket连接异常", {
                                    icon: 5,
                                    time: 3000
                                });
                            }

                            if (fail == 0 && succee == 0) {
                                //已经全部加载出来放开全部取消按钮
                                $('#batchCancel').show();
                            } else {
                                $('#batchCancel').hide();
                            }


                            if (arr.length != 0 && fail + succee == arr.length) {

                                $('#title').empty()
                                $('#title').html('<sapn style="font-size: 12px;font-weight: 500;font-family: normal">' + '成功：' + '<span style="color: #0c7cb5">' + succee + '</span>' + '台 失败: ' + '<span style="color: red">' + fail + '</span>' + '台' + '</span>')
                                $('#buttons').empty()
                                $('#buttons').css('padding', '3px').append('<button type="button" id="closeId" onclick="closePercent()" class="btn btn-primary">确认</button>').append('<button type="button" id="reload" onclick="reloadController()" class="btn btn-primary ml10">重启</button>')
                            }

                            //重新打开游览器
                            if (arr.length == 0 && fail + succee == devarr.length) {
                                $('#title').empty()
                                $('#title').html('<sapn style="font-size: 12px;font-weight: 500;font-family: normal">' + '成功：' + '<span style="color: #0c7cb5">' + succee + '</span>' + '台 失败: ' + '<span style="color: red">' + fail + '</span>' + '台' + '</span>')
                                $('#buttons').empty()
                                $('#buttons').css('padding', '3px').append('<button type="button" id="closeId" onclick="closePercent()" class="btn btn-primary">确认</button>')

                            }

                        }
                    }

            if(l == 5){
                window.clearInterval(bbb)
            }
            l++

                },2000)  //ddd

        */


    }


}

//升级结束后的批量重启操作

function reloadController() {
    let reload = []
    let con = layer.confirm('重启只针对版本下发成功的装置,是否继续重启?', function () {
        $('.process-bar').each(function () {
            let that = this;
            let aa = $(that).find('.pb-text').text()
            console.log(aa)
            if ($(that).find('.pb-text').text() == '100%') {
                let val = $(that).find('.pb-value').attr('value');
                reload.push(val)
            }

        })

        if (reload.length > 0) {
            let index;
            //发送重启请求
            $.ajax({
                method: "post",
                url: "/pqs9900/version/restartDev",
                data: JSON.stringify(reload),
                dataType: 'json',
                contentType: 'application/json;charset=UTF-8',
                beforeSend: function () {
                    index = ityzl_SHOW_LOAD_LAYER();
                },
                success: function (data) {
                    if (data.code == 200) {
                        layer.close(percent)


                    } else {

                    }
                    ityzl_CLOSE_LOAD_LAYER(index);
                    layer.close(con)
                }

            })


        }
    })

}


//进度条
function showPercent() {
    percent = layer.open({
        type: 1
        , title: false //不显示标题栏
        , closeBtn: false
        , area: '290px;'
        , shade: 0.8
        , id: 'LAY_layuipro' //设定一个id，防止重复弹出
        , btnAlign: 'c'
        , moveType: 1 //拖拽模式，0或者1
        , content: '<div style="padding: 8px 5px;font-size: 12px">' +
            '<span class="glyphicon glyphicon-th-list"></span><span style="margin-left: 10px" id="title"></span><span style="float: right"><button style="display: none" id="batchCancel" onclick="batchCancel()">全部取消</button></span>' +
            '</div>' +
            '<div id="loading" style="padding: 15px; background-color: #393D49; color: #fff; font-weight: 300;">' +
            '</div>' +
            '<div id="buttons" style="text-align: center;background-color: #393D49; color: #fff;"></div>'
    });


    if (arr.length != 0) {
        devNameArr.forEach(function (item) {
            let str = '<div class="row">' +
                '<label class="col-sm-4" style="padding-right: 0px;">' + item.devName.substring(0, 12) + '</label>' +
                '<div class="col-sm-6" style="padding: 2px 5px 0px 3px">' +
                '<div class="process-bar">' +
                '<div class="pb-wrapper">' +
                '<div class="pb-highlight"></div>' +
                '<div class="pb-container">' +
                '<div class="pb-text">0%</div>' +
                '<div value="' + item.devIndex + '" flag="0" perce="0" class="pb-value themeBGColor" style="width:0%"></div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '<div class="col-sm-2 cancelSet" style="padding-left: 0px;padding-right: 5px; padding-top:1.5px;display: none"><a href="#" data-toggle="popover" title=""><span onclick="startCancel(' + item.devIndex + ')" value="' + item.devIndex + '" class="glyphicon glyphicon-minus-sign"  style="color:rgb(255,170,0); font-size: 14px;"></span></a></div>' +
                '<div class="col-sm-2 errorSet" style="padding-left: 0px;padding-right: 5px; padding-top:1.5px;display: none"><a href="#" data-toggle="popover" title=""><span class="glyphicon glyphicon-question-sign"  style="color: rgb(255,0,0); font-size: 14px;"></span></a></div>' +
                '</div>'
            $('#loading').append(str)
            devarr.push(item.devIndex)
        })
    }

    $('#title').empty()
    $('#title').text('正在请求升级......')


    /* $('.process-bar').each(function () {
         if ($(this).find('.pb-value').attr('value') == da.devIndex) {
             $(this).find('.pb-value').css('width', da.percent + '%')
             $(this).find('.pb-text').text(da.percent + '%')
             $(this).find('.pb-value').attr('perce', da.percent)
             if (da.state == 0) {
                 $('#title').empty()
                 $('#title').text('正在预加载......')
             } else if (da.state == 1) {
                 $(this).find('.pb-value').attr("flag", 1)
                 $('#title').empty()
                 $('#title').text('正在下装版本......')
                 if (da.percent == 99) {
                     //校验阶段
                     $('#title').text(da.devName + '正在校验......')
                 }


                 //展示取消按钮
                 if (da.percent > 0 && da.percent < 90) {
                     $(this).parent().parent().find('.cancelSet').show()
                     if (fail == 0 && succee == 0 && cancel == 0) {
                         $('#batchCancel').show();
                     }
                     $('.process-bar').each(function () {
                         let that = this
                         let per = $(that).find('.pb-value').attr('perce')
                         if (per == 0 || per >= 90) {
                             $('#batchCancel').hide();
                         }
                     })
                 } else {
                     $('#batchCancel').hide();
                     $(this).parent().parent().find('.cancelSet').hide()
                 }


             } else if (da.state == 2) {
                 $(this).find('.pb-value').attr("flag", 2)
                 succee++;
                 $(this).parent().parent().find('.cancelSet').hide()
             } else if (da.state == 3) {
                 $(this).find('.pb-value').attr("flag", 3)
                 temptPercent(info.data, '出错了')
             }


         }
     })*/

    /*let html = '<div class="loading-div">' +
        '<i class="fa fa-spinner fa-pulse fa-3x fa-fw "></i>' +
        '<span>Loading...</span>' +
        '</div>'
    $('#loading').html(html)
    $('#title').text('请求中......')*/

}


function closePercent() {
    layer.close(percent)
    refresh()
}

function senddevArr() {
    return arr;
}

function sendEdArr() {
    return edArr;
}

function sendEdDate() {
    return dateUp;
}

function closeAndRefrsh() {
    layer.close(restartLoad)
    refresh()
}

