var cols = ["spdm", "a1", "a2"];
var compareData;
var searchParam = {};
var cellX, cellY;
var bLoadComplete = false;

//初始化页面
function pageLoad_P0303() {
    try {
        initInputsP0303();
        var config = ParseData(window.external.DoOptions(strTableP0303, "GetTableConfig", "{}"));
        createGrid(strTableP0303, config.colNames, config.colModel, [], null, null, true, alterRowDataP0303);
        bindGridEventP0303();
        addColFormater(strTableP0303);
        resizeGrid(strTableP0303, true, true);
        createPage(strPageP0303, strTableP0303);
        searchDataClick_P0303(1);
    } catch (e) { }
}

//初始化input控件
function initInputsP0303() {
    $("#sjtype,#ckdmP0303,#ypdmP0303,#djtypebh").combobox();
    addArrowClass();

    //绑定日期控件
    inputAndBindData("sdate", false, "", dateChange);
    inputAndBindData("edate", false, "", dateChange);

    //加载时间类型combobox数据，并绑定事件
    $("#sjtype").combobox({
        width: _iWidth100,
        listWidth: _iWidth100,
        valueField: "dm",
        textField: "mc",
        editable: false,
        panelHeight: 102,
        onSelect: function () {
            var newValue = $(this).combobox("getValue");
            dateExtentCalculation(newValue, "sdate", "edate");
        },
        enterDown: function () {
            var newValue = $(this).combobox("getValue");
            dateExtentCalculation(newValue, "sdate", "edate");
        }
    });
    var options = [{ dm: "本月", mc: "本月" }, { dm: "上一月", mc: "上一月" }, { dm: "本周", mc: "本周" }, { dm: "过去三个月", mc: "过去三个月" }, { dm: "本年", mc: "本年"}];
    $("#sjtype").combobox("loadData", options);

    //加载单据类型combobox数据，并绑定事件
    $("#djtypebh").combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        editable: false,
        panelHeight: 82,
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "全部单据") {
                $(this).combobox("setText", "");
            }
        }
    });
    var djtype = [{ "dm": "", "mc": "全部单据" }, { "dm": "701", "mc": "报损" }, { "dm": "702", "mc": "报溢" }, { "dm": "703", "mc": "赠送"}];
    $("#djtypebh").combobox("loadData", djtype);
    $("#djtypebh").combobox("setValue", "");


    //加载仓库combobox数据，并绑定事件
    $("#ckdmP0303").combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "全部仓库") {
                $(this).combobox("setText", "");
            }
        }
    });
    var cklist = getComboboxData("TCkxx2");
    cklist.unshift({ "dm": "", "mc": "全部仓库" });
    $("#ckdmP0303").combobox("loadData", cklist);

    //加载药品combobox数据，并绑定事件
    $("#ypdmP0303").combobox({
        width: _iWidth120,
        listWidth: _iWidth120,
        valueField: "dm",
        textField: "mc",
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "全部药品") {
                $(this).combobox("setText", "");
            }
        }
    });
    var yplist = getComboboxData("Tspxx2");
    yplist.unshift({ "dm": "", "mc": "全部药品" });
    $("#ypdmP0303").combobox("loadData", yplist);

    //设置combobox初始值
    $("#ckdmP0303,#ypdmP0303").combobox("setValue", "");
    $("#sjtype").combobox("setValue", "本月");
    dateExtentCalculation("本月", "sdate", "edate");

    bLoadComplete = true;
    $(".layoutpanel").css("z-index", "50000009");
}

//日期范围修改方法
function dateChange() {
    if ($("#sjtype").combobox("getText") != "自定义") {
        $("#sjtype").combobox("setValue", "");
        $("#sjtype").combobox("setText", "自定义");
    }
}

