/*************************
*功能：箱号批号登记
*创建人：张振华
*时间：2010-08-15
*备注：此时间是加注释时间
*************************/

var strDivP030101 = "divP030101";
var strTableP030101 = "Tp030101";
var strRecordsCountP030101; //表格的记录数
var iRowP0301 = -1; //行索引
var iColP0301 = -1; //列索引
var strDeletHtmlP030101 = "";   //删除的数据
var strOprateP030101 = "1";     //操作类型

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

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

}

//格式化日期
function formatterP030101Data(cellValue) {
    if (cellValue && checkDatePattern(cellValue)) {
        return formatDate(cellValue);
    }
    else {
        return "&nbsp;"
    }
}

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

//该变保存状态
function ChangeFlagP030101(rowId) {

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

    }
    else {
        objTable.setCell(rowId, "flag", "2");
    }

    objTable = null;
    dataChangeStateP030101(true);
}

//编辑单元格事件
function afterEditCell_P030101(rowId, cellname, value, iRow, iCol) {

    //行索引，列索引
    iRowP0301 = iRow;
    iColP0301 = iCol;

    //表格对象，单元格中的控件
    var objTable = $("#" + strTableP030101);
    var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
    switch (cellname) {
        case "sl":
            //退货单价
            item.autoNumeric({ mDec: window.parent.strCountPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
        case "ph":
            //批号
            item.keypress(function (e) {
                return checkValidate(e);
            }).focus(function () { this.select(); });
            break;
        case "xh":
            //批号
            item.keyup(function (e) {
                //输入除了数字的字符，自动替换成逗号
                if (checkNum(e) != true) {
                    var str = $(this).val();
                    if (/^,/.test(str)) { str = str.replace(/^,/g, ""); }
                    $(this).val(str.replace(/\D+/g, ','));
                }
            }).focus(function () { this.select(); });
            break;
        case "xq":
            //效期
            inputAndBindData(item.attr("id"), false, "#" + strTableP030101, ChangeFlagP030101(rowId));
            break;
    }

    //change事件
    item.change(function () { ChangeFlagP030101(rowId); });

    //释放内训
    item = null;
    objTable = null;
}

//保存单元格之后的事件
function afterSaveCell_P030101(rowId, cellname, value, iRow, iCol) {
    //debugger
    switch (cellname) {
        case "sl":
            getTotalP030101();
            break;
    }
}

//创建grid
function createGridP030101(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 getTotalP030101() {
    var objTable = $("#" + strTableP030101);
    var arrIds = objTable.getDataIDs();
    var strTotalSl = 0;

    for (var i = 0; i < arrIds.length; i++) {
        var strSl = parseFloat(objTable.getCell(arrIds[i], "sl"));
        if (!isNaN(strSl)) {
            strTotalSl += strSl;
        }
    }
    strTotalSl = parseFloat(strTotalSl).toFixed(window.parent.strCountPlace);
    $("#" + strTableP030101).footerData("set", { rn: "合计", sl: strTotalSl }, true);
    objTable = null;
}

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

//添加空行
function addEmptyRowP030101() {
    $("#" + strTableP030101).addRowData(++strRecordsCountP030101, { id: strRecordsCountP030101 });
    addCzHtmlP030101();
    resizeGridScroll(strTableP030101);
}

//浮动删除
function addCzHtmlP030101() {
    $("#" + strTableP030101 + " tr:visible", "#" + strDivP030101).hover(function () {
        var strButtonHtml = "";
        strButtonHtml += "<a style=\"color:red;text-decoration:none;cursor:pointer;\" onclick=\"deleteDataP030101(" + this.id + ");return false;\">删除</a> ";
        $("#" + strTableP030101).jqGrid("setCell", this.id, "cz", strButtonHtml);
    }, function () {
        $("#" + strTableP030101).jqGrid("setCell", this.id, "cz", "&nbsp;");
    });
}

//释放内存
function freeMemory_P030101() {
    strOprateP030101 = null;
    iRowP020102 = null;
    iColP020102 = null;
    strDeletHtmlP030101 = null;
}

//添加弹出层内容
function addContentP030101(strBh, strMxguid) {

    //config,药品,仓库
    var config = ParseData(window.external.DoOptions(strTableP030101, "GetTableConfig", "{}"));
    var objSp = getComboboxData("Tspxx");
    var objCk = getComboboxData("TCkxx");

    var i = 0;
    var strHtml = "";
    var Item;

    //获取数据
    var objRecordsP030101 = { Records: [] };
    if (strBh != "" && strMxguid != "") {
        objRecordsP030101 = ParseData(window.external.DoOptions(strTableP030101, 'GetList', '{"djbh":"' + strBh + '" ,"zbmxguid":"' + strMxguid + '"}'));
    }

    strHtml = "<ul>";
    for (i = 0; i < config.pageHeader.length; i++) {
        Item = config.pageHeader[i];
        if (Item.hidden == true) {
            continue;
        }
        if (Item.edittype == "text") {
            strHtml += "<li class='inp_70'>";
            strHtml += Item.xsmc + "：";
            strHtml += "<input type='text'  name='" + Item.index + "' ";
            strHtml += " value=''  ";
            strHtml += " id='" + Item.index + "'>";
            strHtml += "</li>";
        }
        else if (Item.edittype == "select") {
            strHtml += "<li>";
            strHtml += Item.xsmc + "：";
            strHtml += "<select name='" + Item.index + "' id='" + Item.index + "'";
            strHtml += " class='easyui-combobox' >";
            strHtml += "</select>";
            strHtml += "</li>";
        }
    }
    strHtml += "</ul>";
    strHtml += "<table id=" + strTableP030101 + "></table>";

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

    //药品
    $("#spdm", "#" + strDivP030101).combobox({
        width: _iWidth150,
        listWidth: _iWidth150,
        textField: "mc",
        valueField: "dm"
    });
    if (objSp != "{}") {
        $("#spdm", "#" + strDivP030101).combobox("loadData", objSp);
    }
    $("#spdm", "#" + strDivP030101).combobox('setText', objSelRowP0301.spmc);
    $("#spdm", "#" + strDivP030101).combobox('disable');

    //仓库
    $("#ckdm", "#" + strDivP030101).combobox({
        width: _iWidth150,
        listWidth: _iWidth150,
        textField: "mc",
        valueField: "dm"
    });
    if (objSp != "{}") {
        $("#ckdm", "#" + strDivP030101).combobox("loadData", objCk);
    }
    $("#ckdm", "#" + strDivP030101).combobox('setText', objSelRowP0301.ckmc);
    $("#ckdm", "#" + strDivP030101).combobox('disable');

    //单据日期
    $("#djdate", "#" + strDivP030101).attr("disabled", true);
    $("#djdate", "#" + strDivP030101).val(getNowDate());

    //加载表格,设置高度
    createGridP030101(strTableP030101, config.colNames, config.colModel);
    $("#" + strTableP030101).setGridHeight(141);

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

    //取表格
    var objTable = $("#" + strTableP030101);

    //设置属性
    objTable.setColProp("sl", { formatter: formatterP030101Count });
    objTable.setColProp("xq", { formatter: formatterP030101Data });
    objTable.setGridParam({ afterEditCell: afterEditCell_P030101 });
    objTable.setGridParam({ afterSaveCell: afterSaveCell_P030101 });

    //加载数据
    loadTreeData(strTableP030101, objRecordsP030101.Records);

    if (objRecordsP030101.Records == "{}") {
        objRecordsP030101.Records = [];
    }
    strRecordsCountP030101 = objRecordsP030101.Records.length > 5 ? objRecordsP030101.Records.length : (5 - objRecordsP030101.Records.length);

    //添加空行
    addEmptyRowsP030101();

    //计算合计
    getTotalP030101();

    //添加删除
    addCzHtmlP030101();

    //调整表格
    resizeGridScroll(strTableP030101);

    //移除保存新增按钮
    $("div .btn02").remove();
    $("div .btn03 a").css("margin-left", "-50px");

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

//弹出页
function showDialogP0301(strType) {
    try {

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

        //弹出层
        creatDiv_ShowDlgHaveTbl(strDivP030101, "批号箱号关联", false, true, strTableP030101, "700");

        //编号
        $("#idMust").append("NO:" + objSelRowP0301.djbh);

        //弹出层内容
        addContentP030101(objSelRowP0301.djbh, objSelRowP0301.zbmxguid);

    }
    catch (e) {
        proceError("P030101", e.ToString());
    }
}

//删除数据
function deleteDataP030101(rowId) {
    try {

        //保存时取消单元格编辑
        $("#" + strTableP030101).saveCell(iRowP0301, iColP0301);

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

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

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

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

                        $("#" + strTableP030101).delRowData(rowId);
                        dataChangeStateP030101(true);
                    }
                    else {
                        //新增的时候
                        $("#" + strTableP030101).delRowData(rowId);

                    }
                    //重新计算合计
                    getTotalP030101();
                    return;
                }
            });

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

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

//判断批号是否重复
function checkSamePh(index, strPh) {
    var objTable = $("#" + strTableP030101);
    var arrIds = objTable.getDataIDs();
    for (var i = 0; i < arrIds.length; i++) {
        var objTr = objTable.getRowData(arrIds[i]);
        if (i != index && objTr.ph == strPh) {
            return false;
        }
    }
    objTable = null;
}

//验证表单
function checkForm() {

    //常用变量定义
    var objTable = $("#" + strTableP030101);
    var arrIds = objTable.getDataIDs();
    var objTr;
    var alterMsg = "";

    //保存表格
    objTable.saveCell(iRowP0301, iColP0301);

    //药品总数量和输入数量比较
    var strSl = objTable.footerData('get').sl;

    //药品总数量不能大于出库数量和入库数量
    if (objSelRowP0301.rksl != "" && parseFloat(strSl) > parseFloat(objSelRowP0301.rksl)) {
        window.parent.cihoAlert(msg.other.ZslDyGlExtent);
        return false;
    }

    if (objSelRowP0301.cksl != "" && parseFloat(strSl) > parseFloat(objSelRowP0301.cksl)) {
        window.parent.cihoAlert(msg.other.ZslDyGlExtent);
        return false;
    }

    //循环表格验证
    for (var i = 0; i < arrIds.length; i++) {

        objTr = objTable.getRowData(arrIds[i]);
        if (objTr.flag == "") {
            continue;
        }
        if (checkEmptyRow(objTr, "flag,mxguid")) {
            if (objTr.mxguid != "" && strDeletHtmlP030101.indexOf(objTr.mxguid) == -1) {
                if (strDeletHtmlP030101 != null && strDeletHtmlP030101 != "") {
                    strDeletHtmlP030101 += ",{\"mxguid\":\"" + objTr.mxguid + "\",\"flag\":\"3\"}";
                }
                else {
                    strDeletHtmlP030101 = ",{\"mxguid\":\"" + objTr.mxguid + "\",\"flag\":\"3\"}";
                }
            }
            continue;
        }

        //验证数量
        if (objTr.sl == "") {
            alterMsg = msg.other.dnh + (i + 1) + msg.sz.yp.lnAmountEmp;
            window.parent.cihoAlert(alterMsg);
            return false;
        }

        //验证批号
        if (objTr.ph == "") {
            alterMsg = msg.other.dnh + (i + 1) + msg.other.phNoEmpty;
            window.parent.cihoAlert(alterMsg);
            return false;
        }

        //验证批号是否相同
        if (checkSamePh(i, objTr.ph) == false) {
            alterMsg = msg.other.dnh + (i + 2) + msg.other.SamePh;
            window.parent.cihoAlert(alterMsg);
            return false;
        }

        //验证日期格式
        if (objTr.xq != "" && checkDatePattern(objTr.xq) == false) {
            window.parent.cihoAlert(msg.dt.dtTypeErr);
            return false;
        }
    }

    //释放内存
    objTable = null;

}

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

    //验证数据
    if (checkForm() == false) {
        return;
    }

    //变量定义
    var objTable = $("#" + strTableP030101);
    var arrIds = objTable.getDataIDs();

    //组查询数据
    var strSaveHtml = "{";
    strSaveHtml += "\"zbmxguid\":\"" + objSelRowP0301.zbmxguid + "\",";
    strSaveHtml += "\"djbh\":\"" + objSelRowP0301.djbh + "\",";
    strSaveHtml += "\"djlx\":\"" + objSelRowP0301.djlx + "\",";
    strSaveHtml += "Records:["

    //组表格中数据
    for (var i = 0; i < arrIds.length; i++) {
        var objTr = $("#" + strTableP030101).getRowData(arrIds[i]);
        if (objTr.flag == "") {
            continue;
        }
        if (checkEmptyRow(objTr, "flag,mxguid")) {
            if (objTr.mxguid != "" && strDeletHtmlP030101.indexOf(objTr.mxguid) == -1) {
                if (strDeletHtmlP030101 != null && strDeletHtmlP030101 != "") {
                    strDeletHtmlP030101 += ",{\"mxguid\":\"" + objTr.mxguid + "\",\"flag\":\"3\"}";
                }
                else {
                    strDeletHtmlP030101 = ",{\"mxguid\":\"" + objTr.mxguid + "\",\"flag\":\"3\"}";
                }
            }
            continue;
        }
        strSaveHtml += "{";
        strSaveHtml += "\"sl\":\"" + objTr.sl + "\",";
        strSaveHtml += "\"ph\":\"" + objTr.ph + "\",";
        strSaveHtml += "\"xh\":\"" + objTr.xh + "\",";
        strSaveHtml += "\"xq\":\"" + objTr.xq + "\","
        strSaveHtml += "\"mxguid\":\"" + objTr.mxguid + "\",";
        strSaveHtml += "\"flag\":\"" + objTr.flag + "\"";
        strSaveHtml += "},";

    }

    //删除逗号
    if (strSaveHtml.substring(strSaveHtml.length - 1, strSaveHtml.length) != "[") {
        strSaveHtml = strSaveHtml.substr(0, strSaveHtml.length - 1);
    }

    //组删除部分
    if (strDeletHtmlP030101) {
        strSaveHtml += strDeletHtmlP030101;
    }
    strSaveHtml += "]}";

    //添加到数据库
    var objResult = ParseData(window.external.DoOptions(strTableP030101, 'Edit', strSaveHtml));

    //添加失败
    if (objResult.ReturnCode != "0") {
        window.parent.cihoAlert(objResult.MSG);
        return;
    }

    //添加成功之后
    cihoDlgClose(dialog);

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

    //释放内存
    objTable = null;
    strDeletHtmlP030101 = "";
    strRecordsCountP030101 = null;
    iRowP0301 = -1;
    iColP0301 = -1;
}

