var index = parent.layer.getFrameIndex(window.name);
var treeObj = null, fileMaps = new Map(), itemNames = [], fileNames = [], files;

let describe,eventReason,eventType,lineIndex,time,ms,persistime,waveType,eventValue,num
var treeHeight = $(window).height() - 25;
//文档流完毕后，开始获取树结构
$(document).ready(function () {





});

layui.use(['jquery','laydate','upload'], function() {
    var $ = layui.$ //重点处
        ,upload = layui.upload
        ,laydate = layui.laydate;
    //文档流加载完成后，给设备树一个高度，同时给个border边框
    $("#leftContainer").css("height", treeHeight);
    $("#tree").css("height", treeHeight-40);
    $("#form-horizontal").css("height", treeHeight);
    $("#leftContainer").css("border-right", "solid 1px");
    getTree();
    initDownEvent()


    laydate.render({
        elem: '#date',
        type: 'datetime'
    });





    $('#testListAction1').click(function () {
        time = $('#date').val()
        ms = $('#ms').val()
        persistime = $('#persistTime').val()
        waveType = $('#waveType').val()
        eventValue = $('#eventValue').val()
        describe = $('#describe').val()
        eventReason = $("#eventReason").val()
        eventType = $("#eventType").val()


        if(lineIndex == ''||lineIndex == null){
            layer.msg("请选择监测点",{icon:2})
            return false
        }

        if(time == ''||time == null || ms =='' || ms ==null){
            layer.msg("请填写暂态事件发生时间",{icon:2})
            return false
        }
        if(persistime == ''||persistime == null){
            layer.msg("请填写事件持续时间",{icon:2})
            return false
        }
        if(waveType == ''||waveType == null){
            layer.msg("请选择暂态类型",{icon:2})
            return false
        }
        if(eventValue == ''||eventValue == null){
            layer.msg("特征幅值不可为空",{icon:2})
            return false
        }
        if(eventReason == ''||eventReason == null){
            layer.msg("暂态原因不可为空",{icon:2})
            return false
        }
        if(eventType == ''||eventType == null){
            layer.msg("暂态类型不可为空",{icon:2})
            return false
        }


        var flag = 0;
        //根据fileNames判断,清洗CFG/DAT文件不全的
        if (itemNames.length > 0) {
            for (var i = 0; i < itemNames.length; i++) {
                var cfg = itemNames[i] + ".CFG";
                var dat = itemNames[i] + ".DAT";
                var itemFlag = 0;
                if (fileNames.indexOf(cfg) >= 0) {
                    if (fileNames.indexOf(dat) === -1) {
                        //说明有CFG文件，没有DAT文件，需要将CFG文件删除
                        flag = 1;
                        itemFlag = 1;
                        //同时将该单元格红色标记出来
                        $("td:contains('" + itemNames[i] + "')").css("color", "red");
                    }
                }
                if (fileNames.indexOf(dat) >= 0) {
                    if (fileNames.indexOf(cfg) === -1) {
                        //说明有DAT文件，没有CFG文件，需要将DAT文件删除
                        flag = 1;
                        itemFlag = 1;
                        //同时将该单元格红色标记出来
                        $("td:contains('" + itemNames[i] + "')").css("color", "red");
                    }
                }
                if (fileNames.indexOf(dat) === -1 & fileNames.indexOf(cfg) === -1) {
                    flag = 1;
                }
                //DAT和CFG文件都存在,单元格字体恢复
                if (itemFlag === 0) {
                    $("td:contains('" + itemNames[i] + "')").css("color", "black");
                }
            }
        } else {
            //没有文件数据
            flag = -1;
        }
        if (flag === 0) {
            layer.msg("波形文件无异常", {icon: 1, time: 2000});
        } else if (flag === -1) {
            layer.msg("请选择要上传的文件", {icon: 2, time: 2000});
            return
        } else {
            layer.msg("存在波形文件缺失", {icon: 2, time: 2000});
            return
        }










        let formData = new FormData();

        for(let i in files){
            console.log(files[i])
            formData.append("file",files[i])
        }
        formData.append("time",time)
        formData.append("ms",ms)
        formData.append("persistime",persistime)
        formData.append("describe",describe)
        formData.append("waveType",waveType)
        formData.append("lineIndex",lineIndex)
        formData.append("eventValue",eventValue)
        formData.append("eventReason",eventReason)
        formData.append("eventType",eventType)
        console.log(formData)

        layer.confirm("确认提交吗?",function () {
            let load;
            $.ajax({
                url:'/pqs9900/offdata/addEvent',
                type:'post',
                data:formData,
                cache:false,
                contentType:false,
                processData:false,
                before:function(){
                    load = layer.load();
                },
                success:function (data) {
                    if(data.code == 200){
                        layer.msg(data.message,{icon:1},function () {
                            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                            parent.layer.close(index); //再执行关闭
                            window.parent.refreshes()
                        })

                    }else {
                        layer.msg(data.message,{icon:2})
                    }
                    console.log(data)
                    layer.close(load)
                }

            })
        })


    })


    //演示多文件列表

    var fileListView = $('#fileList')
        , uploadListIns = upload.render({
        elem: '#waveUpload'
        ,elemList: $('#fileList') //列表元素对象
        ,accept: 'file'
        ,multiple: true
        ,number: 2
        ,acceptMime:'CFG/DAT'
        ,auto: false
        ,before:function () {

            if (files === {}) {
                //如果是空对象，说明之前的文件全部上传成功，需要将之前的一些集合清空，同时隐藏上传按钮，显示文件校验按钮，如果需要的话，也可以把表格清空
                fileMaps = new Map();
                itemNames = [];
                fileNames = [];
            }
        }
        ,choose: function(obj){

            var that = this;
            files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function(index, file, result){
                time = $('#date').val()
                ms = $('#ms').val()
                if(time==''||time==null||ms==''||ms==null){
                    layer.msg('请先填写事件发生时间',{type:1})
                    return
                }
                let dealTime = num+'_'+time+"."+ms
                var fileName = file.name.toUpperCase();

                let dealT = dealTime.replace(/-/g,"").replace(/:/g,"").replace('.',"_").replace(' ',"_")
                console.log(dealT)
                console.log(fileName.substring(0,fileName.indexOf(".")))
                if(dealT!=fileName.substring(0,fileName.indexOf("."))){
                    layer.msg("文件与事件不匹配",{type:1})
                    delete files[index];
                    return
                }

                if (fileNames.indexOf(fileName) === -1) {
                    //作为新文件加入进来
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td>' + fileName + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="btn  btn-primary  file-reload layui-hide"><i class="fa fa-refresh"></i>重传</button>'
                        , '<button type="button" class="btn  btn-danger file-delete ml10" ><i class="fa fa-trash"></i>删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));
                    //个性化处理部分**start**
                    fileMaps.set(fileName.toUpperCase(), index);
                    fileNames.push(fileName.toUpperCase());
                    var itemName = fileName.substring(0, fileName.length - 4);
                    if (itemNames.indexOf(itemName) === -1) {
                        itemNames.push(itemName.toUpperCase());
                    }
                    //个性化处理部分**end**

                    //单个重传
                    tr.find('.file-reload').on('click', function () {
                        obj.upload(index, file);
                    });
                    //删除
                    tr.find('.file-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        fileMaps.delete(fileName);
                        fileNames.splice(fileNames.indexOf(fileName), 1);
                        //标识文件名删除前，需要判断还有没有其他后缀文件存在
                        var itemFlag = judgeFileExist(itemName);
                        if (!itemFlag) {
                            itemNames.splice(itemNames.indexOf(itemName), 1);
                        }
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选


                    });
                    fileListView.append(tr);
                } else {
                    layer.msg("请勿上传重复文件", {icon: 2, time: 2000});
                    delete files[index];
                }


            });
        }
        ,done: function(res, index, upload){ //成功的回调
            var that = this;
            //if(res.code == 0){ //上传成功
            var tr = that.elemList.find('tr#upload-'+ index)
                ,tds = tr.children();
            tds.eq(3).html(''); //清空操作
            delete this.files[index]; //删除文件队列已经上传成功的文件
            return;
            //}
            this.error(index, upload);
        }
        ,allDone: function(obj){ //多文件上传完毕后的状态回调
            console.log(obj)
            console.log("所有上传成功")
        }
        ,error: function(index, upload){ //错误回调
            var that = this;
            var tr = that.elemList.find('tr#upload-'+ index)
                ,tds = tr.children();
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }

    });


})


