/*************************
*功能：销项发票维护
*创建人：张振华
*时间：2010-08-15
*备注：此时间是加注释时间
*************************/

var strTableP040202 = "Tp040202";
var strDivP040202 = "divP040202";
var strSaveTypeP040202 = "1"; //保存类型
var objRecordsP040202;  //修改的记录
var strRecordsCountP040202; //总记录数
var iRowP040202 = -1;   //行索引
var iColP040202 = -1;   //列索引
var strDeletHtmlP040202 = "";   //删除
var strCurKpslp040202;  //开票税率

//创建grid
function createGridP040202(strTableID, objColNames, objColModel) {

    $("#" + strTableID).jqGrid({
        datatype: "local",
        sortname: "id",
        colNames: objColNames,
        colModel: objColModel,
        data: [],
        rowNum: 9999999,
        footerrow: true,
        rownumbers: true,
        autowidth: true,
        rownumWidth: 30,
        cellEdit: true,
        cellsubmit: "clientArray",
        gridview: true
    });

    //增加表头‘序号’列
    $("table.ui-jqgrid-htable th:first", $("#gbox_" + strTableID)).text("序号");
}

//格式化数量
function formatterP040202Count(cellValue) {

    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strCountPlace);
    }
    else {
        return "&nbsp;";
    }

}

//格式化单价
function formatterP040202Price(cellValue) {

    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strPricePlace);
    }
    else {
        return "&nbsp;";
    }
}

//格式化金额
function formatterP040202Money(cellValue) {

    if (!isNaN(parseFloat(cellValue))) {
        return parseFloat(cellValue).toFixed(window.parent.strMoneyPlace);
    }
    else {
        return "&nbsp;";
    }
}

//自定义元素
function my_inputP040202(value, options) {
    var strHtml = "<select class=\"easyui-combobox\" name=\"" + options.name + "\"  id=\"" + options.id + "\">";

    return $(strHtml);
}

//获取自定义元素的值
function my_valueP040202(ele) {
    return ele.combobox('getText');
}