//设置grid的双击事件
function alterRowDataP0303(altertype, rowid) {
    try {
        var alterItem = $("#" + strTableP0303).getRowData(rowid);
        if (/^BS/i.test(alterItem.djbh)) { //打开报损单修改页面
            openBSD(alterItem.djbh);
        } else if (/^BY/i.test(alterItem.djbh)) { //打开报溢单修改页面
            openBYD(alterItem.djbh);
        }
    } catch (e) { }
}

//删除管理页面数据
function delRowDataP0303(rowId) {
    try {
        var delItem = $("#" + strTableP0303).getRowData(rowId);
        window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
            if (msgBox.dlgRst.Yes == strRet) {
                if (delItem.glsl > 0) {
                    window.parent.cihoAlert(msg.del.delForbid, msgBox.dlgBtn.Ok);
                } else {
                    var s = ParseData(window.external.DoOptions(strTableP0303, "Delete", '{"djbh":"' + delItem.djbh + '","djdate":"' + delItem.djdate + '"}'));
                    if (s.ReturnCode == 0) {
                        searchDataClick_P0303(2);
                    } else {
                        window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
                    }
                }
            }
        });
    } catch (e) { }
}

//查询按钮的方法
function searchDataClick_P0303(flag) {
    try {
        var sdate = $("#sdate").val();
        var edate = $("#edate").val();
        var ckdm = $("#ckdmP0303").combobox("getValue");
        var spdm = $("#ypdmP0303").combobox("getValue");
        var djtypebh = $("#djtypebh").combobox("getValue");

        if (ckdm == null) { $("#ckdmP0303").combobox("setValue", ""); ckdm = ""; }
        if (spdm == null) { $("#ypdmP0303").combobox("setValue", ""); spdm = ""; }

        if (flag == 1) {
            searchParam.sortfield = "djdate";
            searchParam.orderby = "desc";
        }

        searchParam.flag = flag;
        searchParam.where = '"sdate":"' + sdate + '","edate":"' + edate + '","ckdm":"' + ckdm + '","spdm":"' + spdm + '","djtypebh":"' + djtypebh + '"';

        var s = loadGridData_Page(searchParam);
        searchParam.flag = 0;
        if (s.Records.length == 0) {
            s.sl = s.je = "&nbsp;";
        }
        $("#" + strTableP0303).footerData("set", { rn: "合计", sl: s.sl, je: s.je }, true);
        $("#" + strTableP0303).sortData("djdate");
    } catch (e) { }
}

//为grid绑定事件
function bindGridEventP0303() {
    $("#" + strTableP0303).setGridParam({
        onSelectRow: function (rowId) {
            try {
                selRowId = rowId;
                var selItem = $(this).getRowData(rowId);
                if (selItem.djbh) {
                    var strBtns = '<a  onclick="alterRowDataP0303(2,' + rowId + ');return false; ">修改</a>-<a onclick="delRowDataP0303(' + rowId + ');return false; ">删除</a>';
                    createFloatButton.call(this, rowId, strBtns);
                }
            } catch (e) { }
        },
        onSortCol: function (index, colindex, sortorder) {
            try {
                searchParam.sortfield = index;
                searchParam.orderby = sortorder;
                loadGridData_Page(searchParam);
                $("div.operate").hide();
                return "stop";
            } catch (e) { }
        },
        gridComplete: function () { //设置退货单的字体颜色
            try {
                var Ids = $(this).getDataIDs();
                for (var i = 0; i < Ids.length; i++) {
                    var djbh = $(this).getCell(Ids[i], "djbh");
                    if (/^BS/i.test(djbh)) {
                        $("#" + Ids[i], this).css("color", "#996600");
                    }
                }
            } catch (e) { }
        }
    });
}

//========================窗口公共方法====================

