<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <title>离线数据导入</title>
    <link rel="stylesheet" href="${ctx}/js/plugin/webuploader/style.css">
    <link rel="stylesheet" href="${ctx}/js/plugin/webuploader/webuploader.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="${ctx}/js/plugin/layui/css/layui.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/metroStyle/metroStyle.css">
    <link rel="stylesheet" href="${ctx}/css/basic.css">
    <style type="text/css">
        .layui-left {
            float: left;
        }

        .self-style {
            margin: 0px;
            position: absolute;
            left: 214px;
            top: 2px;
            bottom: 0;
            z-index: 1;
            overflow: auto;
            right: 0px;
        }

        .del {
            position: absolute;
            right: 5px;
            top: 5px;
        }
    </style>
</head>
<body>
<%--离线设备树--%>
<div id="father" style="width: 207px;float: left;height: 100%;padding-top: 2px;border:solid 1px #bfbfbf;">
    <div id="search"><input style="width:160px; height: 25px;" id="searchValue" type="text" value=""
                            placeholder="请输入关键词" autocomplete="off" oninput="valueChange(this.value)"/>
        <input type="button" value="搜索" class="btn-primary" onclick="javascript: searchNode(searchValue.value)"
               style=" height: 25px;width: 40px;border-radius: 4px;border: 1px solid;"/></div>
    <div id="tree" class="ztree" style="overflow: auto"></div>
</div>
<%--上传文件--%>
<div id="uploader" class="wu-example layui-left self-style" style="overflow: auto;">
    <div class="form-inline">
        <div class="form-group has-feedback mr10">
            <div class="btns">
                <div id="picker">新建监测点</div>
                <button id="ctlBtn" class="btn btn-primary" style="padding: 5px 10px;font-size: 12px;">开始上传</button>
            </div>
        </div>
        <div class="form-group fr mr5">
            <b><a href="javascript:void(0)" id="pointInfo"
                  style="font-size:12px; color: red;padding: 5px 10px;"></a></b>
            <button id="clear" class="btn btn-primary" style="font-size: 12px;">清空文件
            </button>
            <button id="download" class="btn btn-primary" style="font-size: 12px;">模板下载
            </button>
            <button id="translateState" class="btn btn-primary" style="font-size: 12px;">解析列表
            </button>
        </div>
    </div>
    <div id="thelist" class="uploader-list" style="border:solid 1px #bfbfbf;margin-top: 3px;">
        <b style="margin-left: 5px;margin-bottom: 6px;">文件列表：</b>
    </div>
