<%@ page contentType="text/html;charset=UTF-8" %>
<script type="text/javascript">
		$(document).ready(function() {
		//zTree初始化
			$.getJSON("${ctx}/sg/managementCenter/projectDailyPlan/bootstrapTreeTable",function(data){
                jstree(data);
                dateTimeValue('1');
			});
            $('#selectId').click(function () {
                var object = $('#jstree').treeview('getChecked');
                if (object.length<1){
                    jp.error("请选择项目！")
                    return false;
                }
                var str = "";
                for (var  i = 0; i < object.length; i++) {
                    str+=object[i].id+",";
                }
                var sureStr  = str.substring(0,str.length-1);
                $("#parentIds").val(sureStr);
                // alert(sureStr);
                add(sureStr);
            });
            //搜索
            var findSearchableNodes = function() {
                return $('#jstree').treeview('search', [ $.trim($('#input-search').val()), { ignoreCase: false, exactMatch: false } ]);
            };
            var search = function(e) {
                var pattern = $.trim($('#input-search').val());
                var options = {
                    ignoreCase: $('#chk-ignore-case').is(':checked'),
                    exactMatch: $('#chk-exact-match').is(':checked'),
                    revealResults: $('#chk-reveal-results').is(':checked')
                };
                $('#jstree').treeview('search', [ $.trim($('#input-search').val()), { ignoreCase: false, exactMatch: false } ]);
                var results = $('#jstree').treeview('search', [ pattern, options ]);
            }
            $('#btn-search').on('click', search);
            $('#btn-clear-search').on('click', function (e) {
                $('#jstree').treeview('clearSearch');
                $('#input-search').val('');
                $('#jstree').treeview('collapseAll', {
                    silent : false//设置初始化节点关闭
                });
            });
            //表格初始化
            $('#table').bootstrapTable({
                //请求方法
                method: 'post',
                //类型json
                dataType: "json",
                contentType: "application/x-www-form-urlencoded",
                //是否显示行间隔色
                //显示刷新按钮
                showRefresh: true,
                //是否显示分页（*）
                // pagination: true,
                //排序方式
                sortOrder: "asc",
                //初始化加载第一页，默认第一页
                pageNumber:1,
                //每页的记录行数（*）
                pageSize: 100,
                //可供选择的每页的行数（*）
                pageList: [5,10, 25, 50, 100],
                //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据
                url: "${ctx}/sg/managementCenter/projectDailyPlan/dailyPlanProject",
                //默认值为 'limit',传给服务端的参数为：limit, offset, search, sort, order Else
                //queryParamsType:'',
                ////查询参数,每次调用是会带上这个参数，可自定义
                queryParams : function(params) {
                    var searchParam = $("#searchForm").serializeJSON();
                    searchParam.pageNo = params.limit === undefined? "1" :params.offset/params.limit+1;
                    searchParam.pageSize = params.limit === undefined? -1 : params.limit;
                    searchParam.orderBy = params.sort === undefined? "" : params.sort+ " "+  params.order;
                    return searchParam;
                },
                //分页方式：client客户端分页，server服务端分页（*）
                sidePagination: "server",
                contextMenuTrigger:"right",//pc端 按右键弹出菜单
                contextMenuTriggerMobile:"press",//手机端 弹出菜单，click：单击， press：长按。
                contextMenu: '#context-menu',
                onContextMenuItem: function(row, $el){
                    if($el.data("item") == "edit"){
                        edit(row.id);
                    } else if($el.data("item") == "delete"){
                        deleteAll(row.id);
                    }
                },
                onClickRow: function(row, $el){
                },
                onLoadSuccess:function(data) {
                    var split = data.rows;
                    var tb = document.getElementById('table');    // table 的 id
                    var rows = tb.rows;                           // 获取表格所有行
                    for (var i =0;i<split.length;i++){
                        if (split[i].flagYesElectricity=="1"){
                            // this.data.rows[i].setAttribute("style","color: red;");
                            rows[i+1].style.color = "red"
                        }
                    }
                },
                onShowSearch: function () {
                    $("#search-collapse").slideToggle();
                },
                columns: [{
                    checkbox: true

                }, {
                    field: 'projectNumber',
                    title: '项目定义号',

                }, {
                    field: 'projectName',
                    title: '项目名称'
                }, {
                    field: 'projectPowerRange',
                    title: '停电范围',
                }
                    ,{
                        field: 'constructionUnit',
                        title: '施工单位项目经理',

                    }
                    ,{
    field: 'remarks',
    title: '备注',
    width:120
}
                ]

            });

        })

        if(navigator.userAgent.match(/(iPhone|iPod|Android|ios)/i)){//如果是移动端
            $('#table').bootstrapTable("toggleView");
        }

        $('#table').on('check.bs.table uncheck.bs.table load-success.bs.table ' +
            'check-all.bs.table uncheck-all.bs.table', function () {
            $('#remove').prop('disabled', ! $('#table').bootstrapTable('getSelections').length);
            $('#edit').prop('disabled', $('#table').bootstrapTable('getSelections').length!=1);
        });
    //安排计划时间
    function add(ids){
        if(null==ids||ids==""){
            jp.error("请选择日计划安排的项目");
        }else{
            jp.post("${ctx}/sg/managementCenter/projectDailyPlan/unDailyPlanned",{'ids':ids},function(data){
                if(data.success){
                    refresh();
                    // jstreeTime(data.mapList);
                    jstree(data.mapListTree);
                    jp.success(data.message)
                }else{
                    jp.error(data.message);
                }
            })
        }
    }
    function getIds() {
        return $("#parentIds").val();
    }
    function jstree(date) {
        $('#jstree').treeview({
            data: date,
            levels: 1,
            highlightSelected:false,
            showCheckbox:true,
            onNodeChecked: function (event, node) { //选中节点
                var selectNodes = getChildNodeIdArr(node); //获取所有子节点
                if (selectNodes) { //子节点不为空，则选中所有子节点
                    $('#jstree').treeview('checkNode', [selectNodes, { silent: true }]);
                }
                // var parentNode = $("#jstree").treeview("getNode", node.parentId);
                // setParentNodeCheck(node);
            },
            onNodeUnchecked: function (event, node) { //取消选中节点
                // 取消父节点 子节点取消
                var selectNodes = setChildNodeUncheck(node); //获取未被选中的子节点
                var childNodes = getChildNodeIdArr(node);    //获取所有子节点
                if (selectNodes && selectNodes.length == 0) { //有子节点且未被选中的子节点数目为0，则取消选中所有子节点
                    $('#tree').treeview('uncheckNode', [childNodes, { silent: true }]);
                }
                // 取消节点 父节点取消
                var parentNode = $("#jstree").treeview("getNode", node.parentId);  //获取父节点
                var selectNodes = getChildNodeIdArr(node);
                setParentNodeCheck(node);
            }
        });
    }
    // function jstreeTime(date) {
    //     $('#jstreeTime').treeview({
    //         data: date,
    //         levels: 1,
    //         highlightSelected:false,
    //         showCheckbox:true,
    //         onNodeSelected: function(event, treeNode) {
    //             var id = treeNode.id;
    //             jp.openSaveDialog('编辑安排计划项目', "${ctx}/sg/managementCenter/constructionProject/formPlan?id=" + id, '800px', '500px');
    //         },
    //
    //     });
    // }
    function dateTimeValue(value) {
        if (value != '1'){
            $("#dateTimeId").val(value);
        }else {
            var date = new Date();
            var str = date.toISOString();
            $("#dateTimeId").val( str.substring(0,7));
        }
    }

    function selected(data){
        if(data.nodeId == undefined){
            for (var i = 0; i < data.nodes.length; i++) {
                $("#jstree").treeview('checkNode', [ data.nodes[i], {silent: true}]);
            }
        }else{
            var parentNode = $('#jstree').treeview('getParent', data.nodeId);
            $("#jstree").treeview('checkNode', [ parentNode, {silent: true}]);
        }
    }
    function unSelected(node){
        if(node.id == undefined){
            for (var i = 0; i < node.nodes.length; i++) {
                $("#jstree").treeview('uncheckNode', [ node.nodes[i], {silent: true}]);
            }
        }else{
            var parentNode = $('#jstree').treeview('getParent', node.nodeId);
            var num;
            for (var i = 0; i < parentNode.nodes.length; i++) {
                if(parentNode.nodes[i].state.checked == true){
                    num=1;
                }
            }
            if(num!=1){
                $("#jstree").treeview('uncheckNode', [ parentNode, {silent: true}]);
            }
            console.log(parentNode);
        }
    }
    function refresh() {
        $('#table').bootstrapTable('refresh');
    }
    function deleteAll(ids){
        if(!ids){
            ids =  getIdSelections();
        }
        if(null!=ids&&ids!=""){
            jp.confirm('确认要取消吗？', function(){
                jp.loading();
                $.get("${ctx}/sg/managementCenter/projectDailyPlan/cancelPackage?ids=" +ids, function(data){
                if(data.success){
                    jstree(data.mapListTree);
                    refresh();
                    jp.success(data.message);
                }else{
                    jp.error(data.message);
                }
                 })
                })
        }else{
            jp.error("请选择取消的项目");
        }

    }