//创建窗口input元素和grid
function createElements(tbId, dlgId) {
    var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", "{}"));     // 向后台请求配置信息
    var header = createInputs(config.pageHeader);                                        // 根据头配置 生成表单元素 
    var footer = createInputs(config.pageFooter);                                        //根据脚信息   生成表单元素
    $("#" + dlgId + "_divform").append(header+'<table id="' + tbId + '"></table>'+footer);                                          //添加头
    config.colNames.push("操作");
    config.colModel.push({ "sortable": false, "edittype": "text", "editable": false, "index": "cz", "hidden": false, "width": 80, "editrules": { "required": false }, "name": "cz", "Formatter": {}, "align": "center" });
    createDjGrid(tbId, config.colNames, config.colModel);
    var vCols = [];
    for (var i in config.colModel) {
        if (config.colModel[i].editable && !config.colModel[i].hidden) {
            vCols.push(config.colModel[i].index);
        }
    }
    $("#" + tbId).data("vCols", vCols);
    $("#" + tbId).setLabel("rn", "序号");
    $(".ui-jqgrid-htable th:visible:last", "#" + dlgId).html('<img id="btnAdd"  style="cursor:pointer"  title="添加行" src="../../Content/Default/images/edit_add.gif" onclick="addNewRow(\'' + tbId + '\');return false; "/>');
}

//创建表单元素
function createInputs(arr) {
    var strForm = "<ul>";
    for (i = 0; i < arr.length; i++) {
        var Item = arr[i];
        if (!Item.hidden) {
            if (Item.edittype == "text") {
                strForm += "<li>";
                strForm += Item.xsmc + "：";
                strForm += "<input type='text'  name='" + Item.index + "' ";
                strForm += " value=''  ";
                strForm += " id='" + Item.index + "' ";
                if (!Item.editable) { strForm += " disabled='disabled'"; }
                if (Item.index != "a4") {
                    strForm += " maxlength='50' ";
                }
                strForm += " onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>";
                strForm += "</li>";
            } else if (Item.edittype == "select") {
                strForm += "<li>";
                strForm += Item.xsmc + "：";
                strForm += "<select name='" + Item.index + "' id='" + Item.index + "'";
                strForm += " class='easyui-combobox' >";
                strForm += "</select>";
                strForm += "</li>";
            }
        }
    }
    strForm += "</ul>";
    return strForm;
}

//为grid的列添加格式化函数
function addColFormater(tbId) {
    var $tbId = $("#" + tbId);
    $tbId.setColProp("sl", { formatter: formatCountPlace });
    $tbId.setColProp("dj", { formatter: formatPricePlace });
    $tbId.setColProp("je", { formatter: formatMoneyPlace });
    $tbId.setColProp("spmc", { editoptions: { custom_element: my_input, custom_value: my_value} });
    if (tbId == strTableP0303) {
        $tbId.setColProp("djtypebh", { formatter: function (cellValue) {
            switch (cellValue) {
                case "701": return "报损"; break;
                case "702": return "报溢"; break;
                case "703": return "赠送"; break;
                default: return "&nbsp;"; break;
            }
        }
        });
    }
    if (tbId == strTableP030301) {
        $tbId.setColProp("mxzymc", { editoptions: { custom_element: my_input, custom_value: my_value} });
        $tbId.setColProp("khmc", { editoptions: { custom_element: my_input, custom_value: my_value} });
    }
    $tbId = null;
}

//加载窗口grid数据，并计算合计
function loadGridData(tbId, mylist) {
    var count = mylist.length > 5 ? mylist.length : 5;
    //添加行并为行分配id，并计算合计
    var hjsl = 0, hjje = 0;
    var $tbId = $("#" + tbId);
    for (var i = 0; i < count; i++) {
        if (mylist[i]) {                                             //添加后台数据行
            hjsl += parseFloat(mylist[i].sl);
            hjje += parseFloat(mylist[i].je);
            $tbId.addRowData(i + 1, mylist[i]);                     //添加后台数据行
        }
        else {                                                      //添加空行
            $tbId.addRowData(i + 1, {});
        }
    }
    $tbId.footerData("set", { rn: "合计", sl: hjsl.toFixed(window.parent.strCountPlace), je: hjje.toFixed(window.parent.strMoneyPlace) });
    $tbId.data("nextNum", count + 1);
    resizeGridScroll(tbId);
    $tbId = null;
}


