//打开进项发票维护界面

function openWh(rowId) {
    try {
        var row = $("#" + strTableP0401).getRowData(rowId);
        var dlgId = strDivP040101, tbId = strTableP040101, state = row.djbh ? 2 : 1;    //如果存在单据编号，则说明是修改，否则为新增

        creatDiv_ShowDlgHaveTbl(dlgId, "进项发票", false, true, tbId, 750);             //创建弹出窗口
        createElements(tbId, dlgId);                                                   //创建表单元素
        initGridSetP040101(tbId, dlgId);                                                //为grid绑定事件
        initInputsProp(dlgId);                                                          //初始化表单元素的属性

        var $dlgId = $("#" + dlgId), $tbId = $("#" + tbId);
        $dlgId.data("state", state);
        var mylist = [];
        if (state == 1) {                                                                       //新增页头页脚默认值
            $dlgId.data("data", {});
            $("#djdate,#fprq", $dlgId).val(getNowDate());
            $("#czymc", $dlgId).attr("disabled", true).val(window.parent.objLoginInfo.name);
        } else if (state == 2) {                                                                //修改，页头页脚初始值
            var data = ParseData(window.external.DoOptions(tbId, "GetList", '{ "djbh": "' + row.djbh + '" }'));
            if (data && data.ReturnCode == 0) {

                $("#idMust", $dlgId).append('（' + row.zt + '）');
                $("#djdate", $dlgId).attr("disabled", true).val(data.djdate);

                //为供应商combobox赋值
                var $gys = $("#gysmc", $dlgId);
                $gys.combobox("setValue", data.gysdm);
                if ($gys.combobox("getText") == data.gysdm) {
                    $gys.combobox("setText", data.gysmc);
                }

                //为开票单位combobox赋值
                var $kpdw = $("#kpdwmc", $dlgId);
                $kpdw.combobox("setValue", data.kpdwdm);
                if ($kpdw.combobox("getText") == data.kpdwdm) {
                    $kpdw.combobox("setText", data.kpdwmc);
                }

                //为发票日期，发票编号、发票金额、制单人、备注赋值
                $("#fprq", $dlgId).val(data.fprq);
                $("#fpbh", $dlgId).val(escape(data.fpbh));
                $("#a1", $dlgId).val((data.a1 * 1).toFixed(window.parent.strMoneyPlace));
                $("#czymc", $dlgId).attr("disabled", true).val(data.czymc);
                $("#bz", $dlgId).val(escape(data.bz));

                if (data.sfzjgp == "True") { $("#sfzjgp", $dlgId).attr("checked", true) }
                if (data.Records instanceof Array) {
                    mylist = data.Records;
                }

                $dlgId.data("data", { djbh: row.djbh, gysdm: data.gysdm, gysmc: data.gysmc, kpdwdm: data.kpdwdm, kpdwmc: data.kpdwmc, czydm: data.czydm, czymc: data.czymc });

                $gys = $kpdw = null;
            } else {
                window.parent.cihoAlert(data.MSG, msgBox.dlgBtn.Ok);
            }
        }

        loadGridData(tbId, mylist);
        $dlgId.data("change", false);
        setTimeout('$("#fpbh","#"+strDivP040101).focus();', 100);

        $(".layoutpanel").css("z-index", "50000009");
        $dlgId = $tbId = null;
    } catch (e) { }
}

