 var zdata = [];
 var dept_tree = null;
 var edittype = "add";
 var UserMap = new HashMap()
 var cols = [{
     width: 10,
     text: '序号',
     type: 'number',
     flex: false,
     colClass: 'text-center'
 }, {
     width: 30,
     text: '账号',
     type: 'string',
     flex: false,
     colClass: 'text-center'
 }, {
     width: 30,
     text: '姓名',
     type: 'string',
     flex: false,
     sort: 'down',
     colClass: 'text-center'
 }, {
     width: 40,
     text: '工号',
     type: 'string',
     flex: true,
     colClass: 'text-center'
 }, {
     width: 80,
     text: '手机号',
     type: 'string',
     flex: false,
     sort: 'down',
     colClass: 'text-center'
 }, {
     width: 150,
     text: '角色',
     type: 'string',
     flex: true,
     colClass: 'text-center'
 }, {
     width: 200,
     text: '操作',
     type: 'string',
     flex: true,
     colClass: 'text-center'
 }];

 var roles = [];
 $(document).ready(function() {
     getJob();

     //  $("#main_content_title").html("用户管理")

     $('#dashboard').dashboard({ draggable: true });
     var zTreeObj;
     var zNodes = [];
     dept_tree = $.fn.zTree.init($("#department_tree"), {}, zNodes);

     getDept();

     $("#user_add").on("click", function() {
         var nodedata = dept_tree.getSelectedNodes();
         edittype = "add"
         loadUserData(nodedata)
         $('#addUserModal').modal('show')
     })

     RoleGetALLNoData(function(data) {

         roles = [];
         for (var i = 0; i < data.length; i++) {
             var m = data[i];
             var zdataItem = {};
             zdataItem["id"] = m.id;
             zdataItem["title"] = m.des;
             roles.push(zdataItem);
         }
     }, function(error) {

     });


     $("#dept_add").on("click", function() {
         var nodedata = dept_tree.getSelectedNodes();
         edittype = "add"
         loadData(nodedata)
         $('#addModal').modal('show')
     })

     $("#dept_edit").on("click", function() {
         //获取选中的节点
         var nodedata = dept_tree.getSelectedNodes();
         if (nodedata.length < 1) {
             layer.msg('请先选择部门！', {
                 time: 2000, //20s后自动关闭
             });
             return;
         }
         edittype = "edit"
         loadData(nodedata)
         $('#addModal').modal('show');

     });

     $("#dept_delete").on("click", function() {

         //获取选中的节点
         var nodedata = dept_tree.getSelectedNodes();
         if (nodedata.length < 1) {
             layer.msg('请先选择部门！', {
                 time: 2000, //20s后自动关闭
             });
             return;
         }
         layer.confirm('您确定要删除该部门？', {
             offset: "auto",
             shade: 0,
             btn: ['确定'] //按钮
         }, function() {
             deleteItem4CallBack(function() {
                 DeptDelete(nodedata[0].id, function(data) {
                     layer.msg('删除成功！', {
                         time: 2000, //20s后自动关闭
                     });
                     dept_tree.removeNode(nodedata[0]);
                 }, function(error) {});
             });
         });


     });



     $('.datatable').datatable({
         checkable: false,
         sortable: false,
         data: {
             cols: cols,
             rows: []
         }
     });


     $('.datatable').on('click', 'button', function() {
         if (this.name == "user_edit") {
             edittype = "edit"
             var user = UserMap.get(parseInt(this.id));
             loadUserData(user)
             $('#addUserModal').modal('show')
         }
         if (this.name == "user_delete") {
             var offset = "auto";

             var userId = this.id;
             var user = UserMap.get(parseInt(userId));

             layer.confirm('您确定要删除 "' + user.truename + '" ？', {
                 offset: offset,
                 shade: 0,
                 btn: ['确定', '取消'] //按钮
             }, function() {
                 UserDelete({ "id": userId }, function(data) {
                         layer.msg('用户删除成功！', {
                             time: 2000, //20s后自动关闭
                         }, function() {
                             var nodedata = dept_tree.getSelectedNodes();
                             updateUser(nodedata[0].id)
                         });
                     },
                     function(error) {

                     })
             }, function(index) {
                 layer.close(index);
             });
         }

         if (this.name == "user_tansfer") {
             var user = UserMap.get(parseInt(this.id));
             var id = this.id;
             scoreLayer = showPopup4Common('选择目标收费站', function() {
                 transferFs(id);
             }, ['400px', '200px'], '#transfer_div');
             setFeSelect("#tansferFsList", user.organid);
         }
     });
 });

 function transferFs(id) {
     var dept = $("#tansferFsList").val();
     if (dept) {
         var parm = {
             "id": id,
             "organid": dept
         };
         UserUpdate(parm, function(data) {
             layer.msg('转站成功！', {
                 time: 2000, //20s后自动关闭
             }, function() {
                 $('#addUserModal').modal('hide')
                 updateUser(dept_selectinput.value)
             });
         }, function(error) {

         });
     } else {
         layer.msg('请选择转移部门！', {
             time: 2000, //20s后自动关闭
         });
     }
 }

 function getDept() {
     function zTreeOnRename(event, treeId, treeNode, isCancel) {
         alert(treeNode.tId + ", " + treeNode.name);
     }

     //  function zTreeBeforeDrop(treeId, treeNodes, targetNode, moveType) {
     //      return !(targetNode == null || (moveType != "inner" && !targetNode.parentTId));
     //  };

     function zTreeOnRemove(event, treeId, treeNode) {
         alert(treeNode.tId + ", " + treeNode.name);
     }

     function zTreeOnClick(event, treeId, treeNode) {
         updateUser(treeNode.id)
     };


     var setting = {
         data: {
             simpleData: {
                 enable: true,
                 idKey: "id",
                 pIdKey: "pId",
                 rootPId: null
             }
         },
         view: { //表示tree的显示状态
             selectMulti: false //表示禁止多选
         },
         check: { //表示tree的节点在点击时的相关设置
             enable: false, //是否显示radio/checkbox
             chkStyle: "checkbox", //值为checkbox或者radio表示
             checkboxType: { p: "", s: "" }, //表示父子节点的联动效果
             radioType: "level" //设置tree的分组
         },
         callback: {
             onRename: zTreeOnRename,
             //  beforeDrop: zTreeBeforeDrop,
             onRemove: zTreeOnRemove,
             onClick: zTreeOnClick
         },
         edit: {
             enable: true,
             drag: {
                 autoExpandTrigger: true,
                 isMove: true,
                 prev: false,
                 next: true,
                 inner: true,
                 autoOpenTime: 0
             },
             showRenameBtn: false,
             showRemoveBtn: false
         }
     };

     DeptGetAll(function(data) {
         zdata = [];
         for (var i = 0; i < data.length; i++) {
             var m = data[i];
             var zdataItem = {};
             zdataItem["id"] = m.id;
             zdataItem["value"] = m.id;
             zdataItem["pId"] = null;
             zdataItem["name"] = m.organname;
             zdataItem["open"] = true;
             zdataItem["children"] = addobj(m);
             zdata.push(zdataItem);
         }
         dept_tree = $.fn.zTree.init($("#department_tree"), setting, zdata)
     }, function(error) {

     });
 }



 function addobj(data) {
     var zdata = [];
     if (typeof(data.childs) != "undefined" && data.childs != null &&
         data.childs.length > 0) {
         for (var i = 0; i < data.childs.length; i++) {
             var m = data.childs[i];
             var zdataItem = {};
             zdataItem["id"] = m.id;
             zdataItem["value"] = m.id;
             zdataItem["pId"] = data.id;
             zdataItem["icon"] = "";
             zdataItem["open"] = true;
             zdataItem["name"] = m.organname;
             zdataItem["children"] = addobj(m);
             zdata.push(zdataItem);
         }
         return zdata;
     } else {
         return [];
     }
 }

 function updateUser(organid) {
     var userData = {
         "organid": organid
     }

     UserGetList(userData, function(data) {
             //跟新table
             var rowdata = [];
             if (data != null && data.length > 0) {
                 for (var i = 0; i < data.length; i++) {
                     var user = data[i];

                     var attr = "";
                     if (user.roles.length > 0) {
                         for (var j = 0; j < user.roles.length; j++) {
                             var at = user.roles[j];
                             if (attr.length > 0) {
                                 attr += "," + at.des;
                                 continue;
                             }
                             attr += at.des;
                         }
                     }


                     UserMap.set(user.id, user)
                     var userdata = {};
                     userdata["checked"] = false;
                     var btns = '<button class="btn btn-primary btn-sm" name="user_edit" id=' + user.id + '><i class="icon icon-edit"></i>修改</button> <button class="btn btn-danger btn-sm" name="user_tansfer" id=' + user.id + '><i class="icon icon-random"></i>转站</button>';
                     if (!roleContains("STATION")) {
                         btns += '<button class="btn btn-primary btn-sm" name="user_delete" id=' + user.id + ' ><i class="icon icon-remove-circle"></i>删除</button>';
                     }
                     userdata["data"] = [i + 1, user.username, user.truename, stringlimit(user.workno == null ? -1 : user.workno, 6), stringlimit(user.mobile == null ? "" : user.mobile, 4), attr, btns];
                     rowdata.push(userdata);
                 }
             }
             // 使用data参数更新数据：
             $('.datatable').datatable('load', {
                 cols: cols,
                 rows: rowdata
             });

         },
         function(error) {

         });
 }

 function stringlimit(string, linmit) {
     if (string.length < linmit) return string;
     return string.substr(0, linmit / 2) + "..." + string.substr(string.length - linmit / 2, linmit / 2)
 }