//关闭窗口
function closeMyDlg(dlgId, strType, strTableName) {
    try {
        var isChange = $("#" + dlgId).data("change");
        if (isChange) {
            window.parent.cihoAlert(msg.other.haveChange, msgBox.dlgBtn.YesNoCancel, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    saveMyData(dlgId, 1, strTableName); //保存单据
                }
                else if (msgBox.dlgRst.No == strRet) {
                    cihoDlgClose(dlgId);
                }
            }
        );
        } else {
            cihoDlgClose(dlgId);
        }
    } catch (e) { }
}

//为操作按钮注册事件
function bindDelEvent(tbId) {
    $("#" + tbId).delegate("tr[id]:visible", "hover", function (e) {
        if (e.type == "mouseenter") {
            var btn = '<a style="color:red;cursor:pointer;text-decoration:none" onclick="delDjRow(\'' + tbId + '\',' + this.id + ');return false; ">删除</a>';
            $("#" + tbId).setCell(this.id, "cz", btn);
        }
        if (e.type == "mouseleave") {
            $("#" + tbId).setCell(this.id, "cz", null);
        }
    });
}


//删除窗口中的grid数据
function delDjRow(tbId, rowId) {
    try {
        var $tbId = $("#" + tbId);
        $tbId.saveCell(cellX, cellY);
        var delItem = $tbId.getRowData(rowId);
        var vCols = $tbId.data("vCols");
        if (delItem.flag && !isRowEmpty(delItem, vCols)) {              //如果有操作标示，或者行不为空，就提示是否要删除
            window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    if (delItem.glsl > 0) {
                        window.parent.cihoAlert(msg.del.delForbid, msgBox.dlgBtn.Ok);
                    } else {
                        var $grid = $("#" + tbId);
                        var row = $grid.getRowData(rowId);
                        $grid.delRowData(rowId);
                        if (row.mxguid) {                                   //如果存在mxguid则保持到records数组里
                            var records = $grid.data("records");
                            records.push('{"mxguid":"' + row.mxguid + '","flag":"3"}');
                            $grid.data("records", records);
                            changeZt(tbId);                                //改变窗口的状态
                        }
                        sumGridTotal(tbId);
                        resizeGridScroll(tbId);
                    }
                }
            });
        } else {
            $tbId.delRowData(rowId);
            if (delItem.mxguid) {                                   //如果存在mxguid则保持到records数组里
                var records = $tbId.data("records");
                records.push('{"mxguid":"' + delItem.mxguid + '","flag":"3"}');
                $tbId.data("records", records);
                changeZt(tbId);                                      //改变窗口的状态
            }
            sumGridTotal(tbId);
            resizeGridScroll(tbId);
        }
    } catch (e) { }
}


//改变对话框或数据行的状态
//如果只提供表格id，则只改变窗口的状态标志
function changeZt(tbId, rowId) {
    if (tbId == strTableP030301) {
        $("#" + strDivP030301).data("change", true);
    } else {
        $("#" + strDivP030302).data("change", true);
    }
    if (rowId) {
        var item = $("#" + tbId).getRowData(rowId);
        if (item.mxguid) {
            $("#" + tbId).setCell(rowId, "flag", 2);                               //2代表更新
        } else {
            $("#" + tbId).setCell(rowId, "flag", 1);                               //1代表新增
        }
        item = null;
    }
}

//计算grid脚部合计
function sumGridTotal(tbId) {
    var ypsl = 0, ypje = 0;
    var $tbId = $("#" + tbId);
    var ids = $tbId.getDataIDs();
    for (var i = 0; i < ids.length; i++) {
        var tempItem = $tbId.getRowData(ids[i]);
        ypsl += isNaN(tempItem.sl) ? 0 : tempItem.sl * 1;
        ypje += isNaN(tempItem.je) ? 0 : tempItem.je * 1;
    }
    $tbId.footerData("set", { rn: "合计", sl: ypsl, je: ypje }, true);
    $tbId = null;
}