//编辑单元格之后的事件
function afterEditCellP040202(rowId, cellname, value, iRow, iCol) {

    //行索引，列索引
    iRowP040202 = iRow;
    iColP040202 = iCol;

    //表格对象，单元格内控件
    var objTable = $("#" + strTableP040202);
    var item = $("#" + rowId + " :input[name='" + cellname + "']", this);

    switch (cellname) {
        case "spmc":

            //药品信息，药品代码
            var objSp = getComboboxData('Tspxx');
            var strSpdm = objTable.getCell(rowId, "spdm");

            item.combobox({
                width: _iWidth150,
                listWidth: _iWidth150,
                valueField: "dm",
                textField: "mc"
            });
            objSp.push({ "mc": "<font color='red'>添加药品</font>", "dm": "-1" });
            if (objSp != "{}") {
                item.combobox("loadData", objSp);
            }
            item.combobox("setValue", strSpdm);
            if (item.combobox("getText") != "" && item.combobox("getText") == strSpdm) {
                var strMcSp = "";
                for (var j = 0; j < objRecords.length; j++) {
                    if (objRecords[j].id == rowid) {
                        strMcSp = objRecords[j].spmc;
                        break;
                    }
                }

                item.combobox('setText', strMcSp);
            }
            item.combobox({
                onChange: function (newValue, oldValue) {
                    if (newValue != undefined && newValue != "-1") {
                        $("#" + strTableP040202).setCell(rowId, "spdm", newValue);
                    }
                    else {
                        $("#" + strTableP040202).setCell(rowId, "spdm", "&nbsp;");
                    }
                    dataChangeStateP040202(true);
                    ChangeFlagP040202(rowId);
                },
                onSelect: function (record) {

                    //带出单价
                    var strKhdm = $("#khdm", "#" + strDivP040202).combobox("getValue");
                    if (record.dm && strKhdm) {
                        var objRecord = ParseData(window.external.DoOptions(strTableP040202, "DoOthers", "{\"flag\":\"3\",\"spdm\":\"" + record.dm + "\",\"khdm\":\"" + strKhdm + "\"}"));
                        if (objRecord.ReturnCode != 0) {
                            return;
                        }
                        if (objRecord.Records.length != 0) {
                            var strDj = parseFloat(objRecord.Records[0].a1).toFixed(window.parent.strMoneyPlace);
                            var strCount = parseFloat($("#" + strTableP040202).getCell(rowId, "sl"));
                            if (!isNaN(strDj)) {
                                $("#" + strTableP040202).setCell(rowId, "dj", strDj);

                                //重新计算合计
                                if (!isNaN(strCount)) {
                                    $("#" + strTableP040202).setCell(rowId, "je", strCount * strDj);
                                    getTotalP040202();
                                }

                            }
                        }
                    }
                },
                afterChange: function (newValue, newText) {
                    if (newValue == "-1") {
                        ciho.IniData({ id: "divAddType", title: "药品", table: "Tflxx" }, { model: "Tspxx", jquery: $(this) });
                        ciho.showTypeDialog();
                    }
                }
            });
            item.combobox('focus');

            //设置层序
            $(".layoutpanel").css("z-index", "50000009");
            break;
        case "sl":
            //退货数量
            item.autoNumeric({ mDec: window.parent.strCountPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
        case "dj":
            //退货单价
            item.autoNumeric({ mDec: window.parent.strPricePlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
        case "je":
            //退票单价
            if (objTable.getCell(rowId, "a3") == "否" || objTable.getCell(rowId, "a3") == "") {
                objTable.restoreCell(iRow, iCol);
                return;
            }
            item.autoNumeric({ mDec: window.parent.strPricePlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
        default:
    }

    item.change(function () { dataChangeStateP040202(true); ChangeFlagP040202(rowId); });
    objTable = null;
    item = null;
}

//保存单元格之后的事件
function afterSaveCellP040202(rowId, cellname, value, iRow, iCol) {
    switch (cellname) {
        case "sl":
            //根据单价，数量计算金额
            var strDj = parseFloat($(this).getCell(rowId, "dj"));
            var strSl = parseFloat(value);
            if (isNaN(strSl) || isNaN(strDj)) {
                $(this).setCell(rowId, "je", "&nbsp;");
            }
            else {
                $(this).setCell(rowId, "je", parseFloat(strDj * strSl).toFixed(window.parent.strMoneyPlace));
            }
            getTotalP040202();
            break;
        case "dj":
            //根据单价，数量计算金额
            var strDj = parseFloat(value);
            var strSl = parseFloat($(this).getCell(rowId, "sl"));
            if (isNaN(strDj) || isNaN(strSl)) {
                $(this).setCell(rowId, "je", "&nbsp;");
            }
            else {
                $(this).setCell(rowId, "je", parseFloat(strDj * strSl).toFixed(window.parent.strMoneyPlace));
            }
            getTotalP040202();
            break;
    }
}

//释放内存
function freeMemory_P040202() {
    strSaveTypeP040202 = null;
    iRowP040202 = null;
    iColP040202 = null;
    objRecordsP040202 = null;
    strRecordsCountP040202 = null;
    strDeletHtmlP040202 = null;
}

//弹出层
function showDialogP040202(strType) {
    try {

        $("div .operate").hide();

        //保存类型
        strSaveTypeP040202 = strType;

        //弹出层，添加弹出层内容
        if (strSaveTypeP040202 == "1") {
            creatDiv_ShowDlgHaveTbl(strDivP040202, "销项发票", false, true, strTableP040202, "800");
            addDivContentP040202("", "");
        }
        else if (strSaveTypeP040202 == "2") {
            creatDiv_ShowDlgHaveTbl(strDivP040202, "销项发票", false, true, strTableP040202, "800");
            $("#idMust", "#" + strDivP040202).append("(" + objSelRowP0402.zt + ")");
            addDivContentP040202("2", objSelRowP0402.djbh);
        }
        else if (strSaveTypeP040202 == "3") {
            creatDiv_ShowDlgHaveTbl(strDivP040202, "销项发票", false, false, strTableP040202, "800");
            $("#idMust", "#" + strDivP040202).append("(" + objSelRowP0402.zt + ")");
            addDivContentP040202("3", objSelRowP0402.djbh);
        }
    }
    catch (e) {
        proceError("P040202", e.ToString());
    }
}

//修改Data change状态
function dataChangeStateP040202(bState) {
    $("#" + strDivP040202 + "_divform").data("change", bState);
}

//改变保存标志位
function ChangeFlagP040202(rowId) {

    var objTable = $("#" + strTableP040202);
    if (objTable.getCell(rowId, "mxguid") == "") {
        objTable.setCell(rowId, "flag", "1");
    }
    else {
        objTable.setCell(rowId, "flag", "2");
    }

    objTable = null;
}

//页面加载时添加的添加空行
function addEmptyRowsP040202() {
    for (var i = 999999999; i < 999999999 + strRecordsCountP040202; i++) {
        $("#" + strTableP040202).addRowData(i, { flag: "" });
    }
}

//浮动删除
function addCzHtmlP040202() {
    $("#" + strTableP040202).delegate("tr[id]:visible", "hover", function (e) {
        if (e.type == "mouseenter") {
            var strButtonHtml = "";
            strButtonHtml += "<a  style=\"color:red;text-decoration:none;cursor:pointer;\" onclick=\"deleteDataP040202(" + this.id + ");return false;\">删除</a> ";
            $("#" + strTableP040202).jqGrid("setCell", this.id, "cz", strButtonHtml);
        }
        else if (e.type == "mouseleave") {
            $("#" + strTableP040202).jqGrid("setCell", this.id, "cz", "&nbsp;");
        }
    });
}

//添加一空行
function addEmptyRowP040202() {
    if (strSaveTypeP040202 != "3") {
        $("#" + strTableP040202).addRowData(++strRecordsCountP040202, { id: strRecordsCountP040202 });
        addCzHtmlP040202();

        //调整表格宽度
        resizeGridScroll(strTableP040202);
    }
}

//弹出层内容
function addDivContentP040202(strZt, strFpbh) {

    //常用变量
    var i = 0;
    var strForm = "";
    var Item;
    objRecordsP040202 = { Records: [] };

    //配置信息和数据
    var config = ParseData(window.external.DoOptions(strTableP040202, "GetTableConfig", "{}"));

    //开票单位，客户
    var objInvDw = getComboboxData("Tkpdwxx");
    var objKh = getComboboxData("Tkhxx1");
    objKh.push({ "mc": "<font color='red'>添加客户</font>", "dm": "-1" });
    objInvDw.push({ "mc": "<font color='red'>添加开票单位</font>", "dm": "-1" });

    //取表格中的值
    if (strFpbh != "") {
        objRecordsP040202 = ParseData(window.external.DoOptions(strTableP040202, "GetList", "{djbh:\"" + objSelRowP0402.djbh + "\"}"));
    }

    //加载头部层内容
    strForm = "<ul>";
    for (i = 0; i < config.pageHeader.length; i++) {

        Item = config.pageHeader[i];
        if (Item.hidden == true) {
            continue;
        }
        if (Item.edittype == "text") {
            strForm += "<li class='inp_100'>";
            strForm += Item.xsmc + "：";
            strForm += "<input type='text'  name='" + Item.index + "' ";
            if (Item.index == "fpbh") {
                strForm += " onkeypress='return checkValidate1(event)' onpaste='return validatePaste()'  "
            }
            else {
                strForm += " onkeypress='return checkValidate(event)' onpaste='return validatePaste()'  "
            }
            strForm += " value=''  ";
            strForm += " id='" + Item.index + "'>";
            if (Item.index == "kpsl") {
                strForm += "%";
            }
            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>";
        }
        else if (Item.edittype == "checkbox") {
            strForm += "<li  class=\"unline\">";
            strForm += "<input id=" + Item.index + " type='checkbox' />";
            strForm += Item.xsmc;
            strForm += "</li>";
        }
    }
    strForm += "</ul>";
    strForm += "<table id=" + strTableP040202 + "></table>";

    //加载尾部层内容
    strForm += "<ul>";
    for (i = 0; i < config.pageFooter.length; i++) {
        Item = config.pageFooter[i];
        if (Item.hidden == true) {
            continue;
        }
        if (Item.edittype == "text") {
            if (Item.index == "a2") {
                strForm += "<li class='bz'>";
                strForm += Item.xsmc + "：";
                strForm += "<input type='text'  name='" + Item.index + "' ";
                strForm += " value=''  ";
                strForm += " id='" + Item.index + "'>";
                strForm += "</li>";
            } else {
                strForm += "<li class='inp_150'>";
                strForm += Item.xsmc + "：";
                strForm += "<input type='text'  name='" + Item.index + "' ";
                strForm += " value=''  ";
                strForm += " id='" + Item.index + "'>";
                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>";

    //添加到弹出层里
    $("#" + strDivP040202 + "_divform").append(strForm);

    //创建Grid
    createGridP040202(strTableP040202, config.colNames, config.colModel);
    $("#" + strTableP040202).setGridHeight(141);

    //设置表格属性
    var objTable = $("#" + strTableP040202);

    objTable.setColProp("je", { editable: true });
    objTable.setColProp("cz", { editable: false });
    if (strSaveTypeP040202 != "3") {
        objTable.setColProp("sl", { editable: true });
        objTable.setColProp("spmc", { editable: true });
        objTable.setColProp("dj", { editable: true });
        objTable.setColProp("je", { editable: true });
    }
    objTable.setColProp("sl", { formatter: formatterP040202Count });
    objTable.setColProp("dj", { formatter: formatterP040202Price });
    objTable.setColProp("je", { formatter: formatterP040202Money });
    objTable.setColProp("spmc", { edittype: "custom" });
    objTable.setColProp("spmc", { editoptions: { custom_element: my_inputP040202, custom_value: my_valueP040202} });
    objTable.setGridParam({ afterEditCell: afterEditCellP040202 });
    objTable.setGridParam({ afterSaveCell: afterSaveCellP040202 });

    //加载数据
    loadTreeData(strTableP040202, objRecordsP040202.Records);

    //计算添加空行
    if (objRecordsP040202.Records == "{}") {
        objRecordsP040202.Records = [];
    }
    strRecordsCountP040202 = objRecordsP040202.Records.length > 5 ? objRecordsP040202.Records.length : (5 - objRecordsP040202.Records.length);

    if (strRecordsCountP040202 <= 5) {
        addEmptyRowsP040202();
    }

    //添加浮动删除
    if (strSaveTypeP040202 != "3") {
        addCzHtmlP040202();
    }

    //计算合计
    getTotalP040202();

    //表格头部添加按钮
    $(".ui-jqgrid-htable th:visible:last").html('<img id="btnAddP010102"  style="cursor:pointer"  title="添加行" src="../../Content/Default/images/edit_add.gif" onclick="addEmptyRowP040202(); "/>');

    //单据日期默认值和事件
    $("#djdate", "#" + strDivP040202).val(getNowDate());
    inputAndBindData("djdate");
    $("#djdate", $("#" + strDivP040202 + "_divform")).blur(function () {
        $("#" + strDivP040202 + "_divform").data("change", true);
    });

    //开票单位加载值
    $("#kpdwdm", "#" + strDivP040202).combobox({
        width: _iWidth100,
        listWidth: _iWidth100,
        textField: "mc",
        valueField: "dm",
        onChange: function (newValue, oldValue) {
            dataChangeStateP040202(true);
        },
        afterChange: function (newValue, newText) {
            if (newValue == "-1") {
                ciho.IniData({ id: "divAddType", title: "开票单位", table: "Tflxx" }, { jquery: $("#kpdwdm", "#" + strDivP040202), model: "Tkpdwxx" });
                ciho.showTypeDialog();
            }

            //带出税率
            var strKpdwdm = $("#kpdwdm", "#" + strDivP040202).combobox("getValue");
            if (strKpdwdm && strKpdwdm != "-1") {
                var objRecord = ParseData(window.external.DoOptions(strTableP040202, "DoOthers", "{flag:'1',kpdwdm:'" + strKpdwdm + "'}"));
                if (objRecord.RecordCode == 0) {
                    strCurKpslp040202 = parseFloat(objRecord.kpsl * 100).toFixed(window.parent.strPercentPlace);
                    $("#kpsl", "#" + strDivP040202).val(strCurKpslp040202);
                }
            }

        }
    });
    if (objInvDw != "{}") {
        $("#kpdwdm", "#" + strDivP040202).combobox("loadData", objInvDw);
    }

    //客户加载数据
    $("#khdm", "#" + strDivP040202).combobox({
        width: _iWidth100,
        listWidth: _iWidth100,
        textField: "mc",
        valueField: "dm",
        onChange: function (newValue, oldValue) {
            dataChangeStateP040202(true);
        },
        onSelect: function (record) {
            if (record.dm) {
                var objRecord = ParseData(window.external.DoOptions(strTableP040202, "DoOthers", "{\"flag\":\"2\",\"khdm\":\"" + record.dm + "\"}"));
                if (objRecord.ReturnCode != 0) {
                    return;
                }
                if (objRecord.Records.length != 0) {
                    $("#kpdwdm", "#" + strDivP040202).combobox("setValue", objRecord.Records[0].kpdwdm);
                    strCurKpslp040202 = parseFloat(objRecord.Records[0].kpsl * 100).toFixed(window.parent.strPercentPlace);
                    $("#kpsl", "#" + strDivP040202).val(strCurKpslp040202);
                }
            }
        },
        afterChange: function (newValue, newText) {
            $(this).combobox("setText", newText.replace(/&nbsp;/g, ""));
            if (newValue == "-1") {
                ciho.IniData({ id: "divAddType", title: "客户", table: "Tflxx" }, { jquery: $("#khdm", "#" + strDivP040202), model: "Tkhxx" });
                ciho.showTypeDialog();
            }
        }
    });
    if (objKh != "{}") {
        $("#khdm", "#" + strDivP040202).combobox("loadData", objKh);
    }

    //制单人
    $("#czydm", "#" + strDivP040202).attr("disabled", true);
    $("#czydm", "#" + strDivP040202).val(window.parent.objLoginInfo.name);

    //税率改变，提示保存数据库
    $("#kpsl", "#" + strDivP040202).autoNumeric({ mDec: window.parent.strPercentPlace, aSep: ""}).focus(function () { this.select(); }).css("ime-mode", "disabled");
    $("#kpsl", "#" + strDivP040202).blur(function () {
        if ($(this).val() != ""&& strCurKpslp040202 && $(this).val() != strCurKpslp040202) {
            strCurKpslp040202 = $(this).val();
            var strValue = $("#kpdwdm", "#" + strDivP040202).combobox('getValue');
            if (strValue) {
                window.parent.cihoAlert(msg.other.SaveSlToDb, msgBox.dlgBtn.YesNo, function (result) {
                    if (result == msgBox.dlgRst.Yes) {
                        $(window.parent.document).find("#divMsgBox").dialog("close");
                        var strKpsl = $("#kpsl", "#" + strDivP040202).val();
                        if (!isNaN(parseFloat(strKpsl))) {
                            strKpsl = parseFloat(strKpsl) / 100;
                        }
                        var objResult = ParseData(window.external.DoOptions("Tp040202", "DoOthers", "{\"flag\":\"1\",\"kpsl\":\"" + strKpsl + "\",\"kpdwdm\":\"" + $("#kpdwdm", "#" + strDivP040202).combobox('getValue') + "\"}"));
                        if (objResult.RecordCode != 0) {
                            window.parent.cihoAlert(objResult.MSG);
                        }

                        //修改全局标志位
                        changePageZt("p0402","1");
                    }
                });
            }
        }

    });

    //金额
    $("#a1", "#" + strDivP040202).autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "", mNum: 9 }).focus(function () { this.select(); }).css("ime-mode", "disabled");

    //发票编号
    $("#fpbh", "#" + strDivP040202).focus(function () { this.select(); }); 
        
    //加载修改状态的值
    if (strSaveTypeP040202 == "2" || strSaveTypeP040202 == "3") {

        $("#djdate", "#" + strDivP040202).val(objRecordsP040202.djdate);
        $("#djdate", "#" + strDivP040202).attr("disabled", true);

        //开票单位
        $("#kpdwdm", "#" + strDivP040202).combobox('setValue', objRecordsP040202.kpdwdm);
        if ($("#kpdwdm", "#" + strDivP040202).combobox('getValue') == objRecordsP040202.kpdwdm) {
            $("#kpdwdm", "#" + strDivP040202).combobox('setText', objRecordsP040202.kpdwmc);
        }

        //开票税率
        strCurKpslp040202 = parseFloat(parseFloat(objRecordsP040202.kpsl) * 100).toFixed(window.parent.strPercentPlace);
        $("#kpsl", "#" + strDivP040202).val(strCurKpslp040202);

        //客户
        $("#khdm", "#" + strDivP040202).combobox('setValue', objRecordsP040202.khdm);
        if ($("#khdm", "#" + strDivP040202).combobox('getValue') == objRecordsP040202.khdm) {
            $("#khdm", "#" + strDivP040202).combobox('setText', objRecordsP040202.khmc);
        }

        //发票编号
        $("#fpbh", "#" + strDivP040202).val(objRecordsP040202.fpbh);

        //发票金额
        $("#a1", "#" + strDivP040202).val(parseFloat(objRecordsP040202.a1).toFixed(window.parent.strMoneyPlace));

        //是否非销售开票
        if (objRecordsP040202.sffxskp == "False") {
            $("#sffxskp", "#" + strDivP040202).attr("checked", false);
        }
        else {
            $("#sffxskp", "#" + strDivP040202).attr("checked", true);
        }

        //制单人
        $("#czydm", "#" + strDivP040202).val(objRecordsP040202.czymc);

        //备注
        $("#a2", "#" + strDivP040202).val(escape(objRecordsP040202.bz));
    }

    ///设定控件不可编辑
    if (strSaveTypeP040202 == "3") {
        $(":input", "#" + strDivP040202).attr("disabled", true);
    }

    //设定状态
    $(":input", $("#" + strDivP040202 + "_divform")).change(function () {
        $("#" + strDivP040202 + "_divform").data("change", true);
    });
    $("#" + strDivP040202 + "_divform").data("change", false);

    setTimeout('$("#fpbh", "#" + strDivP040202).focus()', 100);

    //调整表格宽度
    resizeGridScroll(strTableP040202);

    //设置弹出层位置
    $(".layoutpanel").css("z-index", "50000009");
}

//删除
function deleteDataP040202(rowId) {
    try {

        //删除的那行的数据
        var objTr = $("#" + strTableP040202).getRowData(rowId);

        //保存时取消单元格编辑
        $("#" + strTableP040202).saveCell(iRowP040202, iColP040202);

        //判断改行是否有数据
        if (checkEmptyRow(objTr, "glsl,cz") == false) {

            //删除时提示
            window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {

                    if (objTr.mxguid != "") {
                        //修改的时候
                        if (strDeletHtmlP040202 == null || strDeletHtmlP040202 == "") {
                            strDeletHtmlP040202 = ",{\"mxguid\":\"" + objTr.mxguid + "\",";
                            strDeletHtmlP040202 += "\"flag\":\"3\"}";
                        }
                        else {
                            strDeletHtmlP040202 += ",{\"mxguid\":\"" + objTr.mxguid + "\",";
                            strDeletHtmlP040202 += "\"flag\":\"3\"}";
                        }
                    }

                    //重新计算合计
                    $("#" + strTableP040202).delRowData(rowId);
                    dataChangeStateP040202(true);
                    getTotalP040202();

                    //重新加载发票编号
                    var strInvDwValue = $("#cmbInvoiceBhP0402").combobox("getValue");
                    var objFpBh = ParseData(window.external.DoOptions(strTableP0402, "GetComboBoxData", "{}"));
                    if (objFpBh != null && objFpBh.Records != "{}") {
                        objFpBh.Records.unshift({ mc: "全部发票", dm: "", selected: true });
                        $("#cmbInvoiceBhP0402").combobox("loadData", objFpBh.Records);
                    }
                    $("#cmbInvoiceBhP0402").combobox('setValue', strInvDwValue);

                    return;
                }
            });
        }
        else {
            $("#" + strTableP040202).delRowData(rowId);
        }

        //调整表格宽度
        resizeGridScroll(strTableP040202);
    }
    catch (e) {
        proceError("P040202", e.ToString());
    }

}

//检查表单
function checkFormP040202(dialog, save) {

    var strDjdate = $("#djdate", "#" + strDivP040202).val();

    //开票日期
    if (!strDjdate) {
        window.parent.cihoAlert(msg.dt.inputKpDt, null, function () { $("#djdate", "#" + strDivP040202).focus(); });
        return false;
    }

    //验证日期格式
    if (checkDatePattern(strDjdate) == false) {
        window.parent.cihoAlert(msg.dt.dtTypeErr, msgBox.dlgBtn.Ok, function () { $("#djdate", "#" + strDivP040202).focus(); });
        return false;
    }

    //验证日期在规定日期中
    if (strDjdate) {
        strDjdate = strDjdate.replace(/-/g, "/");
        if (strDjdate < window.parent._startDate) {
            window.parent.cihoAlert(msg.other.kprqExtent, null, function () { $("#djdate", "#" + strDivP040202).focus(); });
            return false;
        }

    }

    //客户
    var strKhText = $("#khdm", "#" + strDivP040202).combobox('getValue');
    if (!strKhText) {
        //修改时，验证数据是否是停用的数据
        if (strSaveTypeP040202 == "2" && $("#khdm", "#" + strDivP040202).combobox('getText') != objRecordsP040202.khmc) {
            window.parent.cihoAlert(msg.sz.kh.empOrNotExit, null, function () { $("#khdm", "#" + strDivP040202).combobox("focus"); });
            return false;
        }
        //新增的时候
        if (strSaveTypeP040202 == "1") {
            window.parent.cihoAlert(msg.sz.kh.empOrNotExit, null, function () { $("#khdm", "#" + strDivP040202).combobox("focus"); });
            return false;
        }
    }

    //开票单位
    var strKpDwValue = $("#kpdwdm", "#" + strDivP040202).combobox('getValue');
    if (!strKpDwValue) {
        //修改时，验证数据是否是停用的数据
        if (strSaveTypeP040202 == "2" && $("#kpdwdm", "#" + strDivP040202).combobox('getText') != objRecordsP040202.kpdwmc) {
            window.parent.cihoAlert(msg.sz.kp.SelKpdw, null, function () { $("#kpdwdm", "#" + strDivP040202).combobox("focus"); });
            return false;
        }
        //新增的时候
        if (strSaveTypeP040202 == "1") {
            window.parent.cihoAlert(msg.sz.kp.SelKpdw, null, function () { $("#kpdwdm", "#" + strDivP040202).combobox("focus"); });
            return false;
        }
    }

    //开票税率
    var strKpsl = $("#kpsl", "#" + strDivP040202).val();
    if (strKpsl == "") {
        window.parent.cihoAlert(msg.sz.kp.SelKpNoEmpty, null, function () { $("#kpsl", "#" + strDivP040202).focus(); });
        return false;
    }
    if (!isNaN(parseFloat(strKpsl)) && parseFloat(strKpsl) <= 0) {
        window.parent.cihoAlert(msg.sz.kp.SelKpRange, null, function () { $("#kpsl", "#" + strDivP040202).focus(); });
        return false;
    }

    //开票金额
    var strA1 = $("#a1", "#" + strDivP040202).val();
    if (strA1 == "") {
        window.parent.cihoAlert(msg.other.FpMoneyEmpty, null, function () { $("#a1", "#" + strDivP040202).focus(); });
        return false;
    }

    //发票编号
    if ($("#fpbh", "#" + strDivP040202).val() == "") {
        window.parent.cihoAlert(msg.other.fpBhNoEmpty, null, function () { $("#fpbh", "#" + strDivP040202).focus(); });
        return false;
    }

    //用来判断是否是空一条数据没有
    var bAddTable = false;

    //table对象，行id
    var objTable = $("#" + strTableP040202);
    var arrIds = objTable.getDataIDs();

    //保存编辑的单元格
    objTable.saveCell(iRowP040202, iColP040202);

    //判断表格的数据是否合法
    for (var i = 0; i < arrIds.length; i++) {

        //获取一行数据
        var objTr = objTable.getRowData(arrIds[i]);

        //改行没有被编辑退出
        if (objTr.flag == "") {
            continue;
        }

        //改行被编辑但是所有数据是空，退出
        if (checkEmptyRow(objTr, "flag,mxguid")) {
            continue;
        }
        bAddTable = true;
        var alterMsg = "";

        //商品代码，数量，单击不能为空
        if (!objTr.spdm) {
            alterMsg = msg.other.dnh + (i + 1) + msg.sz.yp.lnEmpOrNotExit;
            window.parent.cihoAlert(alterMsg);
            return false;
        }
        if (!objTr.sl) {
            alterMsg = msg.other.dnh + (i + 1) + msg.sz.yp.lnAmountEmp;
            window.parent.cihoAlert(alterMsg);
            return false;
        }
        if (!objTr.dj) {
            alterMsg = msg.other.dnh + (i + 1) + msg.sz.yp.lnPriceEmp;
            window.parent.cihoAlert(alterMsg);
            return false;
        }

    }

    //表格中是否有记录
    if (bAddTable == false) {
        window.parent.cihoAlert(msg.other.djNotExit);
        return false;
    }

    var fJe = parseFloat(objTable.footerData('get').je);

    //金额过大
    if (!isNaN(fJe) && fJe > window.parent._MaxPerBill) {
        window.parent.cihoAlert(msg.other.djhjExtent);
        return false;
    }

    // 金额不一致提示
    if (parseFloat(strA1) != fJe) {
        window.parent.cihoAlert(msg.other.FpMoney);
        return false;
    }


}

//保存到数据库
function saveToDbP040202(dialog, save) {

    //表格对象
    var objTable = $("#" + strTableP040202);
    var arrIds = objTable.getDataIDs();

    var strKpdw = $("#kpdwdm", "#" + strDivP040202).combobox('getValue');
    var strKhdm = $("#khdm", "#" + strDivP040202).combobox('getValue');

    //组保存到后台的数据
    var strData = "{";
    strData += "\"djdate\":\"" + $("#djdate", "#" + strDivP040202).val() + "\"";
    if (strSaveTypeP040202 == "2") {
        strData += ",\"djbh\":\"" + objSelRowP0402.djbh + "\"";
    }

    //如果停用取保存的值
    if (!strKpdw) {
        if (strSaveTypeP040202 == "2" && objRecordsP040202.Records != "{}" && $("#kpdwdm", "#" + strDivP040202).combobox('getText') == objRecordsP040202.Records[0].kpdwmc) {
            strKpdw = objRecordsP040202.Records[0].kpdwdm;
        }
    }
    strData += ",\"kpdwdm\":\"" + strKpdw + "\"";
    strData += ",\"kpsl\":\"" + parseFloat($("#kpsl", "#" + strDivP040202).val()) / 100 + "\"";

    //如果停用取保存的值
    if (!strKhdm) {
        if (strSaveTypeP040202 == "2" && objRecordsP040202.Records != "{}" && $("#khdm", "#" + strDivP040202).combobox('getText') == objRecordsP040202.Records[0].khmc) {
            strKhdm = objRecordsP040202.Records[0].khdm;
        }
    }
    strData += ",\"khdm\":\"" + strKhdm + "\"";
    strData += ",\"fpbh\":\"" + $("#fpbh", "#" + strDivP040202).val() + "\"";
    strData += ",\"a1\":\"" + $("#a1", "#" + strDivP040202).val() + "\"";
    strData += ",\"sffxskp\":" + $("#sffxskp", "#" + strDivP040202)[0].checked + "";
    strData += ",Records:[";

    //组表格里的数据
    for (var i = 0; i < arrIds.length; i++) {

        //当前行的对象
        var objTr = objTable.getRowData(arrIds[i]);

        //改行未编辑过退出
        if (objTr.flag == "") {
            continue;
        }

        //改行编辑过，但是空数据
        if (checkEmptyRow(objTr, "flag,mxguid,glsl,fpsl")) {
            if (strSaveTypeP040202 == "2" && strDeletHtmlP040202.indexOf(objTr.mxguid) == -1) {
                if (strDeletHtmlP040202 != null && strDeletHtmlP040202 != "") {
                    strDeletHtmlP040202 += ",{\"mxguid\":\"" + objTr.mxguid + "\",\"flag\":\"3\"}";
                }
                else {
                    strDeletHtmlP040202 = ",{\"mxguid\":\"" + objTr.mxguid + "\",\"flag\":\"3\"}";
                }
            }
            continue;
        }

        strData += "{";
        if (strSaveTypeP040202 != "1") {
            strData += "\"mxguid\":\"" + objTr.mxguid + "\",";
        }

        //商品代码，数量，单价，标志位
        strData += "\"spdm\":\"" + objTr.spdm + "\"";
        strData += ",\"sl\":\"" + objTr.sl + "\"";
        strData += ",\"dj\":\"" + objTr.dj + "\"";
        strData += ",\"flag\":\"" + objTr.flag + "\"";
        strData += "},";
    }

    //取出逗号
    if (strData.substring(strData.length - 1, strData.length) != "[") {
        strData = strData.substr(0, strData.length - 1);
    }

    //组要删除的部分
    if (strDeletHtmlP040202) {
        strData += strDeletHtmlP040202;
    }

    strData += "],"

    //制单人，备注
    strData += "\"czydm\":\"" + window.parent.objLoginInfo.code + "\"";
    strData += ",\"a2\":\"" + trim($("#a2", "#" + strDivP040202).val()) + "\"";
    strData += "}";

    var objResult;
    if (strSaveTypeP040202 == "1") {
        //新增
        objResult = ParseData(window.external.DoOptions(strTableP040202, "Add", strData));
    }
    else if (strSaveTypeP040202 == "2") {
        //修改
        objResult = ParseData(window.external.DoOptions(strTableP040202, "Edit", strData));
    }
    else if (strSaveTypeP040202 == "3") {
        //查看
        objResult = ParseData(window.external.DoOptions(strTableP040202, "Add", strData));
    }

    //数据库操作失败退出
    if (objResult.ReturnCode != "0") {
        window.parent.cihoAlert(objResult.MSG);
        return;
    }

    //保存新增
    if (save == "2") {

        //清楚原来的数据，重新添加空行
        $("#" + strTableP040202).clearGridData();
        strRecordsCountP040202 = 5;
        addEmptyRowsP040202();

        //添加删除列
        addCzHtmlP040202();

        //计算合计
        getTotalP040202();

        //清除数据
        $(":input", $("#" + strDivP040202)).val("");
        $("#khdm", "#" + strDivP040202).combobox('setValue', '');
        $("#kpdwdm", "#" + strDivP040202).combobox('setValue', '');

        $("#czydm", "#" + strDivP040202).val(window.parent.objLoginInfo.name);
        $("#djdate", "#" + strDivP040202).val(getNowDate());
        $("#sffxskp", "#" + strDivP040202).attr("checked", false);
        $("#djdate", "#" + strDivP040202).attr("disabled", false);
        $("#idMust", "#" + strDivP040202).empty();

    }
    else {
        strRecordsCountP040202 = null;
        cihoDlgClose(dialog);
    }

    //重新加载发票编号
    var strInvDwValue = $("#cmbInvoiceBhP0402").combobox("getValue");
    var objFpBh = ParseData(window.external.DoOptions(strTableP0402, "GetComboBoxData", "{}"));
    if (objFpBh != null && objFpBh.Records != "{}") {
        objFpBh.Records.unshift({ mc: "全部发票", dm: "", selected: true });
        $("#cmbInvoiceBhP0402").combobox("loadData", objFpBh.Records);
    }
    $("#cmbInvoiceBhP0402").combobox('setValue', strInvDwValue);


    //清除内存
    objTable = null;
    iRowP040202 = -1;
    iRowP040202 = -1;
    strSaveTypeP040202 = "1";
    strDeletHtmlP040202 = "";
    objRecordsP040202 = null;

    //重新加载数据
    searchDataClickP0402();

    //设定状态
    $("#" + strDivP040202 + "_divform").data("change", false);

}

//保存数据
function saveMyDataTp040202(dialog, save) {

    //验证单据
    if (checkFormP040202() == false) {
        return false;
    }

    //保存数据
    saveToDbP040202(dialog, save);
}

//计算合计
function getTotalP040202() {

    //table对象，行id
    var objTable = $("#" + strTableP040202);
    var arrIds = objTable.getDataIDs();

    //金额合计
    var strTotalJe = 0;

    //循环计算合计
    for (var i = 0; i < arrIds.length; i++) {
        var strJe = parseFloat(objTable.getCell(arrIds[i], "je"));
        if (!isNaN(strJe)) {
            strTotalJe += strJe;
        }

    }

    //给底部添加合计
    $("#" + strTableP040202).footerData("set", { rn: "合计", je: strTotalJe }, true);

    //释放内存
    objTable = null;
}

//不允许输入的特殊字符//特殊字符包括：'  "
function checkValidate1(e) {
        var v = "";
        if (window.event) {
            v = e.keyCode; //IE
        }
        else if (e.which) {//FirFox
            v = e.which;
        }
        if (v == 39 || v == 34) {//输入无效
            return false;
        }
}