/*--------------------------文档信息-------------------------------------------
///
///功能：    流向管理-流向单
///创建人：  王思波
///创建时间：2011年06月11日
///修改人：  --------------
///修改时间：--------------
///修改原因：--------------
///详细说明：--------------
///
-----------------------------------------------------------------------------*/

//页面全局变量
var strTableP020501 = "Tp020501";       //表格ID
var strDialogP020501 = "divP020501";    //流向单窗口ID
var strOldInfo_P020501 = "";            //影响预提费用的数据
var intRowCountP020501 = 8;             //表格的默认行数
var intMaxRowIDP020501 = 0;             //新数据行的编号
var intStockCountP020501 = 0;           //剩余库存
var arrRecordsP020501 = [];             //记录表格中需要操作数据
var objConfigP020501 = {};              //窗口元素的配置信息
var objCellPlace = { iRow: 0, iCol: 0, rowid: "", value: "" }; //记录当前编辑状态的单元格


/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓**事件方法 开始**↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/

//弹出流向单窗口
function showDialog_P020501(strSaveFlag) {
    //弹出编辑窗口
    creatDiv_ShowDlgHaveTbl(strDialogP020501, "流向单", false, true, strTableP020501, 900);
    $("#" + strDialogP020501 + "_content").css("margin-top", "-70px")
    //$("#" + strDialogP020501 + "_pop_box_top").append("<a>导入</a>");

    //设置保存标志
    $("#" + strDialogP020501 + "_divform").data("saveFlag", strSaveFlag);

    //窗口元素的取得
    getPageConfig_P020501();

    //窗口元素的添加
    creatDialogItem_P020501();

    //窗口数据的取得
    getPageData_P020501();
}

//添加行
function addBlankRow_P020501() {
    $("#" + strTableP020501).addRowData("blank_" + intMaxRowIDP020501, {}); //添加空白行
    addMouseMove_P020501("blank_" + intMaxRowIDP020501);                    //添加空白行的操作按钮
    intMaxRowIDP020501++;                                                   //记录最大行ID 

    //调整表格滚动条
    resizeGridScroll(strTableP020501);
}

//删除数据
function deleteData_P020501(rowid) {
    try {
        var objSurplusStock = {};
        var strCount = "";

        //保存单元格的内容
        $("#" + strTableP020501).saveCell(objCellPlace.iRow, objCellPlace.iCol);

        //当GUID不为空时，弹出提示信息
        if (checkRowNull(rowid) == false) {
            //提示用户是否删除数据
            window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (result) {
                if (result == msgBox.dlgRst.Yes) {
                    //记录删除的数据行
                    if ($("#" + strTableP020501).getCell(rowid, "mxguid") != "") {
                        arrRecordsP020501.push("{\"mxguid\":\"" + $("#" + strTableP020501).getCell(rowid, "mxguid") + "\",\"flag\":\"3\"}");
                    }

                    //修改剩余库存
                    objSurplusStock = $("#labSurplusStock", "#" + strDialogP020501);
                    strCount = $("#" + strTableP020501).getRowData(rowid).a1;
                    if (objSurplusStock.text() != "" && strCount != "") {
                        objSurplusStock.text((parseFloat(objSurplusStock.text()) + parseFloat(strCount)).toFixed(window.parent.strCountPlace));
                    }

                    //删除行
                    $("#" + strTableP020501).delRowData(rowid);

                    //计算合计
                    totalCompute_P020501();

                    //设置修改标志
                    $("#" + strDialogP020501 + "_divform").data("change", true);
                }
            });
        }
        else {
            //记录删除的数据行
            if ($("#" + strTableP020501).getCell(rowid, "mxguid") != "") {
                arrRecordsP020501.push("{\"mxguid\":\"" + $("#" + strTableP020501).getCell(rowid, "mxguid") + "\",\"flag\":\"3\"}");
            }

            $("#" + strTableP020501).delRowData(rowid); //删除行
        }

        //调整表格滚动条
        resizeGridScroll(strTableP020501);

        //释放内存
        objSurplusStock = null;
        strCount = null;
    }
    catch (e) { }
}

