var strTableP0604 = "Tbmxx";

//重新加载treegrid数据
function reloadData(tbId) {
    try {
        var s = ParseData(window.external.DoOptions(tbId, 'GetList', '{}'));
        loadTreeData(tbId, s.Records);
        s = null;
    } catch (e) { }
}

// =================jqgrid非重复值判断==============
//添加时判断jqgrid某列中是否存在值
//colName---判断的列名
//val----------要比较的值
//bSel--------是否比较选中行的值
//tdId---------grid 的id

function isKeyExist(tbId, colName, val, bSel) {
    val = trim(val);
    var exist = false;
    var cols = [];
    var ids = $("#" + tbId).getDataIDs();
    for (var i = 0; i < ids.length; i++) {
        var c = $("#" + tbId).getRowData(ids[i]);
        cols.push(trim(c[colName]));
    }
    if (bSel) {
        var selId = $("#" + tbId).getGridParam("selrow");
        var selIdx = $("#" + tbId).getInd(selId) - 1;
        for (var i = 0; i < cols.length; i++) {
            if (i != selIdx) { if (val == cols[i]) { exist = true; break; } }
        }
    } else {
        for (var i = 0; i < cols.length; i++) {
            if (val == cols[i]) {
                exist = true; break;
            }
        }
    }
    return exist;
}

//关闭对话框
function closeMyDlg(dlgId, strType, tbId) {
    try {
        var $dlgId = $("#" + dlgId);
        var isChange = $dlgId.data("change");
        if (!isChange) {
            cihoDlgClose(dlgId);
        } else {
            window.parent.cihoAlert(msg.other.haveChange, msgBox.dlgBtn.YesNoCancel, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    saveMyData(dlgId, 1, tbId);             //保存数据
                } else if (msgBox.dlgRst.No == strRet) {
                    closeMySelf("divmessage", dlgId);
                    cihoDlgClose(dlgId);
                }
            }
        );
        }
    } catch (e) { }
}

//打开部门信息窗口
//state：1   新增根节点
//state：2   新增下一级
//state：3   修改
function openBMXX(state, rowId) {
    try {
        var dlgId = "divP0604";
        var tbId = strTableP0604;

        if (state == 3 && !selItem) return;

        //创建对话框
        creatDiv_ShowDialog(dlgId, "部门信息", true, true, tbId);

        //获取编号，并创建头部的所属信息
        var eleArray = [];

        switch (state) {
            case 1:                     //新增根节点
                var newbh = ParseData(window.external.DoOptions('Tbmxx', 'MakeBH', '{"ParentBH":"0"}'));
                var data = { bh: newbh.BH, state: 1 };
                $("#" + dlgId).data("data", data);
                break;
            case 2:
                if (rowId) {             //新增下一级
                    var item = $("#" + tbId).getRowData(rowId);
                    if (item) {
                        eleArray.push('<h3 id="idH3">所属：');
                        eleArray.push(trim(item.a3));
                        eleArray.push('</h3>');
                    }
                    var newbh = ParseData(window.external.DoOptions('Tbmxx', 'MakeBH', '{"ParentBH":"' + item.bh + '"}'));
                    var data = { bh: newbh.BH, rowId: rowId, state: 2 };                 //新增下一级
                    $("#" + dlgId).data("data", data);
                }
                break;
            case 3:                      //修改
                var item = $("#" + tbId).getRowData(rowId);
                var pNode = $("#" + tbId).getNodeParent(item);
                if (pNode) {
                    eleArray.push('<h3 id="idH3">所属：');
                    eleArray.push(trim(pNode.a3));
                    eleArray.push('</h3>');
                }
                break;
        }
        $("#" + dlgId + "_pop_box_top").append(eleArray.join(""));

        //创建并追加表单元素
        var inputs = '<ul><li><span>部门编号：</span><input type="text" name="depID" id="depID"  maxlength="10" onkeypress="return checkValidate(event)"/></li><li><span><font color="red">*</font>部门名称：</span><input type="text" name="depName" id="depName"  maxlength="50" onkeypress="return checkValidate(event)"/></li></ul>';

        $("#" + dlgId + "_divform").append(inputs);

        //修改时为表单元素赋默认值
        if (state == 3) {
            var item = $("#" + tbId).getRowData(rowId);
            $("#depID").val(escape(item.a1));
            $("#depName").val(escape(item.a3));
            var data = { bh: item.bh, state: 3, rowId: rowId };
            $("#" + dlgId).data("data", data);
        } else {
            $("#depID").val(escape(newbh.a1));
        }
        $("#" + dlgId).data("change", false);
        $(":input[name]", "#" + dlgId).change(function () { $("#" + dlgId).data("change", true); });
        setTimeout('$("#depName").focus();',100);
        
    } catch (e) { }
}

/*----------------------------------保存部门信息------------------------------
//数据有效性验证：
//              必填项，是否为空；
//              数据格式是否正确。
// 1  保存退出
// 2  保存增加
-----------------------------------------------------------------------------*/