/**
 * 删除标识文件名之前，需要判断是否存在该标识的其他后缀的文件
 * */
function judgeFileExist(itemName) {
    var itemFlag = false;
    //一共有4种后缀
    if (fileNames.indexOf(itemName + ".CFG") > -1) {
        itemFlag = true;
    } else if (fileNames.indexOf(itemName + ".DAT") > -1) {
        itemFlag = true;
    } else if (fileNames.indexOf(itemName + ".HDR") > -1) {
        itemFlag = true;
    } else if (fileNames.indexOf(itemName + ".dev") > -1) {
        itemFlag = true;
    }
    return itemFlag;
}


//模糊搜索name满足条件的节点
function searchNode(value) {
    if (value == "")
        return;

    // 获取搜索的节点
    var nodes = treeObj.getNodesByParamFuzzy("name", value);
    // 关闭所有节点的高亮
    var allNodes = treeObj.transformToArray(treeObj.getNodes());
    for (var i = 0; i < allNodes.length; i++) {
        allNodes[i].highlight = false;
        treeObj.updateNode(allNodes[i]);
    }
    // 展开第一层节点
    treeObj.expandAll(false);
    treeObj.expandNode(treeObj.getNodes()[0], true);
    // 高亮并展开搜索到的节点
    for (var i = 0; i < nodes.length; i++) {
        nodes[i].highlight = true;
        treeObj.updateNode(nodes[i]); // 更新节点，让高亮生效
        treeObj.expandNode(nodes[i].getParentNode(), true);
    }
}