//保存数据
function saveData_P020501(strFuncType) {
    var isValidateText = validateText_P020501(); //窗口信息的验证
    var objResult = {};
    var strDataJson = "";
    var strItemInfo = "";

    //验证通过后，执行以下代码
    if (isValidateText) {
        //保存信息的取得
        strDataJson = getDataJson_P020501();
        //保存数据
        objResult = saveData(strTableP020501, strDataJson, $("#" + strDialogP020501 + "_divform").data("saveFlag"));

        //保存成功后的处理
        if (objResult.ReturnCode == 0) {
            //修改预提单
            if ($("#" + strDialogP020501 + "_divform").data("saveFlag") == "2") {
                strItemInfo = getCompareData(strTableP020501, new Array("psdate", "dm", "a1", "a2", "zydm"));
                strItemInfo += $("#spdm", "#" + strDialogP020501).combobox("getValue") + $("#khdm", "#" + strDialogP020501).combobox("getValue");
                if (strItemInfo != strOldInfo_P020501) {
                    ParseData(window.external.DoOptions(strTableP020501, "DoOthers", "{djbh:\"" + objSelRowP0205.djbh + "\"}"));
                }
            }

            //释放内存
            freeMemory_P020501();

            //加载主页面的列表数据
            loadGridData_P0205();

            //保存增加的处理
            if (strFuncType == "2") {
                $("#" + strDialogP020501 + "_divform").data("saveFlag", "1")        //保存类型
                $("#idMust", "#" + strDialogP020501).empty();                       //单据编号
                $("#djdate", "#" + strDialogP020501).val(formatDate(new Date()));   //单据日期
                $("#djdate", "#" + strDialogP020501).attr("disabled", false);       //单据日期
                $("#spdm", "#" + strDialogP020501).combobox("setValue", "");        //药品
                $("#khdm", "#" + strDialogP020501).combobox("setValue", "");        //客户
                $("#labSurplusStock", "#" + strDialogP020501).text(parseFloat("0").toFixed(window.parent.strCountPlace));   //剩余库存
                $("#labBillInitial", "#" + strDialogP020501).text(parseFloat("0").toFixed(window.parent.strCountPlace));    //建帐期初
                $("#czydm", "#" + strDialogP020501).val(window.parent.objLoginInfo.name);   //制单人
                $("#bz", "#" + strDialogP020501).val("");                                   //备注
                loadGridData_P020501([]);                                                   //清空表格
                $("#" + strDialogP020501 + "_divform").data("change", false);               //内容变更标志的更新
            }
            else {
                cihoDlgClose(strDialogP020501); //关闭窗口
            }
        }
        else {
            window.parent.cihoAlert(objResult.MSG); //保存失败时的提示信息
        }
    }

    //释放内存
    isValidateText = null;
    objResult = null;
    strDataJson = null;
}

//单元格编辑状态前的事件
function beforeEditCell_P020501(rowid, cellname, value, iRow, iCol) {
    //记录单元的索引
    objCellPlace.iRow = iRow;
    objCellPlace.iCol = iCol;
    //记录数据行ID
    objCellPlace.rowid = rowid;
    //记录单元格旧的内容
    if (cellname == "a1" || cellname == "a2") {
        objCellPlace.value = !value ? 0 : parseFloat(value);
    }
    else {
        objCellPlace.value = value;
    }
}