function saveMyData(dlgId, strType, tbId) {
    try {
        var depID = trim($("#depID").val());
        var depName = trim($("#depName").val());
        var data = $("#" + dlgId).data("data");

        //如果不存在部门名称
        if (!depName) {
            window.parent.cihoAlert(msg.sz.bm.nameEmp, msgBox.dlgBtn.Ok, function () { $("#depName", "#" + dlgId).focus(); });
            return false;
        }
        var existName = false;
        var existID = false;


        //新增下一级或者新增根节点时，验证tree里面是否已经有了该部门名称
        if (data.state == 1 || data.state == 2) {                                 //state ：1 新增根节点        state：2 新增下一级
            existName = isKeyExist(tbId, "a3", depName, false);
        } else if (data.state == 3) {
            existName = isKeyExist(tbId, "a3", depName, true);
        }
        if (existName) {
            window.parent.cihoAlert(msg.sz.bm.nameQqual, msgBox.dlgBtn.Ok, function () { $("#depName", "#" + dlgId).focus(); });
            return false;
        }

        if (depID) {
            if (data.state == 1 || data.state == 2) {                                 //state ：1 新增根节点        state：2 新增下一级
                existID = isKeyExist(tbId, "a1", depID, false);
            } else if (data.state == 3) {
                existID = isKeyExist(tbId, "a1", depID, true);
            }
        }

        if (existID) {//"部门编号重复，是否保存？"
            window.parent.cihoAlert(msg.sz.bm.idQqual, msgBox.dlgBtn.YesNo, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    saveBMXX(data, tbId, dlgId, strType);
                    return;
                }
                if (msgBox.dlgRst.No == strRet) {
                    $("#depID", "#" + dlgId).focus();
                }
            });
            return false;
        }
        saveBMXX(data, tbId, dlgId, strType);
    } catch (e) { }
}

function saveBMXX(data, tbId, dlgId, strType) {
    var s = null;
    if (data.state == 1) {                           //新增根节点
        var strJson = '{"parent":"0","level":"0","a1":"' + trim($("#depID").val()) + '","a3":"' + trim($("#depName").val()) + '","bh":"' + data.bh + '"}';
        s = saveData(tbId, strJson, 1);
    } else if (data.state == 2) {                //新增
        var item = $("#" + tbId).getRowData(data.rowId);
        var strJson = '{"parent":"' + item.bh + '","level":"' + (item.level * 1 + 1) + '","a1":"' + trim($("#depID").val()) + '","a3":"' + trim($("#depName").val()) + '","bh":"' + data.bh + '"}';
        s = saveData(tbId, strJson, 1);
    } else if (data.state == 3) {                //修改
        var item = $("#" + tbId).getRowData(data.rowId);
        var strJson = '{"bmdm":"' + item.bmdm + '","a1":"' + trim($("#depID").val()) + '","a3":"' + trim($("#depName").val()) + '","bh":"' + data.bh + '"}';
        s = saveData(tbId, strJson, 2);
    }

    if (s.ReturnCode == 0) {
        window.top.arrJbzl[3] = true;
        var addItem = ParseData(strJson);
        addItem.bmdm = s.bmdm;
        addItem.bh = data.bh;
        if (data.state == 1) {             //添加根节点
            $("#" + tbId).addChildNode(addItem.bh, null, addItem);
            resizeGridScroll(strTableP0604);
        }
        else if (data.state == 2) {                            //添加叶子节点
            $("#" + tbId).addChildNode(addItem.bh, addItem.parent, addItem);
            resizeGridScroll(strTableP0604);
        } else {
            $("#" + tbId).setTreeRow(data.rowId, addItem);
        }

        if (strType == 1) {
            cihoDlgClose(dlgId);
        } else {
            $(":input[name]", "#" + dlgId).val("");
            switch (data.state) {
                case 1:                     //新增根节点
                    var bh = ParseData(window.external.DoOptions('Tbmxx', 'MakeBH', '{"ParentBH":"0"}'));
                    data.bh = bh.BH;
                    data.a1 = bh.a1;
                    data.state = 1;
                    data.rowId = undefined;
                    break;
                case 2:                     //新增叶子节点
                case 3:                     //修改
                    var item = $("#" + tbId).getRowData(data.rowId);
                    var bh = ParseData(window.external.DoOptions('Tbmxx', 'MakeBH', '{"ParentBH":"' + item.bh + '"}'));
                    data.bh = bh.BH;
                    data.a1 = bh.a1;
                    data.state = 2;
                    break;
            }
            $("#depID").val(data.a1);
            $("#depName").focus();
            $("#" + dlgId).data("change", false).data("data", data);
        }
    }
    data = s = null;
}





//执行删除
function delSelItem() {
    try {
        window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
            if (msgBox.dlgRst.Yes == strRet) {
                var delStr = "{\"bmdm\":\"" + selItem.bmdm + "\"}";
                if (selItem) {
                    //删除后台信息
                    var l = $("#" + strTableP0604).getNodeChildren(selItem).length;
                    if (l > 0) {
                        window.parent.cihoAlert(msg.del.haveChild, msgBox.dlgBtn.Ok);
                    }
                    else {
                        var strRet = ParseData(window.external.DoOptions(strTableP0604, 'Delete', delStr));
                        if ("0" == strRet.ReturnCode) {
                            window.top.arrJbzl[3] = true;
                            var parentNode = $("#" + strTableP0604).getNodeParent(selItem);
                            $("#" + strTableP0604).delTreeNode(selItem.bh);
                            if (parentNode) {
                                var siblings = $("#" + strTableP0604).getNodeChildren(parentNode).length;
                                if (siblings == 0) {
                                    reloadData(strTableP0604);
                                }
                            }
                            resizeGridScroll(strTableP0604);
                        }
                        else {
                            window.parent.cihoAlert(strRet.MSG, msgBox.dlgBtn.Ok);
                        }
                    }
                }
                else {
                    window.parent.cihoAlert(msg.del.selDelRow, msgBox.dlgBtn.Ok);
                }
            }
        });
    } catch (e) { }
}
