//打开费用支出窗口
function openZc(djbh) {
    try {
        var tbId = strTableP050101, dlgId = strDivP050101;
        var $tbId = $("#" + tbId), $dlgId = $("#" + dlgId);
        var state = djbh ? 2 : 1;

        $dlgId.data("state", state);                                          //保存窗口状态信息
        $dlgId.unbind("keydown keypress").bind("keydown keypress", function () { if (event.keyCode == 13) { return false; } });
        creatDiv_ShowDlgHaveTbl(dlgId, "费用支出单", false, true, tbId, 700);  //创建弹出窗口
        createElements(tbId, dlgId);                                          //创建表单元素
        initGridSetP050101(tbId, dlgId);                                      //为grid绑定事件
        initInputsProp(tbId, dlgId);                                          //创建表单元素
        $("#bz", $dlgId).focus();                                               //初始进来时给备注上加上焦点

        var mylist = [];
        if (state == 1) {                                                     //新增页头页脚默认值
            $dlgId.data("data", {});
            $("#djdate", $dlgId).val(getNowDate());
            $("#czymc", $dlgId).attr("disabled", true).val(window.parent.objLoginInfo.name);
        } else {                                                              //修改，页头页脚初始值
            //去后台请求修改信息
            var data = ParseData(window.external.DoOptions(tbId, "GetList", '{ "djbh": "' + djbh + '" }'));
            if (data && data.ReturnCode == 0) {
                //为单据编号和单据时间赋值
                $("#idMust", $dlgId).append('NO:<span id="djbh">' + djbh + '</span>');
                $("#djdate", $dlgId).attr("disabled", true).val(data.djdate);

                //为账户combotree赋值
                var $zhmc = $("#zhmc", $dlgId);
                $zhmc.cihoComboTree("setValue", data.zhdm);
                $zhmc.cihoComboTree("setText", data.zhmc);

                //为制单人、备注赋值
                $("#czymc", $dlgId).val(data.czymc);
                $("#bz", $dlgId).val(escape(data.bz));
                if (data.Records instanceof Array) { mylist = data.Records };
                $dlgId.data("data", { djbh: djbh, zhdm: data.zhdm, zhmc: data.zhmc, czydm: data.czydm, czymc: data.czymc }); //将修改信息存放在dialog里面
                $zhmc = null;
            } else {
                window.parent.cihoAlert(data.MSG, msgBox.dlgBtn.Ok);
            }
        }
        //为jqgrid加载数据
        loadGridData(tbId, mylist);
        $dlgId.data("change", false);
        setTimeout('$("#bz", "#"+strDivP050101).focus();', 100);
        $(".layoutpanel").css("z-index", "50000009");

        $dlgId = $tbId = null;
    } catch (e) { }
}

//为grid定义事件
function initGridSetP050101(tbId, dlgId) {
    $("#" + tbId).setGridParam({
        "afterSaveCell": function (rowId, cellname, value) {      //保存后要执行的事件（计算和）
            try {
                switch (cellname) {
                    case "je":                                    //计算合计并添加分配按钮
                        if (value * 1) {
                            sumGridTotal(this.id);
                            addFpButton(rowId);
                        }
                        break;
                    case "kmmc":
                        addFpButton(rowId);                      //添加分配按钮 
                        break;
                }
            } catch (e) { }
        },
        "afterEditCell": function (rowId, cellname, value, iRow, iCol) {
            try {
                cellX = iRow; cellY = iCol;
                var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
                switch (cellname) {
                    case "kmmc":
                        //为科目名称绑定combotree
                        item.cihoComboTree({ width: 120, showBox: false, mode: "child", showMode: "all" });

                        //请求并加载combotree数据
                        var record = ParseData(window.external.DoOptions(strTableP0501, "GetTreeList", '{"flag":"1","zt":"true"}'));
                        if (record && record.Records instanceof Array) {
                            item.cihoComboTree('loadData', record.Records);
                        }

                        //为combotree定义事件
                        item.cihoComboTree({
                            onSelect: function (item) {
                                $("#" + tbId).setCell(rowId, "kmdm", item.dm);
                                changeZt(tbId, rowId);
                            }
                        });

                        //为combotree赋值
                        item.cihoComboTree("setValue", $(this).getCell(rowId, "kmdm"));
                        item.cihoComboTree('setText', value);
                        item.cihoComboTree('focus');
                        break;
                    case "zymc":
                        //为职员绑定combobox
                        item.combobox({ valueField: "dm", textField: "mc", width: _iWidth120 });

                        //加载combobox数据
                        var zylist = getComboboxData("TZyxx");
                        zylist.push({ "mc": "<font color='red'>添加职员</font>", "dm": "-1" });
                        item.combobox("loadData", zylist);

                        //为combobox设置值
                        var zydm = $(this).getCell(rowId, "zydm");
                        item.combobox("setValue", zydm);
                        if (item.combobox("getText") == zydm) {
                            item.combobox("setText", value);
                        }

                        item.combobox('focus');

                        //为combobox定义事件
                        item.combobox({
                            onChange: function (newValue, oldValue) {
                                if (newValue) {
                                    $("#" + tbId).setCell(rowId, "zydm", newValue);
                                } else {
                                    $("#" + tbId).setCell(rowId, "zydm", null);
                                }
                                changeZt(tbId, rowId);
                            },
                            onSelect: function (item) {
                                if (item.dm == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "职员", table: "Tflxx" }, { model: "TZyxx", jquery: $(this) });
                                    $(this).combobox("setValue", "");
                                }
                            },
                            afterChange: function (newValue, newText) {
                                if (newValue == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "职员", table: "Tflxx" }, { model: "TZyxx", jquery: $(this) });
                                    ciho.showTypeDialog();
                                    $(this).combobox("setValue", "");
                                }
                            }
                        });
                        break;
                    case "je":
                        //为金额文本框赋值
                        item.val(value);

                        //为金额文本框定义事件
                        item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                        item.change(function () { changeZt(tbId, rowId); });
                        break;
                }
                $(".layoutpanel").css("z-index", "50000009");
            } catch (e) { }
        }
    });

    //格式化grid
    addColFormater(tbId);

    //在grid上绑定一个数组，用来存储删除数据
    $("#" + tbId).data("records", []);

    //为grid绑定删除事件
    bindDelEvent(tbId);
    $("#" + tbId).setGridHeight(141);
}