//查看进项发票维护
//查看
function showWh(rowId) {
    try {
        var row = $("#" + strTableP0401).getRowData(rowId);
        var tbId = strTableP040101, dlgId = strDivP040101;
        creatDiv_ShowDlgHaveTbl(dlgId, "进项发票", false, false, tbId, 750);                   //创建弹出窗口
        var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", "{}"));      // 向后台请求配置信息
        var header = createInputs(config.pageHeader);                                         // 根据头配置 生成表单元素 
        var footer = createInputs(config.pageFooter);                                         //根据脚信息   生成表单元素

        //将创建的元素添加到窗口中
        $("#" + dlgId + "_divform").append(header).append('<table id="' + tbId + '"></table>').append("<br/><br/><br/>" + footer);

        //创建jqgrid
        createDjGrid(tbId, config.colNames, config.colModel);
        $("table.ui-jqgrid-htable th:first", "#" + dlgId).text("序号");

        //设置jqgrid事件
        $("#" + tbId).setGridParam({ "afterEditCell": function (rowId, cellname, value, iRow, iCol) { $(this).restoreCell(iRow, iCol); return; } });

        //格式化jqgrid
        addColFormater(tbId);
        $("#" + tbId).setGridHeight(141);

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

        //设置单据时间、发票日期、开票单位、发票金额、备注的宽度
        $("#djdate,#fprq,#kpdwmc,#a1", $dlgId).parent().addClass("inp_70");
        $("#bz", $dlgId).parent().addClass("bz");

        var mylist = [];

        //去后台请求数据
        var s = ParseData(window.external.DoOptions(tbId, "GetList", '{ "djbh": "' + row.djbh + '" }'));
        if (s && s.ReturnCode == 0) {
            $("#idMust", $dlgId).append('（' + row.zt + '）');
            $("#djdate", $dlgId).attr("disabled", true).val(s.djdate);
            $("#gysmc,#kpdwmc", $dlgId).combobox();

            //为供应商、开票单位、发票日期、发票编号、制单人、备注、发票金额赋值
            $("#gysmc", $dlgId).combobox("setText", s.gysmc);
            $("#kpdwmc", $dlgId).combobox("setText", s.kpdwmc);
            $("#gysmc", $dlgId).combobox("disable");
            $("#kpdwmc", $dlgId).combobox("disable");

            $("#fprq", $dlgId).attr("disabled", true).val(s.fprq);
            $("#fpbh", $dlgId).attr("disabled", true).val(s.fpbh);

            $("#czymc", $dlgId).attr("disabled", true).val(s.czymc);
            $("#bz", $dlgId).attr("disabled", true).val(s.bz);
            $("#a1", $dlgId).attr("disabled", true).val((s.a1 * 1).toFixed(window.parent.strMoneyPlace));

            if (s.sfzjgp == "True") { $("#sfzjgp", $dlgId).attr("checked", true); }
            $("#sfzjgp", $dlgId).attr("disabled", true);
            if (s.Records instanceof Array) { mylist = s.Records; }
        } else {
            window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }

        //为jqgrid加载数据
        loadGridData(tbId, mylist);

        $dlgId.data("change", false);
        $dlgId = null;
    } 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);                                         //根据脚信息   生成表单元素

    //将生成的表单元素添加到dialog中
    $("#" + 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" });

    //创建jqgrid
    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; "/>');
    config = null;
}