function planPowerPacker(ids){
    if(!ids){
        ids =  getIdSelections();
    }
    if (null!=ids&&""!=ids){
        $.post("${ctx}/sg/managementCenter/projectPlanArrage/unplannedPackage?ids=" +ids, function(data){
            if(data.success){
                jstree(data.mapListTree);
                refresh();
                jp.success(data.message);
            }else{
                jp.error(data.message);
            }
        })
    } else {
        jp.error("请选择项目!");
    }

}
function cancelPowerPacker(ids){
    if(!ids){
        ids =  getIdSelections();
    }
    if (null!=ids&&""!=ids){
        $.post("${ctx}/sg/managementCenter/projectDailyPlan/cancelPackage?ids=" +ids, function(data){
            if(data.success){
                jstree(data.mapListTree);
                refresh();
                jp.success(data.message);
            }else{
                jp.error(data.message);
            }
        })
    } else {
        jp.error("请选择项目!");
    }

}
function getRemarksBack(ids){
    if(!ids){
        ids =  getIdSelections();
    }
    $("#idsRemark").val(ids);
    if (null!=ids&&""!=ids){
        jp.prompt("填写备注", function (message) {
            jp.post("${ctx}/sg/managementCenter/projectDailyPlan/remarksBack",
                {
                    "ids": $("#idsRemark").val(),
                    "remarks": window.encodeURI(message)
                },
                function (data) {
                    if(data.success){
                        jstree(data.mapListTree);
                        refresh();
                        jp.success(data.message);
                    }else{
                        jp.error(data.message);
                    }
                })
        });
    } else {
        jp.error("请选择项目!");
    }

}
    function getIdSelections() {
        return $.map($("#table").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
function getChildNodeIdArr(node) {
    var ts = [];
    if (node.children) {
        for (x in node.children) {
            ts.push(node.children[x].nodeId);
            if (node.children[x].children) {
                var getNodeDieDai = getChildNodeIdArr(node.children[x]);
                for (j in getNodeDieDai) {
                    ts.push(getNodeDieDai[j]);
                }
            }
        }
    } else {
        ts.push(node.nodeId);
    }
    return ts;
}

// 选中所有子节点时，选中父节点 取消子节点时取消父节点
function setParentNodeCheck(node) {
    var parentNode = $("#jstree").treeview("getNode", node.parentId);
    if (parentNode.children) {
        var checkedCount = 0;
        for (x in parentNode.children) {
            if (parentNode.children[x].state.checked) {
                checkedCount++;
            } else {
                break;
            }
        }
        if (checkedCount == parentNode.children.length) {  //如果子节点全部被选 父全选
            $("#jstree").treeview("checkNode", parentNode.nodeId);
            setParentNodeCheck(parentNode);
        } else {   //如果子节点未全部被选 父未全选
            $('#jstree').treeview('uncheckNode', parentNode.nodeId);
            setParentNodeCheck(parentNode);
        }
    }
}

// 取消父节点时 取消所有子节点
function setChildNodeUncheck(node) {
    if (node.children) {
        var ts = [];    //当前节点子集中未被选中的集合
        for (x in node.children) {
            if (!node.children[x].state.checked) {
                ts.push(node.children[x].nodeId);
            }
            if (node.children[x].nodes) {
                var getNodeDieDai = node.children[x];
                console.log(getNodeDieDai);
                for (j in getNodeDieDai) {
                    if (!getNodeDieDai.state.checked) {
                        ts.push(getNodeDieDai[j]);
                    }
                }
            }
        }
    }
    return ts;
}
</script>