//添加分配按钮
function addFpButton(rowId) {
    var $tbId = $("#" + strTableP050101);
    var kmdm = $tbId.getCell(rowId, "kmdm");
    var je = $tbId.getCell(rowId, "je") * 1;
    var fyfp = $tbId.getCell(rowId, "fyfp");             //费用分配列没有任何图标
    if (!$.trim(fyfp) && je && kmdm) {                   //没有已分配信息，并且科目和金额已经填好，则未费用分配列添加费用分配图标
        $tbId.setCell(rowId, "fyfp", "<div class = 'name'><div class='wfp'><div class='add'><a href=\"#\" title=\"分配费用\" onclick=\"openFYFP(" + rowId + ");return false; \"></a></div></div></div>");
    }
    $tbId = null;
}

//验证费用支出单
function authMyBillsTp050101(tbId, dlgId) {
    var data = $("#" + dlgId).data("data");
    var $dlgId = $("#" + dlgId), $tbId = $("#" + tbId);
    $tbId.saveCell(cellX, cellY);

    var je = $tbId.footerData("get").je * 1;
    var maxAmount = window.top._MaxPerBill;
    if (je > maxAmount) {//"单据金额过大！"
        window.parent.cihoAlert(msg.other.djhjExtent, msgBox.dlgBtn.Ok);        //alert("单据金额过大！");
        return false;
    }

    //验证时间
    var djdata = $("#djdate", $dlgId).val();
    if (!djdata) {//"支出日期为空或者不存在！"
        window.parent.cihoAlert(msg.dt.inputOutDt, msgBox.dlgBtn.Ok, function () { $("#djdate", "#" + dlgId).select(); });
        $dlgId = $tbId = null;
        return false;
    } else {
        var djdt = djdata.replace(/-/g, "/");
        if (djdt < window.top._startDate) {
            window.parent.cihoAlert(msg.other.zcrqExtent, msgBox.dlgBtn.Ok, function () { $("#djdate", "#" + dlgId).select(); });
            $dlgId = $tbId = null;
            return false;
        }
    }

    //验证付款账户
    var $zh = $("#zhmc", $dlgId);
    var zhdm = $zh.cihoComboTree("getValue");
    var zhmc = $zh.cihoComboTree("getText");

    if (!zhdm && zhmc != data.zhmc) {//"付款账户为空或者不存在！"
        window.parent.cihoAlert(msg.other.inputFkzh, msgBox.dlgBtn.Ok, function () { $("#zhmc", $dlgId).focus(); });
        $dlgId = $tbId = $zh = null;
        return false;
    }


    var vCols = $tbId.data("vCols");
    var ids = $tbId.getDataIDs();
    for (var i = 0, len = ids.length; i < len; i++) {
        var item = $tbId.getRowData(ids[i]);
        if (item.flag && !isRowEmpty(item, vCols)) {             //只有有修改标示并且非空，才去验证
            if (!item.kmdm) {// "】行的支出科目为空或不存在！"
                window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.kjkm.trZckmNotExit, msgBox.dlgBtn.Ok);
                $dlgId = $tbId = $zh = null;
                //alert("请选择第【" + (i + 1) + "】行的药品！");
                return false;
            }
            if (item.je * 1 <= 0) {//"】行的金额为空！"
                window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.cw.trjeNotEmp, msgBox.dlgBtn.Ok);
                $dlgId = $tbId = $zh = null;
                //alert("请输入第【" + (i + 1) + "】行的药品数量！");
                return false;
            }
            if (item.fpje * 1 > item.je * 1) {//"】行的已分配金额大于支出金额！"
                window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.cw.trfpjeMorezcje, msgBox.dlgBtn.Ok);
                $dlgId = $tbId = $zh = null;
                //alert("请选择第【" + (i + 1) + "】行的药品！");
                return false;
            }
        }
    }
    $dlgId = $tbId = $zh = null;
    return true;
}