//初始化grid事件
function initGridSetP040101(tbId, dlgId) {
    $("#" + tbId).setGridParam({
        "afterSaveCell": function (rowId, cellname, value) {//保存后要执行的事件（计算和）
            if (cellname == "sl" || cellname == "a2") {
                var ypNum = $(this).getCell(rowId, "sl");
                var ypPrice = $(this).getCell(rowId, "a2");
                if (/^\d+(\.\d+)?$/.test(ypNum) && /^\d+(\.\d+)?$/.test(ypPrice)) {
                    $(this).setCell(rowId, "je", ypNum * ypPrice);
                } else {
                    $(this).setCell(rowId, "je", null);
                }
                sumGridTotal(this.id);
            }
        },
        "afterEditCell": function (rowId, cellname, value, iRow, iCol) {
            try {
                cellX = iRow; cellY = iCol;
                var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
                switch (cellname) {
                    case "spmc":                //药品名称下拉框
                        item.combobox({ valueField: "dm", textField: "mc", width: _iWidth120 });

                        //为药品combobox加载数据
                        var yplist = getComboboxData("Tspxx");
                        yplist.push({ "mc": "<font color='red'>添加药品</font>", "dm": "-1" });
                        item.combobox("loadData", yplist);

                        //为药品combobox赋值
                        var ypdm = $(this).getCell(rowId, "spdm");
                        item.combobox("setValue", ypdm);
                        if (item.combobox("getText") == ypdm) {
                            item.combobox("setText", value);
                        }

                        item.combobox('focus');

                        //为药品combobox绑定事件
                        item.combobox({
                            onChange: function (newValue) {
                                var $tbId = $("#" + tbId);
                                var dlgId = strDivP040101;
                                if (newValue) {
                                    $tbId.setCell(rowId, "spdm", newValue);
                                    var gysdm = $("#gysmc", "#" + dlgId).combobox("getValue") ? $("#gysmc", "#" + dlgId).combobox("getValue") : $("#" + dlgId).data("data").gysdm;

                                    if (gysdm && newValue) {                             //如果存在供应商代码并且没有单价信息，就去请求跟踪信息
                                        var gzdj = ParseData(window.external.DoOptions(strTableP040101, "DoOthers", '{"gysdm":"' + gysdm + '","spdm":"' + newValue + '","fb":"2"}'));
                                        if (gzdj.ReturnCode == 0 && /^\d+(\.\d+)?$/.test(gzdj.a1)) {
                                            $tbId.setCell(rowId, "a2", gzdj.a1);

                                            var ypNum = $tbId.getCell(rowId, "sl");
                                            var ypPrice = $tbId.getCell(rowId, "a2");
                                            if (/^\d+(\.\d+)?$/.test(ypNum) && /^\d+(\.\d+)?$/.test(ypPrice)) {
                                                $tbId.setCell(rowId, "je", ypNum * ypPrice);
                                            } else {
                                                $tbId.setCell(rowId, "je", null);
                                            }
                                            sumGridTotal(tbId);
                                        }
                                    }
                                } else {
                                    $tbId.setCell(rowId, "spdm", null);
                                }
                                changeZt(tbId, rowId);
                            },
                            onSelect: function (item) {
                                if (item.dm == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "药品", table: "Tflxx" }, { model: "Tspxx", jquery: $(this) });
                                    $(this).combobox("setValue", "");
                                }
                            },
                            afterChange: function (newValue, newText) {
                                if (newValue == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "药品", table: "Tflxx" }, { model: "Tspxx", jquery: $(this) });
                                    ciho.showTypeDialog();
                                    $(this).combobox("setValue", "");
                                }
                            }
                        });
                        break;
                    case "sl":
                        item.val(value);
                        item.autoNumeric({ mDec: window.parent.strCountPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                        item.change(function () { changeZt(tbId, rowId); });
                        break;
                    case "a2":
                        item.val(value);
                        item.autoNumeric({ mDec: window.parent.strPricePlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                        item.change(function () { changeZt(tbId, rowId); });
                        break;
                }
                $(".layoutpanel").css("z-index", "50000009");
                item = null;
            } catch (e) { }
        }
    });

    //格式化jqgrid
    addColFormater(tbId);

    //为jqgrid绑定删除事件
    bindDelEvent(tbId);

    //为jqgrid保存一个删除信息的数组
    $("#" + tbId).data("records", []);
    $("#" + tbId).data("data", {});
    $("#" + tbId).setGridHeight(141);
}

//为操作按钮注册事件
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);
        }
    });
}