//树的基础配置
var setting = {
    check: {
        enable: true,
        chkDisabledInherit: true
    },
    data: {
        simpleData: {
            enable: true
        }
    },
    view: {
        fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
    },
    callback: {
        onClick: zTreeOnClick
    }
};

// 设置高亮字体
function setHighlight(treeId, treeNode) {
    return (!!treeNode.highlight) ? {
        color: "#000",
        "font-weight": "bold"
    } : {
        color: "#999",
        "font-weight": "normal"
    };
}

//获取设备树
function getTree() {
    $.ajax({
        type: 'POST',
        dataType: "json",
        url: '/pqs9900/device/getOnlineDeviceTree',
        error: function () {
        },
        success: function (data) {
            //根据返回数据，初始化设备树
            var datalist = [];
            for (var i = 0; i < data.length; i++) {
                var str = '';
                str += '{' + "id:" + data[i].id;
                str += ',' + "name:'" + data[i].name + "'";
                str += ',' + "nodeIndex:" + data[i].nodeIndex;
                str += ',' + "nodeType:" + data[i].nodeType;
                str += ',' + "ppId:" + data[i].ppId;
                if (data[i].nodeType === "0") {
                    str += ',' + "open:" + true;
                } else {
                    str += ',' + "open:" + false;
                }
                str += ',' + "state:" + data[i].state;
                str += ',' + "pId:" + data[i].pId + '}';
                datalist.push(str);
            }
            datalist = eval('[' + datalist + ']');// string->json数组
            var zNodes = datalist;
            for (var index = 0; index < zNodes.length; index++) {
                if (zNodes[index].nodeType === 1) {
                    zNodes[index].icon = "../images/img/base.png";
                } else if (zNodes[index].nodeType === 2) {
                    zNodes[index].icon = "../images/img/power.png";
                } else if (zNodes[index].nodeType === 3) {
                    zNodes[index].icon = "../images/img/substation.png";
                } else if (zNodes[index].nodeType === 4) {
                    zNodes[index].icon = "../images/img/device.png";
                } else if (zNodes[index].nodeType === 5) {
                    zNodes[index].icon = "../images/img/subvstation.png";
                } else if (zNodes[index].nodeType === 6) {
                    zNodes[index].icon = "../images/img/gray.png";
                }
            }
            treeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
            //展开第一层级
            var zTree = $.fn.zTree.getZTreeObj("tree");
            var nodes = zTree.getNodes();
            zTree.expandNode(nodes[0], true);
        }
    });
}

//树节点点击效果
function zTreeOnClick() {
    var zTree = $.fn.zTree.getZTreeObj("tree");
    if (zTree != null) {
        var nodes = zTree.getSelectedNodes();   //获取树控件选中对象集合
        // 关闭所有节点的高亮
        var allNodes = treeObj.transformToArray(treeObj.getNodes());
        for (var i = 0; i < allNodes.length; i++) {
            allNodes[i].highlight = false;
            treeObj.updateNode(allNodes[i]);
        }
        // 高亮并展开搜索到的节点
        for (var i = 0; i < nodes.length; i++) {
            nodes[i].highlight = true;
            treeObj.updateNode(nodes[i]); // 更新节点，让高亮生效
        }
        if (nodes[0].level === 5) {    //如果选中监测点信息则进行处理，其他信息不处理
            var bdname = nodes[0].getParentNode().getParentNode().getParentNode();
            // var gdname = nodes[0].getParentNode().getParentNode().getParentNode().getParentNode();
           // $("#lineIndex").val(nodes[0].nodeIndex);
           // $("#deviceIndex").val(nodes[0].getParentNode().getParentNode().nodeIndex);
            $("#lineName").text(bdname.name + '->' + nodes[0].name);
            //开始上传按钮点击效果
           // $("#judgeFiles").removeProp("disabled");
            lineIndex = nodes[0].nodeIndex
            num = lineIndex%10
        }
    }
}


//关闭窗口
function closeWindow() {
    parent.layer.close(index);
}


//初始化暂降原因类型下拉

function initDownEvent(){
    $.ajax({
        type: 'post',
        url: '/pqs9900/device/getselect',
        data: {dictypeName: '暂降原因'},
        dataType: 'json',
        success: function (data) {
            $('#eventReason').empty()
            var html = ''
            data.forEach(function (item) {
                let op = '<option value="' + item.dicIndex + '">' + item.dicName + '</option>'
                html += op;
            })
            $('#eventReason').append(html)
        },error:function () {

        }

    })

    $.ajax({
        type: 'post',
        url: '/pqs9900/device/getselect',
        data: {dictypeName: '暂降类型'},
        dataType: 'json',
        success: function (data) {
            $('#eventType').empty()
            var html = ''
            data.forEach(function (item) {
                let op = '<option value="' + item.dicIndex + '">' + item.dicName + '</option>'
                html += op;
            })
            $('#eventType').append(html)
        },error:function () {

        }

    })
}