//保存费用支出单
function saveTableP050101(dlgId, afterSave, tbId) {

    if (!authMyBillsTp050101(tbId, dlgId)) { return false; }        //验证单据信息

    var $tbId = $("#" + tbId), $dlgId = $("#" + dlgId);

    var recordCount = 0;                        //数据条数

    var records = $tbId.data("records");        //保存到grid中的删除信息

    var state = $dlgId.data("state");           //对话框的修改状态

    var data = $dlgId.data("data");             //修改时传到对话框的修改信息

    var ids = $tbId.getDataIDs();

    var rows = [];

    var vCols = $tbId.data("vCols");            //可见列名
    for (var i = 0; i < ids.length; i++) {
        var item = $tbId.getRowData(ids[i]);
        if (item.flag) {                        //只有标示列才去保存
            var rowEmpty = isRowEmpty(item, vCols);
            if (!rowEmpty) {                    //非空行，保存该行数据
                recordCount++;
                var scxx = "";
                if ($.trim(item.scxx).length > 0) {
                    scxx = "," + item.scxx;
                }
                var record = '{"mxguid":"' + item.mxguid + '","kmdm":"' + item.kmdm + '","je":"' + item.je + '","zydm":"' + item.zydm + '","flag":"' + item.flag + '","Records":[' + item.fpxx + scxx + ']}';
                rows.push(record);
            } else if (item.mxguid) {           //空行并且有mxguid的，发送到后台删除
                rows.push('{"mxguid":"' + item.mxguid + '","flag":"3"}');
            }
        }
    }

    if (recordCount == 0) {//"费用支出单不能为空！"
        window.parent.cihoAlert(msg.cw.fyzcdNotEmp, msgBox.dlgBtn.Ok);
        return false;
    }

    //组织页头和页脚的数组
    var inputs = [];

    //日期
    inputs.push('"djdate":"' + $("#djdate", $dlgId).val() + '"');

    //付款账户
    var $km = $("#zhmc", $dlgId);
    var kmdm = $km.cihoComboTree("getValue");
    var kmmc = $km.cihoComboTree("getText");
    if (kmmc == data.zhmc) {
        inputs.push('"zhdm":"' + data.zhdm + '"');
    } else if (kmdm) {
        inputs.push('"zhdm":"' + kmdm + '"');
    }

    //制单人
    if (state == 1) {                                                        //新增时，制单人取当前操作员
        inputs.push('"czydm":"' + window.parent.objLoginInfo.code + '"');
    } else if (state == 2) {
        inputs.push('"czydm":"' + data.czydm + '"');                        //修改时，制单人取保存到grid里的操作员
        inputs.push('"djbh":"' + data.djbh + '"');                          //修改时，保存到grid里的单据编号
    }

    //备注
    inputs.push('"bz":"' + trim($("#bz", $dlgId).val()) + '"');

    var jsonStr = '{' + inputs + ',"Records":[' + rows.concat(records) + ']}';

    var s = null;
    if (state == 1) {
        s = ParseData(window.external.DoOptions(tbId, "Add", jsonStr));
    } else {
        s = ParseData(window.external.DoOptions(tbId, "Edit", jsonStr));
    }

    if (s && s.ReturnCode == 0) {                   //添加成功！
        if (afterSave == 2) {                       //保存新增
            resetGrid(tbId, dlgId);
            $("#bz", "#" + dlgId).focus();            //给备注设上焦点
        } else {                                    //保存退出
            cihoDlgClose(dlgId);
        }
        searchDataClick_P0501(0);
        resizeGrid(strTableP0501);
    } else {
        window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
    }
}