//添加空行
function addNewRow(tbId) {
    try {
        var $tbId = $("#" + tbId);
        var nextNum = $tbId.data("nextNum") + 1;
        $tbId.addRowData(nextNum, {});
        $tbId.data("nextNum", nextNum);
        resizeGridScroll(tbId);
    } catch (e) { }
}

//初始化表单元素属性和事件
function initInputsProp(dlgId, tbId) {
    try {
        var $dlgId = $("#" + dlgId);

        //设置表单元素宽度
        $("#djdate,#djtypebh,#zymc", $dlgId).parent().addClass("inp_70");
        $("#a4", $dlgId).parent().addClass("bz");

        //为单据时间绑定日历控件，并绑定事件
        inputAndBindData("djdate", false, "#" + dlgId, function () { $("#" + dlgId).data("change", true); changePrice(tbId, dlgId); });
        $("#djdate", $dlgId).change(function () { if (checkDatePattern(this.value)) { changePrice(tbId, dlgId); } }).focus(function () { $(this).select(); });

        //初始化仓库combobox并绑定事件，加载数据
        $("#ckmc", $dlgId).combobox({
            valueField: "dm",
            textField: "mc",
            onSelect: function (item) {
                if (item.dm == "-1") {
                    ciho.IniData({ id: "divAddType", title: "仓库", table: "Tflxx" }, { model: "TCkxx", jquery: $(this) });
                    $(this).combobox("setValue", "");
                }
            },
            afterChange: function (newValue, newText) {
                if (newValue == "-1") {
                    ciho.IniData({ id: "divAddType", title: "仓库", table: "Tflxx" }, { model: "TCkxx", jquery: $(this) });
                    ciho.showTypeDialog();
                    $(this).combobox("setValue", "");
                }
            }
        });
        var cklist = getComboboxData("TCkxx");
        cklist.push({ "mc": "<font color='red'>添加仓库</font>", "dm": "-1" });
        $("#ckmc", $dlgId).combobox("loadData", cklist);

        //初始化职员combobox并绑定事件，加载数据
        $("#zymc", $dlgId).combobox({
            valueField: "dm",
            textField: "mc",
            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", "");
                }
            }
        });
        var zylist = getComboboxData("TZyxx");
        zylist.push({ "mc": "<font color='red'>添加经手人</font>", "dm": "-1" });
        $("#zymc", $dlgId).combobox("loadData", zylist);

        if (dlgId == strDivP030301) {
            //初始化单据类型combobox，并加载
            $("#djtypebh", $dlgId).combobox({
                valueField: "dm",
                textField: "mc",
                panelHeight: 42,
                editable: false
            });
            $("#djtypebh", $dlgId).combobox("loadData", [{ "dm": "701", "mc": "报损" }, { "dm": "703", "mc": "赠送"}]);
        }

        //为仓库combobox赋值
        if (cklist.length == 2) { $("#ckmc", $dlgId).combobox("setValue", cklist[0].dm); }

        //为表单元素注册事件
        $("#ckmc,#zymc,#djtypebh", $dlgId).combobox({ onChange: function () { $("#" + dlgId).data("change", true); } });
        $("#zymc,#ckmc,#a4", $dlgId).change(function () { $("#" + dlgId).data("change", true); });
        $("#a4", $dlgId).focus(function () { $(this).select(); });
        $dlgId = null;
    } catch (e) { }
}

