<%@ page contentType="text/html;charset=UTF-8" %>
<script type="text/javascript">
		$(document).ready(function() {
		//zTree初始化
			$.getJSON("${ctx}/sg/managementCenter/constructionProject/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);
                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//设置初始化节点关闭
                });
            });
            $.getJSON("${ctx}/sg/managementCenter/constructionProject/treeData",function(data){
                jstreeTime(data)
            });
            //搜索
            var search1 = function(e) {
                var pattern = $.trim($('#input-search1').val());
                var options = {
                    ignoreCase: $('#chk-ignore-case').is(':checked'),
                    exactMatch: $('#chk-exact-match').is(':checked'),
                    revealResults: $('#chk-reveal-results').is(':checked')
                };
                $('#jstreeTime').treeview('search', [ $.trim($('#input-search1').val()), { ignoreCase: false, exactMatch: false } ]);
                var results = $('#jstreeTime').treeview('search', [ pattern, options ]);
            }
            $('#btn-search1').on('click', search1);
            $('#btn-clear-search1').on('click', function (e) {
                $('#jstreeTime').treeview('clearSearch');
                $('#input-search1').val('');
                $('#jstreeTime').treeview('collapseAll', {
                    silent : false//设置初始化节点关闭
                });
            });
            $('#selectId1').click(function () {
                var object = $('#jstreeTime').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);
                minus(sureStr);
            })
            //表格初始化
            $('#table').bootstrapTable({
                //请求方法
                method: 'post',
                //类型json
                dataType: "json",
                contentType: "application/x-www-form-urlencoded",
                //是否显示行间隔色
                //显示刷新按钮
                showRefresh: true,
                //是否显示分页（*）
                pagination: true,
                //排序方式
                sortOrder: "asc",
                //初始化加载第一页，默认第一页
                pageNumber:1,
                //每页的记录行数（*）
                pageSize: 5,
                //可供选择的每页的行数（*）
                pageList: [5,10, 25, 50, 100],
                //这个接口需要处理bootstrap table传递的固定参数,并返回特定格式的json数据
                url: "${ctx}/sg/managementCenter/constructionProjectTemporaryController/dataPlan",
                //默认值为 '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].htmlStatus=="2"){
                            // this.data.rows[i].setAttribute("style","color: red;");
                            rows[i+1].style.backgroundColor = "#e6e6e6"
                        }
                    }
                },
                onShowSearch: function () {
                    $("#search-collapse").slideToggle();
                },
                columns: [{
                    checkbox: true

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

                }, {
                    field: 'projectName',
                    title: '项目名称'
                }, {
                    field: 'powerScope',
                    title: '停电范围'
                }
                ]

            });

        })

        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){
        jp.loading();
        jp.post("${ctx}/sg/managementCenter/constructionProject/unplanned",{'ids':ids},function(data){
            if(data.success){
                refresh();
                // jstreeTime(data.mapList);
                jstree(data.mapListTree);
                jp.success("安排计划成功")
            }else{
                jp.error(data.message);
            }
        })
    }
    function getIds() {
        return $("#parentIds").val();
    }
    function jstree(date) {
        $('#jstree').treeview({
            data: date,
            levels: 1,
            highlightSelected:false,
            showCheckbox:true,
        });
    }
    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();
        }
        jp.confirm('确认要退回项目吗？', function(){
            jp.loading();
            $.get("${ctx}/sg/managementCenter/constructionProjectTemporaryController/deleteAll?ids=" +ids, function(data){
                if(data.success){
                    jstree(data.mapListTree);
                    refresh();
                    jp.success(data.message);
                }else{
                    jp.error(data.message);
                }
            })
        })
    }
    function getIdSelections() {
        return $.map($("#table").bootstrapTable('getSelections'), function (row) {
            return row.id
        });
    }
</script>