//单元格编辑事件
function afterEditCell_P020501(rowid, cellname, value, iRow, iCol) {
    var objCellItem = $("#" + rowid + " :input[name='" + cellname + "']", this); //单元格对象
    var objClient = [];     //客户
    var objEmployee = [];   //销售员
    var objResult = {};     //数据获取结果
    var strMedicinal = "";

    //创建当前单元格的控件
    switch (cellname) {
        case "psdate": //配送日期
            inputAndBindData(":input[name='psdate']", false, "#" + strTableP020501, null);
            break;
        case "kh": //客户
            objCellItem.combobox({ width: 95, listWidth: 95, textField: "mc", valueField: "dm" });
            //加载数据
            objClient = getComboboxData("Tkhxx1");
            objClient.push({ "mc": "添加客户", "dm": "-1" });
            objCellItem.combobox("loadData", objClient);
            objCellItem.combo_ciho("layoutpanel").find("div.combobox-item[value='-1']").css("color", "red");
            //默认值的设定
            objCellItem.combobox("setValue", $(this).getCell(rowid, "dm"));
            objCellItem.combobox("setText", objCellPlace.value);
            //获取焦点
            objCellItem.combobox("focus");
            //添加事件
            objCellItem.combobox({
                afterChange: function (newValue, newText) {
                    if (newValue == "-1") {
                        ciho.IniData({ id: "divP020503", title: "客户", table: "" }, { jquery: $(this), model: "Tkhxx" }); //添加功能
                        ciho.showTypeDialog();
                    }
                    else if (newValue) {
                        //药品、客户选择后，带出单价
                        strMedicinal = $("#spdm", "#" + strDialogP020501).combobox("getValue");
                        if (strMedicinal && newValue) {
                            objResult = ParseData(window.external.DoOptions(strTableP020501, "DoOthers", "{spdm:\"" + strMedicinal + "\",khdm:\"" + newValue + "\",flag:1}"))
                            if (objResult && objResult.Records.length > 0) {
                                $("#" + strTableP020501).setCell(rowid, "a2", parseFloat(objResult.Records[0].a1).toFixed(window.parent.strPricePlace));
                            }
                        }
                        //保存代码
                        $(this).combobox("setText", newText.replace(/&nbsp;/g, ""));    //去除空格
                        $("#" + strTableP020501).setCell(rowid, "dm", newValue);        //代码的设置
                    }
                    else {
                        $("#" + strTableP020501).setCell(rowid, "dm", "&nbsp;");        //代码的设置
                    }
                }
            });
            break;
        case "lxmc": //销售类型
            //属性的设置
            objCellItem.combobox({ width: 95, listWidth: 95, textField: "mc", valueField: "dm", editable: false });
            //加载数据
            objCellItem.combobox("loadData", [{ mc: "终端", dm: "0" }, { mc: "配送", dm: "1"}]);
            //默认值的设定
            objCellItem.combobox("setValue", $("#" + strTableP020501).getCell(rowid, "lxdm"));
            //获取焦点
            objCellItem.combobox("focus");
            //添加事件
            objCellItem.combobox({
                onSelect: function (option) {
                    if (!option.dm) {
                        $("#" + strTableP020501).setCell(rowid, "lxdm", null);
                    }
                    else {
                        $("#" + strTableP020501).setCell(rowid, "lxdm", option.dm);
                    }
                }
            });
            break;
        case "zymc": //销售员
            //属性的设置
            objCellItem.combobox({ width: 95, listWidth: 95, textField: "mc", valueField: "dm" });
            //加载数据
            objEmployee = getComboboxData("TZyxx");
            objEmployee.push({ "mc": "添加销售员", "dm": "-1" });
            objCellItem.combobox("loadData", objEmployee);
            objCellItem.combo_ciho("layoutpanel").find("div.combobox-item[value='-1']").css("color", "red");
            //默认值的设定
            objCellItem.combobox("setValue", $("#" + strTableP020501).getCell(rowid, "zydm"));
            objCellItem.combobox("setText", objCellPlace.value);
            //获取焦点
            objCellItem.combobox("focus");
            //添加事件
            objCellItem.combobox({
                afterChange: function (newValue, newText) {
                    if (newValue == "-1") {
                        ciho.IniData({ id: "divP020503", title: "销售员", table: "" }, { jquery: $(this), model: "TZyxx" }); //添加功能
                        ciho.showTypeDialog();
                    }
                    else if (newValue) {
                        $("#" + strTableP020501).setCell(rowid, "zydm", newValue);
                    }
                    else {
                        $("#" + strTableP020501).setCell(rowid, "zydm", "&nbsp;");
                    }
                }
            });
            break;
        case "a1": //数量
            objCellItem.css("text-align", "right");
            objCellItem.autoNumeric({ mDec: window.parent.strCountPlace, aSep: "", aNeg: "-" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
        case "a2": //单价
            objCellItem.css("text-align", "right");
            objCellItem.autoNumeric({ mDec: window.parent.strPricePlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
    }

    //释放内存
    objCellItem = null;  //单元格对象
    objClient = null;    //客户
    objEmployee = null;  //销售员
    objResult = null;    //数据获取结果
    strMedicinal = null; //药品代码
}

//单元格保存事件
function afterSaveCell_P020501(rowid, cellname, value, iRow, iCol) {
    var intCount = !$(this).getCell(rowid, "a1") ? 0 : parseFloat($(this).getCell(rowid, "a1")); //数量
    var intPrice = !$(this).getCell(rowid, "a2") ? 0 : parseFloat($(this).getCell(rowid, "a2")); //单价
    var objSurplusStock = $("#labSurplusStock", "#" + strDialogP020501); //剩余库存对象
    var intNowStockCount = 0; //当前剩余库存
    var intNewStockCount = 0; //新的剩余库存

    //设置表格中数据行的保存类型
    if (!$(this).getCell(rowid, "mxguid")) {
        $(this).setCell(rowid, "flag", "1");
    }

    //窗口信息变量标志
    $("#" + strDialogP020501 + "_divform").data("change", true);

    //数量、单价输入后，自动计算出金额
    if ($(this).getCell(rowid, "a1") != "" && $(this).getCell(rowid, "a2") != "") {
        $(this).setCell(rowid, "je", parseFloat(intCount * intPrice).toFixed(window.parent.strMoneyPlace));
    }
    else {
        $(this).setCell(rowid, "je", null);
    }

    //更新剩余库存
    if (cellname == "a1") {
        if (objSurplusStock.text() != "") {
            intNowStockCount = objSurplusStock.text() == "" ? 0 : parseFloat(objSurplusStock.text()); //当前剩余
            intNewStockCount = intNowStockCount + objCellPlace.value - intCount;
            objSurplusStock.text(intNewStockCount.toFixed(window.parent.strCountPlace));
        }
    }

    //计算合计
    totalCompute_P020501();

    //释放内存
    intCount = null;
    intPrice = null;
    objSurplusStock = null;
    intNowStockCount = null;
    intNewStockCount = null;
}

/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑**事件方法 结束**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/


/*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓**自定义方法 开始**↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/

//添加表单元素到窗口中
function creatDialogItem_P020501() {
    var objPageHeader = objConfigP020501.pageHeader; //页头元素
    var objPageFooter = objConfigP020501.pageFooter; //页尾元素
    var strHideItemHtml = "";   //隐藏控件 
    var strItemHtml = "";       //显示控件 
    var strLockDate = "";       //锁定控件

    //修改时锁定日期项
    if ($("#" + strDialogP020501 + "_divform").data("saveFlag") == "2") {
        strLockDate = "disabled=\"disabled\"";
    }

    //页面元素的组建
    strItemHtml = "<ul>"; //页头元素
    for (var intI = 0; intI < objPageHeader.length; intI++) {
        if (objPageHeader[intI].hidden == false) {
            if (objPageHeader[intI].edittype == "text") {
                strItemHtml += "<li class=\"inp_70\">";
                strItemHtml += objPageHeader[intI].xsmc + "：<input id=\"" + objPageHeader[intI].name + "\" name=\"" + objPageHeader[intI].name + "\" type=\"text\" " + strLockDate + "/>";
                strItemHtml += "</li>";
            }
            else if (objPageHeader[intI].edittype == "select") {
                strItemHtml += "<li>";
                strItemHtml += objPageHeader[intI].xsmc + "：<select id=\"" + objPageHeader[intI].name + "\" name=\"" + objPageHeader[intI].name + "\" class=\"easyui-combobox\"></select>";
                strItemHtml += "</li>";
            }
        }
    }
    strItemHtml += "    <li style=\"padding-top:11px;\">";
    strItemHtml += "        剩余库存：<label id=\"labSurplusStock\"></label>";
    strItemHtml += "    </li>";
    strItemHtml += "    <li style=\"padding-top:11px;\">";
    strItemHtml += "        建帐期初：<label id=\"labBillInitial\"></label>";
    strItemHtml += "    </li>";
    strItemHtml += "    <li class=\"fil_btn\">";
    strItemHtml += "        <a href=\"#\" onclick=\"showDialog_P020502(2)\">修改</a>";
    strItemHtml += "    </li>";
    strItemHtml += "</ul>";
    strItemHtml += "<table id=\"" + strTableP020501 + "\"></table><br><br>"; //表格元素
    strItemHtml += "<ul>"; //页尾元素
    for (var intJ = 0; intJ < objPageFooter.length; intJ++) {
        if (objPageFooter[intJ].name == "bz") {
            strItemHtml += "<li class=\"bz\">";
            strItemHtml += objPageFooter[intJ].xsmc + "：<input id=\"" + objPageFooter[intJ].name + "\" name=\"" + objPageFooter[intJ].name + "\" type=\"text\" onkeypress=\"return checkValidate(event)\" onpaste=\"return validatePaste()\"/>";
            strItemHtml += "</li>";
        }
        else if (objPageFooter[intJ].name == "czymc") {
            strItemHtml += "<li class=\"inp_70\">";
            strItemHtml += objPageFooter[intJ].xsmc + "：<input id=\"" + objPageFooter[intJ].name + "\" name=\"" + objPageFooter[intJ].name + "\" type=\"text\" disabled=\"disabled\" value=\"" + window.parent.objLoginInfo.name + "\" />";
            strItemHtml += "</li>";
        }
        else {
            strHideItemHtml += "<input id=\"" + objPageFooter[intJ].name + "\" name=\"" + objPageFooter[intJ].name + "\" type=\"hidden\" value=\"" + window.parent.objLoginInfo.code + "\"/>";
        }
    }
    strItemHtml += "</ul>";
    strItemHtml += strHideItemHtml;
    $("#" + strDialogP020501 + "_divform").append(strItemHtml);

    //设置初始焦点
    $("#bz", "#" + strDialogP020501).focus();

    //绑定日期控件
    inputAndBindData("djdate", false, "#" + strDialogP020501, function () { $("#" + strDialogP020501 + "_divform").data("change", true); });
    $("#djdate", "#" + strDialogP020501).val(formatDate(new Date()));

    //加载下拉框控件的信息
    loadDrugData_P020501(); //药品
    loadClient_P020501();   //客户
    $(".layoutpanel").css("z-index", "50000009");

    //创建表格
    createGrid_P020501();

    //给控件添加变量事件
    $(":input", $("#" + strDialogP020501 + "_divform")).change(function () {
        $("#" + strDialogP020501 + "_divform").data("change", true);
    });

    //释放内存
    objPageHeader = null;
    objPageFooter = null;
    strHideItemHtml = null;
    strItemHtml = null;
    strLockDate = null;
}

//药品下拉框信息的加载
function loadDrugData_P020501() {
    //设置属性
    $("#spdm", "#" + strDialogP020501).combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        //内容变更前事件
        afterChange: function (newValue, newText) {
            if (newValue == "-1") {
                ciho.IniData({ id: "divP020503", title: "药品", table: "" }, { jquery: $("#spdm", "#" + strDialogP020501), model: "Tspxx" });
                ciho.showTypeDialog();
            }
        },
        //选择事件
        onSelect: function (option) {
            getStockInitial_P020501(option.dm, $("#khdm", "#" + strDialogP020501).combobox("getValue"));
            $("#" + strDialogP020501 + "_divform").data("change", true);
        }
    });

    //加载数据
    var objMedicinal = getComboboxData("Tspxx");
    objMedicinal.push({ "mc": "添加药品", "dm": "-1" });
    $("#spdm", "#" + strDialogP020501).combobox("loadData", objMedicinal);
    $("#spdm", "#" + strDialogP020501).combo_ciho("layoutpanel").find("div.combobox-item[value='-1']").css("color", "red");

    //释放内存
    objMedicinal = null;
}

//客户下拉框信息的加载
function loadClient_P020501() {
    //设置属性
    $("#khdm", "#" + strDialogP020501).combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        //内容变更前事件
        afterChange: function (newValue, newText) {
            //添加功能
            if (newValue == "-1") {
                ciho.IniData({ id: "divP020503", title: "客户", table: "" }, { jquery: $("#khdm", "#" + strDialogP020501), model: "Tkhxx" });
                ciho.showTypeDialog();
            }
            else {
                $("#khdm", "#" + strDialogP020501).combobox("setText", newText.replace(/&nbsp;/g, ""));
            }
        },
        //选择事件
        onSelect: function (option) {
            getStockInitial_P020501($("#spdm", "#" + strDialogP020501).combobox("getValue"), option.dm);
            $("#" + strDialogP020501 + "_divform").data("change", true);
        }
    });

    //加载数据
    var objClient = getComboboxData("Tkhxx1");
    objClient.push({ "mc": "添加客户", "dm": "-1" });
    $("#khdm", "#" + strDialogP020501).combobox("loadData", objClient);
    $("#khdm", "#" + strDialogP020501).combo_ciho("layoutpanel").find("div.combobox-item[value='-1']").css("color", "red");

    //释放内存
    objClient = null;
}

//窗口中元素的取得
function getPageConfig_P020501() {
    //获得jqGrid的列名和属性
    objConfigP020501 = ParseData(window.external.DoOptions(strTableP020501, "GetTableConfig", "{}"));

    //配置信息是否为空
    if (objConfigP020501) {
        for (var intI = 0; intI < objConfigP020501.colModel.length; intI++) {
            //客户、销售类型、销售员
            if (objConfigP020501.colModel[intI].name == "kh" || objConfigP020501.colModel[intI].name == "lxmc" || objConfigP020501.colModel[intI].name == "zymc") {
                objConfigP020501.colModel[intI].edittype = "custom";
                objConfigP020501.colModel[intI].editoptions = {
                    custom_element: function (value, options) { return "<select  id=\"" + options.id + "\" class=\"easyui-combobox\"></select>"; },
                    custom_value: function (e) { return e.combobox("getText"); }
                };
            }
            //数量
            else if (objConfigP020501.colModel[intI].name == "a1") {
                objConfigP020501.colModel[intI].formatter = function (cellvalue, options, rowObject) {
                    if (cellvalue != undefined && cellvalue != "") {
                        return parseFloat(cellvalue).toFixed(window.parent.strCountPlace);
                    }
                    else {
                        return "&nbsp;";
                    }
                };
            }
            //单价
            else if (objConfigP020501.colModel[intI].name == "a2") {
                objConfigP020501.colModel[intI].formatter = function (cellvalue, options, rowObject) {
                    if (cellvalue != undefined && cellvalue != "") {
                        return parseFloat(cellvalue).toFixed(window.parent.strPricePlace);
                    }
                    else {
                        return "&nbsp;";
                    }
                };
            }
            //金额
            else if (objConfigP020501.colModel[intI].name == "je") {
                objConfigP020501.colModel[intI].formatter = function (cellvalue, options, rowObject) {
                    if (cellvalue != undefined && cellvalue != "") {
                        return parseFloat(cellvalue).toFixed(window.parent.strMoneyPlace);
                    }
                    else {
                        return "&nbsp;";
                    }
                };
            }
        }
    }
    else {
        objConfigP020501 = { colNames: [], colModel: [] };
    }
}

//窗口中数据的取得
function getPageData_P020501() {
    //当修改时的数据取得
    if ($("#" + strDialogP020501 + "_divform").data("saveFlag") == "2") {
        var objDataListP020501 = ParseData(window.external.DoOptions(strTableP020501, "GetList", "{\"djbh\":\"" + objSelRowP0205.djbh + "\"}"));

        //页头、页尾信息
        $("#idMust", "#" + strDialogP020501).append("NO:" + objSelRowP0205.djbh); //单据编号
        //日期
        $("#djdate", "#" + strDialogP020501).val(objDataListP020501.djdate);
        //药品
        $("#spdm", "#" + strDialogP020501).combobox("setValue", objDataListP020501.spdm);
        $("#spdm", "#" + strDialogP020501).combobox("setText", objDataListP020501.spmc);
        //配送客户
        $("#khdm", "#" + strDialogP020501).combobox("setValue", objDataListP020501.khdm);
        $("#khdm", "#" + strDialogP020501).combobox("setText", objDataListP020501.khmc);
        //制单人
        $("#czydm", "#" + strDialogP020501).val(objDataListP020501.czydm);
        $("#czymc", "#" + strDialogP020501).val(objDataListP020501.czymc);
        //备注
        $("#bz", "#" + strDialogP020501).val(escape(objDataListP020501.bz));

        //加载表格数据
        loadGridData_P020501(objDataListP020501.Records);

        //记录旧的数据
        if ($("#" + strDialogP020501 + "_divform").data("saveFlag") == "2") {
            strOldInfo_P020501 = getCompareData(strTableP020501, new Array("psdate", "dm", "a1", "a2", "zydm"));
            strOldInfo_P020501 += $("#spdm", "#" + strDialogP020501).combobox("getValue") + $("#khdm", "#" + strDialogP020501).combobox("getValue");
        }

        //计算合计
        totalCompute_P020501();

        //剩余库存、建帐期初
        getStockInitial_P020501(objDataListP020501.spdm, objDataListP020501.khdm);

    }
    else {
        loadGridData_P020501([]);
    }
}

//加载表格数据
function loadGridData_P020501(objRecords) {
    var objDataGrid = $("#" + strTableP020501); //表格对象
    var intRowLength = objRecords.length <= intRowCountP020501 ? intRowCountP020501 : objRecords.length; //行数量
    var intCountSum = 0; //数据合计
    var intMoneySum = 0; //金额合计

    //清空旧数据
    $("#" + strTableP020501).clearGridData();

    //添加新数据
    for (var intI = 0; intI < intRowLength; intI++) {
        if (intI < objRecords.length) {
            //加载数据
            objDataGrid.addRowData(intI, objRecords[intI]);

            //计算合计
            intCountSum += objRecords[intI].a1 == "" ? 0 : parseFloat(objRecords[intI].a1);
            intMoneySum += objRecords[intI].je == "" ? 0 : parseFloat(objRecords[intI].je);
        }
        else {
            objDataGrid.addRowData("blank_" + intI.toString(), {});
        }
    }

    //设置合计
    $("#" + strTableP020501).footerData("set", { rn: "合计", a1: intCountSum.toFixed(window.parent.strCountPlace), je: intMoneySum.toFixed(window.parent.strMoneyPlace) }, false);

    //调整表格滚动条
    resizeGridScroll(strTableP020501);

    //数据行ID
    intMaxRowIDP020501 = intI;
}

//剩余库存、建收期初的取得
function getStockInitial_P020501(strDrugID, strClientID) {
    var objResult = {};
    var intSurplusStock = 0; //剩余库存

    //药品、客户都存在时，再执行操作
    if (strDrugID && strClientID) {
        //剩余库存的取得
        objResult = ParseData(window.external.DoOptions(strTableP020501, "DoOthers", "{spdm:\"" + strDrugID + "\",khdm:\"" + strClientID + "\",flag:0}"));

        //设置剩余库存、建帐期初
        if (objResult.sykc != "") {
            //编辑信息时的剩余库存数量=当前剩余+表格的合计数量
            if (strOldInfo_P020501.indexOf(strDrugID) >= 0 && strOldInfo_P020501.indexOf(strClientID) >= 0) {
                intSurplusStock = parseFloat(objResult.sykc); //  - parseFloat($("#" + strTableP020501).footerData("get").a1);
            }
            else {
                intSurplusStock = parseFloat(objResult.sykc) - parseFloat($("#" + strTableP020501).footerData("get").a1);
            }

            //剩余库存
            $("#labSurplusStock", "#" + strDialogP020501).text(intSurplusStock.toFixed(window.parent.strCountPlace));
            //建帐期初
            $("#labBillInitial", "#" + strDialogP020501).text(parseFloat(objResult.jzqc).toFixed(window.parent.strCountPlace));
        }
        else {
            $("#labSurplusStock", "#" + strDialogP020501).text("0");
            $("#labBillInitial", "#" + strDialogP020501).text("0");
        }

    }
    else {
        //设置剩余库存、建帐期初
        $("#labSurplusStock", "#" + strDialogP020501).text("");
        $("#labBillInitial", "#" + strDialogP020501).text("");
    }

    //释放内存
    objResult = null;
    intSurplusStock = null;
}

//保存数据的json字符串的取得
function getDataJson_P020501() {
    var objDataGrid = $("#" + strTableP020501); //表格对象
    var arrDataIDs = objDataGrid.getDataIDs();  //数据行ID
    var strDataJson = "";
    var isEmptyRow = false;

    //列表数据的拼接
    for (var intI = 0; intI < arrDataIDs.length; intI++) {
        //保存类型不为空时，才进行数据保存
        if (objDataGrid.getCell(arrDataIDs[intI], "flag") != "") {
            //验证数据行信息是否全部为空
            isEmptyRow = checkRowNull(arrDataIDs[intI]);
            if (isEmptyRow == false) {
                arrRecordsP020501.push("{mxguid:\"" + objDataGrid.getCell(arrDataIDs[intI], "mxguid") + "\"," + //GUID
                                       "psdate:\"" + objDataGrid.getCell(arrDataIDs[intI], "psdate") + "\"," + //配送日期
                                       "dm:\"" + objDataGrid.getCell(arrDataIDs[intI], "dm") + "\"," +         //客户
                                       "lxdm:\"" + objDataGrid.getCell(arrDataIDs[intI], "lxdm") + "\"," +     //销售类型
                                       "a1:\"" + objDataGrid.getCell(arrDataIDs[intI], "a1") + "\"," +         //数据
                                       "a2:\"" + objDataGrid.getCell(arrDataIDs[intI], "a2") + "\"," +         //单价
                                       "zydm:\"" + objDataGrid.getCell(arrDataIDs[intI], "zydm") + "\"," +     //销售员
                                       "flag:\"" + objDataGrid.getCell(arrDataIDs[intI], "flag") + "\"}");     //保存类型
            }
        }
    }

    //页头、页尾数据的组建
    strDataJson = "{djbh:\"" + ($("#" + strDialogP020501 + "_divform").data("saveFlag") == "1" ? "" : objSelRowP0205.djbh) + "\","; //单据编号
    strDataJson += "djdate:\"" + $("#djdate", "#" + strDialogP020501).val() + "\",";            //日期
    strDataJson += "spdm:\"" + $("#spdm", "#" + strDialogP020501).combobox("getValue") + "\","; //药品
    strDataJson += "khdm:\"" + $("#khdm", "#" + strDialogP020501).combobox("getValue") + "\","; //客户
    strDataJson += "jzqc:\"" + $("#labBillInitial", "#" + strDialogP020501).text() + "\",";     //剩余库存
    strDataJson += "czydm:\"" + $("#czydm", "#" + strDialogP020501).val() + "\",";              //制单人
    strDataJson += "bz:\"" + trim($("#bz", "#" + strDialogP020501).val()) + "\",";              //备注
    strDataJson += "Records:[" + arrRecordsP020501.join(",") + "]}";                            //明细信息

    //释放内存
    objDataGrid = null;
    arrDataIDs = null;

    //返回值
    return strDataJson;
}

//合计的计算
function totalCompute_P020501() {
    var objDataGrid = $("#" + strTableP020501); //表格对象
    var arrDataIDs = objDataGrid.getDataIDs();  //行ID
    var intCountSum = 0; //数据
    var intMoneySum = 0; //金额

    //计算合计数据
    for (var intI = 0; intI < arrDataIDs.length; intI++) {
        intCountSum += objDataGrid.getCell(arrDataIDs[intI], "a1") == "" ? 0 : parseFloat(objDataGrid.getCell(arrDataIDs[intI], "a1"));
        intMoneySum += objDataGrid.getCell(arrDataIDs[intI], "je") == "" ? 0 : parseFloat(objDataGrid.getCell(arrDataIDs[intI], "je"));
    }

    //设置合计数据
    objDataGrid.footerData("set", { rn: "合计", a1: intCountSum.toFixed(window.parent.strCountPlace), je: intMoneySum.toFixed(window.parent.strMoneyPlace) }, false);

    //释放内存
    objDataGrid = null;
    arrDataIDs = null;
    intCountSum = null;
    intMoneySum = null;
}

//添加行的鼠标移动事件
function addMouseMove_P020501() {
    $("#" + strTableP020501).delegate("tr[id]:visible", "hover", function (e) {
        if (e.type == "mouseenter") {
            $("#" + strTableP020501).setCell(this.id, "cz", "<a href=\"#\" style=\"color:red;text-decoration:none;\" onclick=\"deleteData_P020501('" + this.id + "');return false;\">删除</a> ");
        }
        if (e.type == "mouseleave") {
            $("#" + strTableP020501).setCell(this.id, "cz", "&nbsp;");
        }
    });
}

//数据行是否为空的验证
function checkRowNull(rowid) {
    var arrColData = $("#" + rowid + " td:visible");
    var isResult = false;

    //判断指定行可见列的内容是否为空
    for (var intJ = 1; intJ < arrColData.length - 1; intJ++) {
        if (trim((arrColData[intJ].innerText)) != "") {
            isResult = false;
            break;
        }
        else {
            isResult = true;
        }
    }

    //释放内存
    arrColData = null;

    //返回值
    return isResult;
}

//创建表格
function createGrid_P020501() {
    $("#" + strTableP020501).jqGrid({
        datatype: "local",
        sortname: "id",
        colNames: objConfigP020501.colNames,
        colModel: objConfigP020501.colModel,
        data: [],
        rownumbers: true,
        autowidth: true,
        footerrow: true,
        gridview: true,
        cellEdit: true,
        cellsubmit: "clientArray",
        rownumWidth: 30,
        rowNum: 9999999,
        beforeEditCell: beforeEditCell_P020501,
        afterEditCell: afterEditCell_P020501,
        afterSaveCell: afterSaveCell_P020501
    });

    //设置表格高度
    $("#" + strTableP020501).setGridHeight(225);

    //设置序号列名称
    $("#" + strTableP020501).setLabel("rn", "序号");

    //操作列的设置
    $("#" + strTableP020501).setLabel("cz", "<img onclick=\"addBlankRow_P020501()\" style=\"cursor:pointer;padding-top:5px\"  title=\"添加行\" src=\"../../Content/Default/images/edit_add.gif\"/>");

    //添加行的鼠标移动事件
    addMouseMove_P020501();
}

//数据的验证
function validateText_P020501() {
    var objDataGrid = {};
    var arrDataIDs = [];
    var arrColData = {};
    var isEmptyRow = false;
    var intDataCount = 0;
    var strChittyDate = "";

    //保存单元格内容
    $("#" + strTableP020501).saveCell(objCellPlace.iRow, objCellPlace.iCol);

    //日期
    strChittyDate = $("#djdate", "#" + strDialogP020501).val();

    //日期不能为空
    if (strChittyDate == "") {
        window.parent.cihoAlert(msg.cx.lxglRq, msgBox.dlgBtn.Ok, function () { $("#djdate", "#" + strDialogP020501).focus(); });
        return false;
    }
    //药品不能为空
    else if ($("#spdm", "#" + strDialogP020501).combobox("getText") == "") {
        window.parent.cihoAlert(msg.cx.lxglYp, msgBox.dlgBtn.Ok, function () { $("#spdm", "#" + strDialogP020501).combobox("focus"); });
        return false;
    }
    //药品不存在
    else if ($("#spdm", "#" + strDialogP020501).combobox("getValue") == undefined) {
        window.parent.cihoAlert(msg.cx.lxglYpNot, msgBox.dlgBtn.Ok, function () { $("#spdm", "#" + strDialogP020501).combobox("focus"); });
        return false;
    }
    //客户不能为空
    else if ($("#khdm", "#" + strDialogP020501).combobox("getText") == "") {
        window.parent.cihoAlert(msg.cx.lxglPskh, msgBox.dlgBtn.Ok, function () { $("#khdm", "#" + strDialogP020501).combobox("focus"); });
        return false;
    }
    //客户不存在
    else if ($("#khdm", "#" + strDialogP020501).combobox("getValue") == undefined) {
        window.parent.cihoAlert(msg.cx.lxglPskhNot, msgBox.dlgBtn.Ok, function () { $("#khdm", "#" + strDialogP020501).combobox("focus"); });
        return false;
    }
    //日期是否在有效范围内
    else if (strChittyDate.replace(/-/g, "/") < window.parent._startDate) {
        window.parent.cihoAlert(msg.other.djrqExtent, msgBox.dlgBtn.Ok, function () { $("#djdate", "#" + strDialogP020501).focus(); });
        return false;
    }
    //表格数据的验证
    else {
        objDataGrid = $("#" + strTableP020501);
        arrDataIDs = objDataGrid.getDataIDs();

        //循环表格
        for (var intI = 0; intI < arrDataIDs.length; intI++) {
            if (objDataGrid.getCell(arrDataIDs[intI], "flag") != "") {
                //验证数据行信息是否全部为空
                isEmptyRow = checkRowNull(arrDataIDs[intI]);
                //arrColData = $("#" + arrDataIDs[intI] + " td:visible");
                //for (var intJ = 1; intJ < arrColData.length - 1; intJ++) {
                //    if (trim((arrColData[intJ].innerText)) != "") {
                //        isEmptyRow = false;
                //        break;
                //    }
                //    else {
                //        isEmptyRow = true;
                //    }
                //}
                //isEmptyRow = checkEmptyRow(objDataGrid.getRowData(arrDataIDs[intI]), "");  //验证数据行信息是否全部为空

                //行数据不为空时，执行下面的验证
                if (isEmptyRow == false) {
                    //配送日期
                    if (objDataGrid.getCell(arrDataIDs[intI], "psdate") == "") {
                        window.parent.cihoAlert(msg.cx.lxglPsrq.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //配送日期格式
                    else if (checkDatePattern(objDataGrid.getCell(arrDataIDs[intI], "psdate")) == false) {
                        window.parent.cihoAlert(msg.cx.lxglPsrq1.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //客户
                    else if (objDataGrid.getCell(arrDataIDs[intI], "kh") == "") {
                        window.parent.cihoAlert(msg.cx.lxglKh.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //客户代码
                    else if (objDataGrid.getCell(arrDataIDs[intI], "dm") == "") {
                        window.parent.cihoAlert(msg.cx.lxglKhNot.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //销售类型
                    else if (objDataGrid.getCell(arrDataIDs[intI], "lxmc") == "") {
                        window.parent.cihoAlert(msg.cx.lxglXslx.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //销售类型为配送时，两个客户不能相同
                    else if (objDataGrid.getCell(arrDataIDs[intI], "dm") == $("#khdm", "#" + strDialogP020501).combobox("getValue") && objDataGrid.getCell(arrDataIDs[intI], "lxdm") == "1") {
                        window.parent.cihoAlert(msg.cx.lxglKh1.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //数量
                    else if (objDataGrid.getCell(arrDataIDs[intI], "a1") == "" || parseFloat(objDataGrid.getCell(arrDataIDs[intI], "a1")) == 0) {
                        window.parent.cihoAlert(msg.cx.lxglSl.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //单价
                    else if (objDataGrid.getCell(arrDataIDs[intI], "a2") == "" || parseFloat(objDataGrid.getCell(arrDataIDs[intI], "a2")) == 0) {
                        window.parent.cihoAlert(msg.cx.lxglDj.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //销售员
                    else if (objDataGrid.getCell(arrDataIDs[intI], "zymc") != "" && objDataGrid.getCell(arrDataIDs[intI], "zymc") == "") {
                        window.parent.cihoAlert(msg.cx.lxglDj.replace("NO", (intI + 1).toString()));
                        return false;
                    }
                    //格式化配送日期
                    objDataGrid.setCell(arrDataIDs[intI], "psdate", formatDate(objDataGrid.getCell(arrDataIDs[intI], "psdate")));
                    //计算表格数据条数
                    intDataCount++;
                }
                //行数为空时，做删除操作
                else if (objDataGrid.getCell(arrDataIDs[intI], "mxguid") != "") {
                    arrRecordsP020501.push("{\"mxguid\":\"" + objDataGrid.getCell(arrDataIDs[intI], "mxguid") + "\",\"flag\":\"3\"}");
                }
            }
        }

        //表格中没有数据，不能保存
        if (intDataCount <= 0) {
            window.parent.cihoAlert(msg.cx.lxglLxd);
            return false;
        }
        //合计大于1亿时提醒
        else if (parseFloat(objDataGrid.footerData("get").a1) >= window.parent._MaxPerBill || parseFloat(objDataGrid.footerData("get").je) >= window.parent._MaxPerBill) {
            window.parent.cihoAlert(msg.other.djhjExtent);
            return false;
        }


    }

    //释放内存
    objDataGrid = null;
    arrDataIDs = null;
    arrColData = null;
    isEmptyRow = null;
    intDataCount = null;
    strChittyDate = null;

    //返回值
    return true;
}

//释放内存
function freeMemory_P020501() {
    strOldInfo_P020501 = "";    //影响预提费用的数据
    intMaxRowIDP020501 = 0;     //新数据行的编号
    intStockCountP020501 = 0;   //剩余库存
    arrRecordsP020501 = [];     //记录表格中需要操作数据
    objConfigP020501 = {};      //窗口元素的配置信息
    objCellPlace = { iRow: 0, iCol: 0, rowid: "", value: "" }; //记录当前编辑状态的单元格
}

/*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑**自定义方法 结束**↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/