//日期更改后，更改最低单价，金额，合计
function changePrice(tbId, dlgId) {
    var $tbId = $("#" + tbId);
    var date = $("#djdate", "#" + dlgId).val();
    if (/^\s*(\d{4})-(\d{2})-\d{2}\s*$/.test(date)) {
        var months = date.replace(/^\s*(\d{4})-(\d{2})-\d{2}\s*$/, "$1$2");
        var ids = $tbId.getDataIDs();
        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.spdm) {
                //这里根据药品编号、月份，请求单价
                var jsonStr = '{"spdm":"' + item.spdm + '","months":"' + months + '","fb":"1"}';
                var dj = window.external.DoOptions(tbId, "DoOthers", jsonStr);
                if (/^\d+(\.\d+)?$/.test(dj)) {
                    $tbId.setCell(ids[i], "dj", dj);
                    var sl = $tbId.getCell(ids[i], "sl");
                    if (/^\d+(\.\d+)?$/.test(sl)) {
                        $tbId.setCell(ids[i], "je", sl * dj);
                    } else {
                        $tbId.setCell(ids[i], "je", null);
                    }
                } else {
                    $tbId.setCell(ids[i], "dj", null);
                }
            }
        }

    }
    sumGridTotal(tbId);
    $tbId = null;
}


//重新选择药品后要修改本行的单价和合计
//需要优化
function changeRowPrice(dlgId, tbId, rowId) {
    var $tbId = $("#" + tbId);
    var item = $tbId.getRowData(rowId);
    if (item.spdm) {
        var date = $("#djdate", "#" + dlgId).val();
        if (/^\s*(\d{4})-(\d{2})-\d{2}\s*$/.test(date)) {
            var months = date.replace(/^\s*(\d{4})-(\d{2})-\d{2}\s*$/, "$1$2");
            var jsonStr = '{"spdm":"' + item.spdm + '","months":"' + months + '","fb":"1"}';
            var dj = window.external.DoOptions(tbId, "DoOthers", jsonStr);
            if (/^\d+(\.\d+)?$/.test(dj)) {
                $tbId.setCell(rowId, "dj", dj);
                var sl = $tbId.getCell(rowId, "sl");
                if (/^\d+(\.\d+)?$/.test(sl)) {
                    $tbId.setCell(rowId, "je", sl * dj);
                } else {
                    $tbId.setCell(rowId, "je", null);
                }
            } else {
                $tbId.setCell(rowId, "dj", null);
            }
        }
    }
    sumGridTotal(tbId);
    $tbId = item = null;
}

//验证窗口数据
function authMyBills(tbId, dlgId) {
    try {
        var amount = $("#" + tbId).footerData("get").je * 1;
        var maxAmount = window.top._MaxPerBill;
        if (amount >= maxAmount) {
            window.parent.cihoAlert(msg.other.djhjExtent, msgBox.dlgBtn.Ok);
            return false;
        }

        //验证时间
        var djdate = $("#djdate", "#" + dlgId).val();
        if (!djdate) {
            window.parent.cihoAlert("请录入单据日期！", msgBox.dlgBtn.Ok, function () { $("#djdate", "#" + dlgId).focus(); $("#djdate", "#" + dlgId).select(); });
            return false;
        } else {
            var djdt = djdate.replace(/-/g, "/");
            if (djdt < window.top._startDate) {
                window.parent.cihoAlert(msg.other.djrqExtent, msgBox.dlgBtn.Ok, function () { $("#djdate", "#" + dlgId).focus(); $("#djdate", "#" + dlgId).select(); });
                return false;
            }
        }

        var data = $("#" + dlgId).data("data");

        //验证仓库

        var $ck = $("#ckmc", "#" + dlgId);
        var ckdm = $ck.combobox("getValue");
        var ckmc = $ck.combobox("getText");

        if (!ckdm && ckmc != data.ckmc) {
            window.parent.cihoAlert(msg.sz.ck.empOrNotExit, msgBox.dlgBtn.Ok, function () { $ck.combobox("focus"); });
            return false;
        }
        //验证经手人

        var $zy = $("#zymc", "#" + dlgId);
        var zydm = $zy.combobox("getValue");
        var zymc = $zy.combobox("getText");

        if (!zydm && zymc != data.zymc) {
            window.parent.cihoAlert(msg.sz.jsr.empOrNotExit, msgBox.dlgBtn.Ok, function () { $zy.combobox("focus"); });
            return false;
        }
        //验证制单人
        var czydm = $("#czymc", "#" + dlgId).val();
        if (!czydm) {
            window.parent.cihoAlert(msg.other.inputZdr, msgBox.dlgBtn.Ok, function () { $("#czydm", "#" + dlgId).select(); });
            return false;
        }

        if (tbId == strTableP030301) {
            var djtypebh = $("#djtypebh", "#" + dlgId).combobox("getValue");
        }
        var $tbId = $("#" + tbId);
        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.spdm) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.yp.lnEmpOrNotExit, msgBox.dlgBtn.Ok);      //alert("请选择第【" + (i + 1) + "】行的药品！");
                    ids = item = null;
                    return false;
                }
                if (!item.sl) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.yp.lnAmountEmp, msgBox.dlgBtn.Ok);         //alert("请输入第【" + (i + 1) + "】行的药品数量！");
                    ids = item = null;
                    return false;
                }
                if (djtypebh == "703" && !item.khdm) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.kh.lnEmpOrNotExit, msgBox.dlgBtn.Ok);      //alert("请选择第【" + (i + 1) + "】行的客户名称为空或者不存在！");
                    ids = item = null;
                    return false;
                }
            }
        }
        return true;
    } catch (e) { }
}