</div>
</body>
<script src="${ctx}/js/plugin/jquery.min.js"></script>
<script src="${ctx}/js/plugin/webuploader/webuploader.js"></script>
<script src="${ctx}/js/plugin/webuploader/xlsx.core.min.js"></script>
<script src="${ctx}/js/plugin/layui/layer.js"></script>
<script src="${ctx}/js/plugin/ztree/jquery.ztree.core.js"></script>
<script src="${ctx}/jspJS/utils/judgeAjaxStatus.js"></script>
<script>
    var $list = $('#thelist');
    var fileNames = [];
    var files;
    var count = 0;

    // zTree属性配置
    var setting = {
        data: {
            simpleData: {
                enable: true
            }
        },
        view: {
            fontCss: setHighlight // 高亮一定要设置，setHighlight是自定义方法
        },
        callback: {
            onClick: pointSelected
        }
    };

    var bSelect = 0; //未选中树节点 0-未选中  1-选中
    var nodeIndex = 0;
    var te = '';

    function pointSelected(event, treeId, treeNode) {
        if (bSelect === 0) {
            bSelect = 1;
            uploader.reset();
            $list.html('<b style="margin-left: 5px;margin-bottom: 6px;">文件列表：</b>');
        }

        if (nodeIndex === 0 && bSelect === 1 && treeNode.level === 4 || treeNode.level === 4 && bSelect === 1 && nodeIndex === treeNode.nodeIndex || treeNode.level === 4 && bSelect == 1 && uploader.getFiles().length === 0) {
            nodeIndex = treeNode.nodeIndex;
            te = '监测点：' + treeNode.getParentNode().getParentNode().name + '->' + treeNode.getParentNode().name + '->' + treeNode.name;
            $('#pointInfo').text(te);
            $('.webuploader-element-invisible').click(); //触发
        }
        else if (treeNode.level === 4 && bSelect == 1 && uploader.getFiles().length > 0) {
            layer.msg('请注意上传文件已与监测点绑定');
        }
    }

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

    var uploader = WebUploader.create({
        auto: false,
        threads: '3',
        swf: '../../js/plugin/webuploader/Uploader.swf',
        server: '/pqs9900/device/uploader',
        pick: {id: '#picker', multiple: true},
        resize: false,
        duplicate: false,
        accept: {
            title: '数据文件',
            extensions: 'xlsx,bin',
            mimeTypes: '.xlsx,.bin'
        }
    });

    $('#picker').click(function () {
        if ($('#picker').click.caller === null) {
            if (bSelect === 1) {
                bSelect = 0;
                te = '';
                uploader.reset();
                $list.html('<b style="margin-left: 5px;margin-bottom: 6px;">文件列表：</b>');
                $('#pointInfo').text('');
                nodeIndex = 0;
            }
        }
    });

    $(function () {
        initDiv();
        getData();
    });


    uploader.on('uploadBeforeSend', function (object, data, headers) {
        if (bSelect === 1) {   //单点上传带入监测点的id
            data.id = nodeIndex;
        } else {
            data.id = -1;
        }
    });

    uploader.on('filesQueued', function (file) {
        for (var i = 0; i < file.length; i++) {
            $list.append('<div id="' + file[i].id + '" class="file-item thumbnail" style="margin-bottom: 2px;">' +
                '<div class="info">' + file[i].name + '</div>' +
                '<div class="state">等待上传...</div>' +
                '<div class="del remove-this" style="cursor:pointer;">X</div>' +
                '</div>');

            $list.on('click', '.remove-this', function () {
                for (var i = 0; i < file.length; i++) {
                    if ($(this).parent().attr('id') == file[i].id) {
                        uploader.removeFile(file[i], true);
                        $(this).parent().remove();
                    }
                }
            });
        }

        var text = '已选择' + uploader.getFiles().length + '个数据文件   ' + te;
        $('#pointInfo').text(text);
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress', function (file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');

        // 避免重复创建
        if (!$percent.length) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo($li).find('.progress-bar');
        }

        $li.find('div.state').text('');

        $percent.css('width', percentage * 100 + '%');
    });

    uploader.on('uploadSuccess', function (f, response) {
        var excelFileNames = [];

        if (response.code === 2019) { //excel解析失败提示失败原因,并终止上传
            layer.alert(response.body);
            //删除第一个元素内容，并新增excel文件到这里
            $("#" + f.id).remove();
            uploader.addFiles(f.source.source);
            return;
        } else if (response.code === 2020) {//excel解析成功,上传其他文件
            var fileReader = new FileReader();

            fileReader.onloadend = function () {
                var filess = '';
                for (var i = 0; i < excelFileNames.length; i++) {
                    filess += excelFileNames[i] + ',';
                }

                $.ajax({//先将文件集合传到后台判断服务器文件是否存在，如果存在则不再上传,返回不存在的文件列表
                        url: '/pqs9900/device/existfile',
                        data: {
                            filename: filess,
                            lineid: 0
                        },
                        type: 'post',
                        success: function (data) {
                            if (data.length === 0) {
                                uploadSuccess();

                                $.post('/pqs9900/device/translate', function (data) {
                                });
                            }

                            var file = judgeFileExits(data, fileNames, excelFileNames);//判断文件是否存在

                            if (file.length > 0) {
                                var str = '文件缺失列表：<br/>';

                                for (var i = 0; i < file.length; i++) {
                                    str += file[i] + '<br/>';
                                }

                                var layId = layer.confirm(str, {
                                    btn: ['继续上传', '取消']
                                }, function () {
                                    count = 0;//初始化为0

                                    for (var i = 0; i < fileNames.length; i++) {
                                        for (var j = 0; j < data.length; j++) {
                                            if (data[j] === fileNames[i]) {
                                                uploader.upload(files[i]);
                                                count++;
                                            }
                                        }
                                    }
                                    layer.close(layId);

                                    if (count === 0) {
                                        uploadSuccess();

                                        $.post('/pqs9900/device/translate', function (data) {
                                        });
                                    }
                                }, function () {
                                    layer.close(layId);
                                });
                            } else {
                                count = 0;//初始化为0

                                for (var i = 0; i < fileNames.length; i++) {
                                    for (var j = 0; j < data.length; j++) {
                                        if (data[j] === fileNames[i]) {
                                            uploader.upload(files[i]);
                                            count++;
                                        }
                                    }
                                }
                            }
                        }
                    }
                );
            }

            fileReader.onload = function (ev) {
                var data = ev.target.result,
                    workbook = XLSX.read(btoa(fixdata(data)), {   //缓存文件内容
                        type: 'base64'
                    }), persons = [];

                for (var sheet in workbook.Sheets) {
                    if (workbook.Sheets.hasOwnProperty(sheet)) {
                        persons = persons.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet]));
                        break; //只读取第一张sheet表单
                    }
                }

                for (var i = 1; i < persons.length; i++) {
                    excelFileNames.push(persons[i].__EMPTY_30);  //统计文件名那列内容以便与已选中的文件进行比对
                }
            }

            fileReader.readAsArrayBuffer(f.source.source);  //读取文件内容
        }

        $('#' + f.id).find('div.state').text('已上传');

        if (bSelect === 0) {
            if (uploader.getStats().successNum + uploader.getStats().uploadFailNum === count + 1 && response.code === 200) {
                uploadSuccess();

                $.post('/pqs9900/device/translate', function (data) {
                });
            }
        } else if (bSelect === 1) {
            if (uploader.getStats().successNum + uploader.getStats().uploadFailNum === uploader.getFiles().length && response.code === 200) {
                uploadSuccess();

                $.post('/pqs9900/device/translate', function (data) {
                });
            }
        }
    });

    uploader.on('uploadError', function (file) {
        $('#' + file.id).find('div.state').text('上传出错');
    });

    uploader.on('uploadComplete', function (file) {
        $('#' + file.id).find('.progress').fadeOut();
    });

    $("#translateState").click(function () {
        demo();
    });

    function demo() {
        layer.open({
            type: 2,
            title: '数据解析状态',
            shadeClose: true,
            shade: 0.8,
            area: ['100%', '100%'],
            content: 'translatestate'
        });
    }

    $("#ctlBtn").click(function () {
        //如果解析线程开启，则不上传
        $.ajax({
            type: 'POST',
            url: '/pqs9900/device/getTranslateState',
            success: function (data) {
                if (data.code === 0) {
                    layer.msg("后台数据正在解析中，请稍候重试");
                } else {
                    files = uploader.getFiles();
                    var file = null;
                    fileNames = [];

                    for (var i = 0; i < files.length; i++) {
                        fileNames.push(files[i].name);

                        if (files[i].name.indexOf(".xlsx") > -1) {
                            file = files[i];
                        }
                    }

                    if (bSelect === 0) {
                        if (file != null) {
                            uploader.upload(file);

                            for (var i = 0; i < files.length; i++) {
                                if (!(files[i].name.indexOf(".xlsx") > -1)) {
                                    uploader.stop(files[i]); //暂停其他文件不上传
                                }
                            }
                        } else {
                            layer.msg('未选中excel文件');
                        }
                    } else if (bSelect === 1) { //选中监测点
                        if (nodeIndex === 0) {
                            layer.msg('未选中监测点');
                            return;
                        } else if (uploader.getFiles().length === 0) {
                            layer.msg('没有选择上传文件');
                            return;
                        }

                        var filess = '';
                        for (var i = 0; i < fileNames.length; i++) {
                            filess += fileNames[i] + ',';
                        }

                        $.ajax({//先将文件集合传到后台判断服务器文件是否存在，如果存在则不再上传,返回不存在的文件列表
                                url: '/pqs9900/device/existfile',
                                data: {
                                    filename: filess,
                                    lineid: nodeIndex,
                                },
                                type: 'post',
                                success: function (data) {
                                    if (data.length === 0) {
                                        uploadSuccess();

                                        $.post('/pqs9900/device/translate', function (data) {
                                        });
                                    } else {
                                        for (var i = 0; i < files.length; i++) {
                                            for (var j = 0; j < data.length; j++) {
                                                if (files[i].name === data[j]) {
                                                    uploader.upload(files[i]);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        );
                    }
                }
            }
        });
    });

    function fixdata(data) { //文件流转BinaryString
        var o = "",
            l = 0,
            w = 10240;
        for (; l < data.byteLength / w; ++l) o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
    }

    function judgeFileExits(excelFiles, filess, excel) { //以excel统计的内容为准,并剔除服务器已存在的文件
        var file = [];

        for (var i = 0; i < excelFiles.length; i++) {
            for (var j = 0; j < filess.length; j++) {
                if (excelFiles[i] === filess[j]) {
                    break;
                } else if (j === filess.length - 1) {
                    file.push(excelFiles[i]);
                }
            }
        }

        return file;
    }

    function initDiv() {
        document.getElementById("tree").style.height = document
                .getElementById("father").offsetHeight
            - document.getElementById("search").offsetHeight - 12 + "px";
    }

    // 关闭所有高亮节点
    function closeHigh() {
        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var allNodes = treeObj.transformToArray(treeObj.getNodes());// 关闭所有节点的高亮

        for (var i = 0; i < allNodes.length; i++) {
            allNodes[i].highlight = false;
            treeObj.updateNode(allNodes[i]);
        }
    }

    function valueChange(value) {
        if (value == '') {
            closeHigh();
        }
    }

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

        var treeObj = $.fn.zTree.getZTreeObj("tree");
        var nodes = treeObj.getNodesByParamFuzzy("name", value);// 获取搜索的节点

        closeHigh();

        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);
        }
    }

    //数据库获取离线终端树数据
    function getData() {
        $.ajax({
            url: "/pqs9900/device/offLinetree",
            type: "post",
            async: false,
            dataType: "json",
            data: {},
            success: function (data) {
                if (data.code == 500 || data.body == null) {
                    layer.msg("获取终端树内容失败.");
                } else {
                    initTree(data.body);
                }
            }
        });
    }

    // 初始化终端树
    function initTree(treeData) {
        if (treeData.length == 0) {
            layer.msg("数据库数据为空,终端树加载失败.");
            return;
        }

        var datalist = [];
        for (var i = 0; i < treeData.length; i++) {
            var str = '';

            str += '{' + "id:" + treeData[i].id;
            str += ',' + "name:'" + treeData[i].name + "'";
            str += ',' + "nodeIndex:" + treeData[i].nodeIndex;
            str += ',' + "nodeType:" + treeData[i].nodeType;
            str += ',' + "ppId:" + treeData[i].ppId;
            if (treeData[i].nodeType == "0") {
                str += ',' + "open:" + true;
            } else {
                str += ',' + "open:" + false;
            }
            str += ',' + "pId:" + treeData[i].pId + '}';
            datalist.push(str);
        }

        datalist = eval('[' + datalist + ']');// string->json数组
        var zNodes = datalist;

        $.fn.zTree.init($("#tree"), setting, zNodes);
    }

    function uploadSuccess() {
        $list.find('div.state').text('处理完成');

        var layId = layer.confirm('文件上传成功，注意数据解析需要较长时间!', {
            btn: ['确定']
        }, function () {
            demo();
            uploader.reset();
            count = 0;//初始化为0
            $list.html('<b style="margin-left: 5px;margin-bottom: 6px;">文件列表：</b>');
            layer.close(layId);
        });
    }

    $('#clear').click(function () {
        bSelect = 0;
        count = 0;//初始化为0
        uploader.reset();
        $list.html('<b style="margin-left: 5px;margin-bottom: 6px;">文件列表：</b>');
        $('#pointInfo').text('');
        nodeIndex = 0;
    });

    $('#download').click(function () {
        window.location.href = "/pqs9900/device/export";
    });
</script>
</html>