//创建表单元素
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 != "bz") {
                    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>";
            } else if (Item.edittype == "checkbox") {
                strForm += "<li class='unline' >";
                strForm += "<input type='checkbox'name='" + Item.index + "' id='" + Item.index + "'/>";
                strForm += Item.xsmc;
                strForm += "</li>";
            }
        }
    }
    strForm += "</ul>";
    return strForm;
}

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

        //验证时间
        var djdate = $("#djdate", $dlgId).val();
        if (!djdate) {
            window.parent.cihoAlert("请输入收票日期！", msgBox.dlgBtn.Ok, function () {
                $("#djdate", $dlgId).focus();
                $tbId = $dlgId = null;
            });
            return false;
        } else {
            var djdt = djdate.replace(/\-/g, "/");
            if (djdt < window.top._startDate) {
                window.parent.cihoAlert(msg.other.sprqExtent, msgBox.dlgBtn.Ok, function () {
                    $("#djdate", $dlgId).focus();
                    $tbId = $dlgId = null;
                });
                return false;
            }
        }

        var data = $("#" + dlgId).data("data");
        //验证供应商
        var $gys = $("#gysmc", $dlgId);
        var gysdm = $gys.combobox("getValue");
        var gysmc = $gys.combobox("getText");
        if (!gysdm && gysmc != data.gysmc) {
            window.parent.cihoAlert(msg.sz.gys.nameEmp, msgBox.dlgBtn.Ok, function () {
                $gys.combobox("focus");
                $tbId = $dlgId = data = $gys = null;
            });
            return false;
        }

        //发票日期
        var fprq = $("#fprq", $dlgId).val();
        if (!fprq) {
            window.parent.cihoAlert("请输入发票日期！", msgBox.dlgBtn.Ok, function () {
                $("#fprq", $dlgId).focus();
                $tbId = $dlgId = data = $gys = null;
            });
            return false;
        } else {
            var djdt = fprq.replace(/-/g, "/");
            if (djdt < window.top._startDate) {
                window.parent.cihoAlert(msg.other.fprqExtent, msgBox.dlgBtn.Ok, function () {
                    $("#fprq", $dlgId).select();
                    $tbId = $dlgId = data = $gys = null;
                });
                return false;
            }
        }

        //发票编号
        var fpbh = $.trim($("#fpbh", $dlgId).val());
        if (!fpbh) {
            window.parent.cihoAlert("发票编号不能为空！", msgBox.dlgBtn.Ok, function () {
                $("#fpbh", $dlgId).focus();
                $tbId = $dlgId = data = $gys = null;
            });
            return false;
        }

        //验证收票单位
        var $kpdw = $("#kpdwmc", $dlgId);
        var kpdwdm = $kpdw.combobox("getValue");
        var kpdwmc = $kpdw.combobox("getText");
        if (!kpdwdm && kpdwmc != data.kpdwmc) {
            window.parent.cihoAlert("收票单位为空或不存在！", msgBox.dlgBtn.Ok, function () {
                $kpdw.combobox("focus");
                $tbId = $dlgId = data = $gys = $kpdw = null;
            });
            return false;
        }

        //发票金额
        var fpje = $.trim($("#a1", $dlgId).val());
        if (fpje != amount) {
            window.parent.cihoAlert("开票金额与合计不一致！", msgBox.dlgBtn.Ok, function () {
                $("#a1", $dlgId).focus();
                $tbId = $dlgId = data = $gys = $kpdw = null;
            });
            return false;
        }

        var vCols = $tbId.data("vCols");
        var ids = $tbId.getDataIDs();
        for (var i = 0, len = ids.length; i < len; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.flag && !isRowEmpty(item, vCols)) {
                if (!item.spdm) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.yp.lnEmpOrNotExit, msgBox.dlgBtn.Ok);                    //alert("请选择第【" + (i + 1) + "】行的药品！");
                    $tbId = $dlgId = $gys = $kpdw = null;
                    return false;
                }
                if (item.sl * 1 <= 0) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.yp.lnAmountEmp, msgBox.dlgBtn.Ok);                    //alert("请输入第【" + (i + 1) + "】行的药品数量！")
                    $tbId = $dlgId = $gys = $kpdw = null;
                    return false;
                }
                if (item.a2 * 1 <= 0) {
                    //window.parent.cihoAlert(msg.other.dnh + (i + 1) + "】行的药品单价！", msgBox.dlgBtn.Ok);                    //alert("请输入第【" + (i + 1) + "】行的药品数量！");
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.yp.lnPriceNOtZeroOrEmp, msgBox.dlgBtn.Ok);
                    $tbId = $dlgId = $gys = $kpdw = null;
                    return false;
                }
            }
        }
        $tbId = $dlgId = $gys = $kpdw = null;
        return true;
    } catch (e) { }
}