//保存单据，
//afterSave：1：保存退出
//                  2：保存增加
//tbId：        1：报损：Tp030301
//                  2：报溢：Tp030302
function saveMyData(dlgId, afterSave, tbId) {
    try {
        //添加分类
        if (tbId == ciho.layal.table) {
            ciho.saveType(); return;
        }

        var $tbId = $("#" + tbId);
        $tbId.saveCell(cellX, cellY);
        if (!authMyBills(tbId, dlgId)) { return false; } //验证单据信息

        //组织grid里面的数据
        var recordCount = 0;
        var vCols = $tbId.data("vCols");
        var ids = $tbId.getDataIDs();
        var records = $tbId.data("records");
        var isP030301 = tbId == strTableP030301 ? true : false;
        var rows = [];
        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 record = '{"mxguid":"' + item.mxguid + '","spdm":"' + item.spdm + '","a1":"' + item.sl + '","a2":"' + item.dj + '","flag":"' + item.flag + '"';
                    if (isP030301) {
                        record += ',"zydm":"' + item.mxzydm + '","khdm":"' + item.khdm + '"';
                    }
                    record += '}';
                    rows.push(record);
                } else if (item.mxguid) {
                    rows.push('{"mxguid":"' + item.mxguid + '","flag":"3"}');
                }
            }
        }

        if (recordCount == 0) {
            window.parent.cihoAlert("单据不能为空！", msgBox.dlgBtn.Ok);
            return false;
        }

        //组织页头和页脚
        var inputs = [];
        var $dlgId = $("#" + dlgId);

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

        var data = $dlgId.data("data");

        //仓库
        var $ck = $("#ckmc", $dlgId);
        var ckdm = $ck.combobox("getValue");
        var ckmc = $ck.combobox("getText");
        if (ckdm) {
            inputs.push('"ckdm":"' + ckdm + '"');
        } else if (ckmc == data.ckmc) {
            inputs.push('"ckdm":"' + data.ckdm + '"');
        }

        //经手人
        var $zy = $("#zymc", $dlgId);
        var zydm = $zy.combobox("getValue");
        var zymc = $zy.combobox("getText");
        if (zydm) {
            inputs.push('"zydm":"' + zydm + '"');
        } else if (zymc == data.zymc) {
            inputs.push('"zydm":"' + data.zydm + '"');
        }

        //业务类型
        if (tbId == strTableP030301) {
            inputs.push('"djtypebh":"' + $("#djtypebh", $dlgId).combobox("getValue") + '"');
        }

        var state = $dlgId.data("state");
        //制单人
        if (state == 1) {                                                                      //新增
            inputs.push('"czydm":"' + window.parent.objLoginInfo.code + '"');
        } else if (state == 2) {
            inputs.push('"czydm":"' + data.czydm + '"');                                       //修改
            inputs.push('"djbh":"' + data.djbh + '"');
        }

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

        //为了不破坏grid中的删除记录，所以用concat把删除记录跟修改记录连接，concat会返回连接后的数组
        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);
            } else {                            //保存退出
                cihoDlgClose(dlgId);
            }
            searchDataClick_P0303(0);
            if (state == 2) {
                if (compareData != getCompareData(tbId, cols)) {                    //发送信息到后台
                    var jsonStr = '{"fb":"2","djdate":"' + data.djbh + '"}';
                    window.external.DoOptions(tbId, "DoOthers", jsonStr);
                }
            }
        }
        else {
            window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }
        ids = inputs = s = null;
    } catch (e) { }
}

