$(function () {
    initialPage();
    getGrid("../sys/dept/list?name=");
});

function initialPage() {
    $(window).resize(function () {
        TreeGrid.table.resetHeight({height: $(window).height() - 100});
    });
}

const deptData = {}

function getGrid(url) {
    var colunms = TreeGrid.initColumn();
    var table = new TreeTable(TreeGrid.id, url, colunms);
    table.setExpandColumn(2);
    table.setIdField("deptId");
    table.setCodeField("deptId");
    table.setParentCodeField("parentId");
    table.setExpandAll(true);
    table.setHeight($(window).height() - 100);
    table.init();
    TreeGrid.table = table;
}

var TreeGrid = {
    id: "deptTable",
    table: null,
    layerIndex: -1
};


/**
 * 初始化表格的列
 */
TreeGrid.initColumn = function () {
    var columns = [
        {field: 'selectItem', radio: true},
        {title: '公司ID', field: 'deptId', visible: false, align: 'center', valign: 'middle', width: '80px'},
        {title: '公司名称', field: 'name', align: 'center', valign: 'middle', sortable: true, width: '180px'},
        {title: '上级公司', field: 'parentName', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '可新增员工数', field: 'staffNum', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '已有员工数', field: 'staffNum', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '排序号', field: 'orderNum', align: 'center', valign: 'middle', sortable: true, width: '100px'},
        {title: '到期时间', field: 'expirationDate', align: 'center', valign: 'middle', sortable: true, width: '100px'}]
    return columns;
};

var setting = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url: "nourl"
        }
    }
};
var ztree;

var vm = new Vue({
    el: '#rrapp',
    data: {
        comfirmActive:1,
        showList: true,
        title: null,
        dept: {
            parentName: null,
            parentId: 0,
            orderNum: 0
        },
        q: {
            name: ''
        },
        ruleValidate: {
            name: [
                {required: true, message: '公司名称不能为空', trigger: 'blur'}
            ]
        }
    },
    methods: {
        getDept: function () {
            //加载公司树
            Ajax.request({
                url: "../sys/dept/select",
                async: true,
                successCallback: function (r) {
                    ztree = $.fn.zTree.init($("#deptTree"), setting, r.deptList);
                    var node = ztree.getNodeByParam("deptId", vm.dept.parentId);
                    if (node) {
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    } else {
                        node = ztree.getNodeByParam("deptId", 0);
                        ztree.selectNode(node);
                        vm.dept.parentName = node.name;
                    }
                }
            });
        },
        validatorDept:function (id,cb) {
            Ajax.request({
                url: "../sys/dept/countDeptLevel?deptId=" + id,
                async: true,
                successCallback: function (r) {
                    cb(r)
                }
            });
        },
        add: function () {
           
            var deptId = TreeGrid.table.getSelectedRow();
            var parentId = 0;
            if (deptId.length != 0) {
                parentId = deptId[0].id;
            }
            
            if (parentId === 0) {
                vm.showList = false;
                vm.title = "新增";
                vm.dept = {parentName: null, parentId: parentId, orderNum: 0};
                vm.getDept();
                return
            }

            this.validatorDept(parentId || deptId,function (r) {
                if (r.num<5) {
                    vm.showList = false;
                    vm.title = "新增";
                    vm.dept = {parentName: null, parentId: parentId, orderNum: 0};
                    vm.getDept();
                }
                else{
                   return alert('部门层级已经达到5层了，无法再创建子部门');
                }
            })
           
        },
        update: function () {
            var deptId = getDeptId();
            if (!deptId) {
                return;
            }
            Ajax.request({
                url: "../sys/dept/info/" + deptId,
                async: true,
                successCallback: function (r) {
                    vm.showList = false;
                    vm.title = "修改";
                    vm.dept = r.dept;

                    vm.getDept();
                }
            });
        },
        del: function () {
            var deptId = getDeptId();
            if (!deptId) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../sys/dept/delete",
                    params: {"deptId": deptId},
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        saveOrUpdate: function (event) {
            var url = vm.dept.deptId == null ? "../sys/dept/save" : "../sys/dept/update";
            Ajax.request({
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.dept),
                type: 'POST',
                successCallback: function () {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        query:function () {
            getGrid('../sys/dept/list?name='+vm.q.name);
        },
        deptTree: function () {
            openWindow({
                title: "选择公司",
                area: ['300px', '450px'],
                content: jQuery("#deptLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var node = ztree.getSelectedNodes();
                    //选择上级公司
                    vm.validatorDept(node[0].deptId,function (r) {
                        if (r.num<5) {
                            vm.dept.parentId = node[0].deptId;
                            vm.dept.parentName = node[0].name;
                            layer.close(index);
                        }
                        else{
                           return alert('部门层级已经达到5层了，无法再创建子部门');
                        }
                    })
                    
                }
            });
        },
        reload: function () {
            vm.showList = true;
            TreeGrid.table.refresh();
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        }
    }
});

function getDeptId() {
    var selected = $('#deptTable').bootstrapTreeTable('getSelections');
    if (selected.length == 0) {
        alert("请选择一条记录");
        return false;
    } else {
        return selected[0].id;
    }
}