//保存
function saveP040101(tbId, afterSave, dlgId) {
    try {
        var $tbId = $("#" + tbId), $dlgId = $("#" + dlgId);
        $tbId.saveCell(cellX, cellY);

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

        //组织grid里面的数据
        var recordCount = 0, records = $tbId.data("records");
        var ids = $tbId.getDataIDs();
        var vCols = $tbId.data("vCols");
        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.a2 + '","flag":"' + item.flag + '"}';
                    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 data = $dlgId.data("data");

        //组织页头和页脚
        var inputs = [];
        //日期
        inputs.push('"djdate":"' + $("#djdate", $dlgId).val() + '"');

        //供应商
        var $gys = $("#gysmc", $dlgId);
        var gysdm = $gys.combobox("getValue");
        var gysmc = $gys.combobox("getText");
        if (gysdm) {
            inputs.push('"gysdm":"' + gysdm + '"');
        } else if (gysmc == data.gysmc) {
            inputs.push('"gysdm":"' + data.gysdm + '"');
        }

        //开票单位
        var $kpdw = $("#kpdwmc", $dlgId);
        var kpdwdm = $kpdw.combobox("getValue");
        var kpdwmc = $kpdw.combobox("getText");
        if (kpdwdm) {
            inputs.push('"kpdwdm":"' + kpdwdm + '"');
        } else if (kpdwmc == data.kpdwmc) {
            inputs.push('"kpdwdm":"' + data.kpdwdm + '"');
        }

        //发票编号
        inputs.push('"fpbh":"' + trim($("#fpbh", $dlgId).val()) + '"');
        //发票日期
        inputs.push('"fprq":"' + $("#fprq", $dlgId).val() + '"');
        //金额
        inputs.push('"a1":"' + $("#a1", $dlgId).val() + '"');
        //直接购票
        inputs.push('"sfzjgp":"' + $("#sfzjgp", $dlgId)[0].checked + '"');

        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('"a2":"' + trim($("#bz", $dlgId).val()) + '"');
        var jsonStr = '{' + inputs + ',"Records":[' + rows.concat(records) + ']}';

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

        if (s.ReturnCode == 0) {                            //添加成功！
            refreshFPBH(fpbh);
            if (afterSave == 2) {                           //保存新增
                resetGrid(tbId, dlgId);

            } else {                                        //保存退出
                cihoDlgClose(dlgId);
            }
            searchDataClick_P0401(0);
            resizeGridScroll(strTableP0401);
        }
        else {
            window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }
        ids = inputs = null;
    } catch (e) { }
}

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

        $("#idMust", $dlgId).empty();
        $("#kpdwmc", $dlgId).combobox("enable");
        $("#kpdwmc,#gysmc", $dlgId).combobox("setValue", "");

        $("#a1,#fpbh,#bz", $dlgId).val("");
        $("#djdate,#fprq,#dkdate", $dlgId).val(getNowDate());

        $("#dkdate,#djdate", $dlgId).attr("disabled", false);
        $("#czymc", $dlgId).attr("disabled", true).val(window.parent.objLoginInfo.name);
        $("#sfzjgp", $dlgId).attr("checked", false);
        $dlgId.data("change", false);
        $dlgId.data("state", 1);
        $dlgId.data("data", {});

        if (tbId == strTableP040101) {
            setTimeout('$("#fpbh","#"+strDivP040101).focus();', 100);
        }
        iseditable = true;
        $dlgId = null;
    } catch (e) { }
}

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