//保存新增后，初始化grid
function resetGrid(tbId, dlgId) {
    try {
        var $dlgId = $("#" + dlgId);
        $dlgId.data("data", {});
        $dlgId.data("state", 1);
        $("#" + tbId).clearGridData();
        loadGridData(tbId, []);

        $("#idMust", $dlgId).empty();
        $("#djdate", $dlgId).attr("disabled", false).val(getNowDate());
        $("#zymc", $dlgId).combobox("setValue", "");

        //初始化仓库
        var $ck = $("#ckmc", $dlgId);
        $ck.combobox("enable");
        var cklist = $ck.combobox("getData");
        if (cklist.length == 2) {
            $ck.combobox("setValue", cklist[0].dm);
        } else {
            $ck.combobox("setValue", "");
        }

        $("#czymc", $dlgId).attr("disabled", true).val(window.parent.objLoginInfo.name);
        $("#djtypebh", $dlgId).combobox("setValue", "701");
        $("#a4", $dlgId).val("");

        $dlgId.data("change", false);
        $dlgId = $ck = null;
    } catch (e) { }
}

//创建单据grid
function createDjGrid(strTableName, cNames, cModel) {
    $("#" + strTableName).jqGrid({
        datatype: "local",
        autowidth: true,
        colNames: cNames,
        colModel: cModel,
        rownumbers: true,
        footerrow: true,
        sortable: false,
        rownumWidth: 30,
        cellEdit: true,
        cellsubmit: "clientArray"
    });
}

//格式化grid中的combobox
function my_input(value, options) {
    return $('<select name="' + options.name + '" id="' + options.id + '"></select>').addClass("easyui-combobox");
}
function my_value(ele) {
    return ele.combobox('getText');
}

//格式化数量
function formatCountPlace(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strCountPlace);
    }
    else {
        return "&nbsp;";
    }
}

//格式化价格
function formatPricePlace(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strPricePlace);
    }
    else {
        return "&nbsp;";
    }
}
//格式化金额
function formatMoneyPlace(cellValue) {
    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strMoneyPlace);
    }
    else {
        return "&nbsp;";
    }
}

//========================公共方法========================
function refreshMyCombobox(strModels) {
    for (var i = 0; i < strModels.length; i++) {
        var data;
        //这里是当前页面有的comgbobox
        if (strModels[i] == "TCkxx") {
            data = getComboboxData(strModels[i] + "2");
            data.unshift({ dm: "", mc: "全部仓库" });
            reLoadCombobox("ckdmP0303", data);
        }
        if (strModels[i] == "Tspxx") {
            data = getComboboxData(strModels[i] + "2");
            data.unshift({ dm: "", mc: "全部药品" });
            reLoadCombobox("ypdmP0303", data);
        }
    }
}

//判断grid中的行是否为空行
function isRowEmpty(row, cols) {
    for (var i = 0; i < cols.length; i++) {
        if (!/^\s*$/.test(row[cols[i]])) {
            return false;
        }
    }
    return true;
}