/*--------------------------文档信息-------------------------------------------
///功能：      预提管理——预提余额结转单
///创建人：  王群
///创建时间：2011年05月31日
///修改人：  --------------
///修改时间：--------------
///详细说明：--------------
-----------------------------------------------------------------------------*/
var strTableP050605 = "Tp050605";           //表格的ID
var strDlgIdP050605 = "divP050501";        //弹出层的ID
var bSvaeSignP050605 = 1;                        //保存的标志位
var objRetRecordP050605 = {};                  //修改时保存要修改的记录
var objconfigP050605 = {};                        //列配置
var iRowP050605 = 0;                                //当前选中单元格的row索引
var iColP050605 = 0;                                 //当前选中单元格的col索引
var iRowIdP050605 = 0;                            //当前选中单元格的rowid
var roleRecords = {};                                 //combobox的数据

//在jqGrid中自定义下拉框
//创建select表单元素
function my_inputP050605(value, options) {
    return $('<select name="' + options.name + '" id="' + options.id + ' name="' + options.id + '""></select>').addClass("easyui-combobox");
}

//保存选中的值
function my_valueP050605(ele) {
    return ele.combobox('getText');
}

//给表格中select控件转化成自定义的形式
function userdefined_P0050605() {
    //设置属性custom:绑定combobox：原规则
    $("#" + strTableP050605).setColProp("oldgzguid", { edittype: "custom" });
    $("#" + strTableP050605).setColProp("oldgzguid", { editoptions: { custom_element: my_inputP050605, custom_value: my_valueP050605} });
    //新规则
    $("#" + strTableP050605).setColProp("newgzguid", { edittype: "custom" });
    $("#" + strTableP050605).setColProp("newgzguid", { editoptions: { custom_element: my_inputP050605, custom_value: my_valueP050605} });
    //编辑状态，绑定事件
    $("#" + strTableP050605).setGridParam({ afterEditCell: afterEditCellP050605 });
    //格式化表中的数据
    $("#" + strTableP050605).setColProp("a1", { formatter: formatterP050605Money });
    //给转账日期绑定日期控件
    inputAndBindData("djdate", false, "#" + strDlgIdP050605, function () { $("#" + strDlgIdP050605 + "_divform").data("change", true); });
}

/*-----------------------------------------------------------------------------
//功能：点击添加按钮，弹出对话框
//参数：
//strType:1：添加
//2：修改
//strTableP050605 表名
-----------------------------------------------------------------------------*/
function showDialog_P050605(strType) {
    try {
        //获取规则的combobox值
        roleRecords = ParseData(window.external.DoOptions(strTableP050605, "GetComboBoxData", "{}")).Records;

        //清空弹出窗口内容
        $("#" + strDlgIdP050605).empty();

        //添加
        if (strType == "1") {
            //值为1，插入数据；值为2，更新数据
            bSvaeSignP050605 = "1";                 //初次保存insert数据
        }
        //修改
        else if (strType == "2") {
            bSvaeSignP050605 = "2";
        }
        //创建弹出窗口dialog
        creatDiv_ShowDlgHaveTbl(strDlgIdP050605, "预提余额结转单", false, true, strTableP050605, "700");

        //获得jqGrid的列名和属性
        objconfigP050605 = ParseData(window.external.DoOptions(strTableP050605, 'GetTableConfig', '{}'));

        if (!objconfigP050605) {
            window.parent.cihoAlert(msg.cg.LineFail);        //"列配置取得失败！"
            return;
        }

        //添加表单元素到窗口中
        tableFormP050605(strType);

        //创建表格
        createGridP050605(strTableP050605, objconfigP050605.colNames, objconfigP050605.colModel);

        //给表格中select控件转化成自定义的形式
        userdefined_P0050605();
        $("#a2", "#" + strDlgIdP050605).focus();                //给备注设置焦点
        //添加
        if ("1" == strType) {
            //调整日期,默认当前日期
            var nowData = getNowDate();
            $("#djdate", $("#" + strDlgIdP050605 + "_divform")).val(nowData);

            //加载空记录
            $("#" + strTableP050605).addRowData(1, {});
            nowData = null;
        }
        //修改
        else if ("2" == strType) {
            //设定单据的原始值
            setDjValueP050605();
            iRowIdP050605 = $("#" + strTableP050605).jqGrid("getDataIDs")[0];
        }

        //设定data change 为false
        dataChangeState(false);

        setTimeout(function () { $("#a2", "#" + strDlgIdP050605).focus(); }, 100);
    } catch (e) { }
}

//创建表单
function tableFormP050605() {
    //获取列配置
    var strPageHeader = objconfigP050605.pageHeader;
    var strpageFooter = objconfigP050605.pageFooter;
    //创建页头
    var pageHead = "<ul>";
    for (var i = 0; i < strPageHeader.length; i++) {
        pageHead += "<li>";
        pageHead += strPageHeader[i]["xsmc"] + "：";
        pageHead += "<input id='" + strPageHeader[i]["index"] + "' name='" + strPageHeader[i]["name"] + "' type='text'  maxlength='50'";
        pageHead += " onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>"; //限制输入，粘贴特殊字符
        pageHead += "</li>";
    }
    pageHead += "</ul>";
    //创建表格
    $("#" + strDlgIdP050605 + "_divform").append(pageHead);
    var tableP050605 = "<table id='Tp050605'><table>";
    $("#" + strDlgIdP050605 + "_divform").append(tableP050605);
    //创建页尾
    var pageFoot = "<ul>";
    for (var i = 0; i < strpageFooter.length; i++) {
        if (strpageFooter[i]["name"] == "czymc") {
            continue;
        }
        if (strpageFooter[i]["name"] == "a2") {
            pageFoot += "<li class='bz'>";
            pageFoot += strpageFooter[i]["xsmc"] + "：";
            pageFoot += "<input id='" + strpageFooter[i]["index"] + "' name='" + strpageFooter[i]["name"] + "' type='text' ";
            pageFoot += " onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>"; //限制输入，粘贴特殊字符
            pageFoot += "</li>";
        }
        else {
            pageFoot += "<li class='inp_70'>";
            pageFoot += strpageFooter[i]["xsmc"] + "：";
            pageFoot += "<input id='" + strpageFooter[i]["index"] + "' name='" + strpageFooter[i]["name"] + "' type='text'  maxlength='50'";
            pageFoot += " onkeypress='return checkValidate(event)' onpaste='return validatePaste()'/>"; //限制输入，粘贴特殊字符
            pageFoot += "</li>";
        }
    }
    pageFoot += "</ul>";
    $("#" + strDlgIdP050605 + "_divform").append(pageFoot);

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

    //设定状态
    $(":input[name]", $("#" + strDlgIdP050605 + "_divform")).change(function () {
        dataChangeState(true);
    });
}

//修改时，设定单据的原值
//function setDjValueP050605() {
//        var strDjbh = $("#" + strTableP0505).getCell(strSelRowIDP0505, "djbh");
//    //选中行ID；
//        objRetRecordP050605 = ParseData(window.external.DoOptions(strTableP050605, 'GetList', "{'djbh':'" + strDjbh + "'}"));
//    objRetRecordP050605 = ParseData(window.external.DoOptions(strTableP050605, 'GetList', "{'djbh':'YTJZ-20110714-001'}"));
//    if (!objRetRecordP050605) {
//        //"DB操作失败！"
//        window.parent.cihoAlert(msg.other.dbOprateErr);
//        return;
//    }
//    else {
//        if (objRetRecordP050605.Records == "{}") {
//            //数据为空
//            window.parent.cihoAlert(msg.other.dataEmp);
//            return;
//        }
//        else {
//            //加载数据
//            $("#" + strTableP050605).setColProp("a1", { formatter: formatMoneyPlace });
//            //填充表格
//            loadTreeData(strTableP050605, objRetRecordP050605.Records);
//        }
//    }
//    //加载资金转账单编号
//    $("#idMust", $("#" + strDlgIdP050605)).append("NO:" + objRetRecordP050605.Records[0].djbh);
//    //转账日期
//    $("#djdate", $("#" + strDlgIdP050605 + "_divform")).val(objRetRecordP050605.Records[0].djdate);
//    $("#czydm", $("#" + strDlgIdP050605 + "_divform")).val(objRetRecordP050605.Records[0]["czymc"]);
//    $("#a2", $("#" + strDlgIdP050605 + "_divform")).val(escape(objRetRecordP050605.Records[0].a2));
//    //释放内存
//    strDjbh = null;
//}

/*----------------------------------------------------
功能：创建一个jqGrid表格
******strTableID：表格的ID
******objColNames：表格的列名
******objColModel：表格的列配
-----------------------------------------------------*/
function createGridP050605(strTableID, objColNames, objColModel) {
    $("#" + strTableID).jqGrid({
        datatype: "local",
        colNames: objColNames,
        colModel: objColModel,
        data: [],
        rownumbers: true,
        rowNum: 9999,
        sortname: "id",
        autowidth: true,
        width: 600,
        cellEdit: true,
        cellsubmit: "clientArray",
        gridview: true
    });
    //调整表格的高度
    $("#" + strTableID).setGridHeight(47);
    //调整表格的列宽度
    resizeGridScroll(strTableID);
    //增加表头‘序号’列
    $("#" + strTableID).setLabel("rn", "序号");
}

//编辑状态，设置单元格属性
function afterEditCellP050605(rowId, cellname, value, iRow, iCol) {
    iRowIdP050605 = rowId;          //把当前的行ID传给全局变量
    iRowP050605 = iRow;             //把当前的行索引传给全局变量
    iColP050605 = iCol;                 //把当前的列索引传给全局变量

    var item = $("#" + rowId + " :input[name='" + cellname + "']", this);        //存放表格中所有的input对象

    switch (cellname) {
        case "oldgzguid":
            item.combobox({
                width: _iWidth100,
                listWidth: _iWidth100,
                valueField: "gzguid",
                textField: "gzname",
                editable: true
            });
            item.combobox("loadData", roleRecords == "{}" ? [] : roleRecords);        //加载数据

            item.combobox("setValue", $(this).getCell(rowId, "oldRoledm"));            //设定选中值
            if (item.combobox("getText") != "" && item.combobox("getText") == $(this).getCell(rowId, "oldRoledm")) {
                item.combobox('setText', objRetRecord.Records[0]["oldgzguid"]);
            }
            item.combobox({
                onChange: function (newValue, oldValue) {
                    if (newValue != undefined) {
                        $("#" + strTableP050605).setCell(rowId, "oldRoledm", newValue);
                    }
                    else {
                        //原规则为空或者不存在
                        $("#" + strTableP050605).setCell(rowId, "oldRoledm", "&nbsp;");
                    }
                    //修改Data change状态
                    dataChangeState(true);
                },
                onSelect: function (Record) {
                    if (Record.jsrdm != undefined) {
                        //点击旧规则时自动的带出旧规则经手人
                        $("#" + strTableP050605).setCell(rowId, "oldjsrmc", Record.oldjsrmc);
                    }
                },
                enterDown: function () {
                    for (var i = 0; i < roleRecords.length; i++) {
                        if (item.combobox("getValue") == roleRecords[i].gzguid) {
                            //按回车旧规则时自动的带出旧规则经手人
                            $("#" + strTableP050605).setCell(rowId, "oldjsrmc", roleRecords[i].oldjsrmc);
                        }
                    }
                }
            });
            break;
        case "newgzguid":
            item.combobox({
                width: _iWidth100,
                listWidth: _iWidth100,
                valueField: "gzguid",
                textField: "gzname",
                editable: true
            });

            item.combobox("loadData", roleRecords == "{}" ? [] : roleRecords);      //加载数据

            item.combobox("setValue", $(this).getCell(rowId, "newRoledm"));        //设定选中值
            if (item.combobox("getText") != "" && item.combobox("getText") == $(this).getCell(rowId, "newRoledm")) {
                item.combobox('setText', objRetRecord.Records[0]["newgzguid"]);
            }
            item.combobox({
                onChange: function (newValue, oldValue) {
                    if (newValue != undefined) {
                        $("#" + strTableP050605).setCell(rowId, "newRoledm", newValue);
                    }
                    else {
                        //新规则为空或者不存在
                        $("#" + strTableP050605).setCell(rowId, "newRoledm", "&nbsp;");
                    }
                    //修改Data change状态
                    dataChangeState(true);
                },
                onSelect: function (Record) {
                    if (Record.jsrdm != undefined) {
                        //点击新规则时自动带出新规则的经手人
                        $("#" + strTableP050605).setCell(rowId, "newjsrmc", Record.oldjsrmc);
                    }
                },
                enterDown: function () {
                    for (var i = 0; i < roleRecords.length; i++) {
                        if (item.combobox("getValue") == roleRecords[i].gzguid) {
                            //按回车旧规则时自动的带出旧规则经手人
                            $("#" + strTableP050605).setCell(rowId, "newjsrmc", roleRecords[i].oldjsrmc);
                        }
                    }
                }
            });
            break;
        case "a1":
            item.change(function () { dataChangeState(true) });             //流动金额
            item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
            break;
    }

    item.combobox('focus');         //给选中的combobox设定获得焦点。
    $(".layoutpanel").css("z-index", "50000009");
}

//保存的方法
function saveDataP050605(strType) {
    try {
        var strRecordP050605 = checkDataValidateP050605();      //数据有效性验证,组织要保存的数据
        var objRetP050605 = {};                         //用于存放从后台返回的信息
        if (!strRecordP050605) {                        //录入数据不完整;
            return;
        }

        if (bSvaeSignP050605 == "1") {                  //添加
            objRetP050605 = ParseData(window.external.DoOptions(strTableP050605, 'Add', strRecordP050605));
        }
        else {                                                              //修改
            objRetP050605 = ParseData(window.external.DoOptions(strTableP050605, 'Edit', strRecordP050605));
        }
        if (!objRetP050605) {                                       //"DB操作失败!"
            window.parent.cihoAlert(msg.other.dbOprateErr);
            return;
        }

        if ("0" == objRetP050605.ReturnCode) {          //操作成功
            //重新加载管理画面数据
            loadGridDataP0505();
            $("#idMust", $("#" + strDlgIdP050605)).empty();

            if (strType == "2") {                                       //保存新增          
                bSvaeSignP050605 = "1";                         //保存标志为设置为添加

                $(":input[name]", $("#" + strDlgIdP050605 + "_divform")).val("");       //清空当前窗口数据

                $("#" + strDlgIdP050605 + "_pop_box_top").empty();      //清除单据编号

                $("#djdate", $("#" + strDlgIdP050605 + "_divform")).val(getNowDate());      //转账日期
                $("#djdate", $("#" + strDlgIdP050605 + "_divform")).attr("disabled", false);

                $("#czydm", $("#" + strDlgIdP050605 + "_divform")).val(window.parent.objLoginInfo.name);    //制单人
                $("#a2", "#" + strDlgIdP050605).focus();                    //给备注设置上焦点
                //清空表格中的元素
                $("#" + strTableP050605).jqGrid("clearGridData");
                //加载空记录
                $("#" + strTableP050605).addRowData(1, {});
                //表单元素置为未修改
                dataChangeState(false);
                setTimeout(function () { $("#a2", "#" + strDlgIdP050605).focus(); }, 100);
            }

            else {      //保存退出/关闭
                cihoDlgClose(strDlgIdP050605);
            }
        }

        else {      //操作失败，弹出提示消息
            window.parent.cihoAlert(msg.save.saveFail);
        }
        //内存释放区域
        strRecordP050605 = null;
        objRetP050605 = null;
    } catch (e) { }
}

//验证数据有效性
function checkDataValidateP050605() {
    //取消表格中的数据的编辑状态，保存数据
    $("#" + strTableP050605).saveCell(iRowP050605, iColP050605);

    var arrListP050605 = "";                                //组织要保存的数据
    var strTzdate = trim($("#djdate", $("#" + strDlgIdP050605 + "_divform")).val());        //存放单据中当前的日期

    if (!strTzdate) {                                            // 调整日期不能为空！
        window.parent.cihoAlert(msg.cw.tzDataEmp, null, function () { $("#djdate", $("#" + strDlgIdP050605 + "_divform")).focus(); });
        return;
    }
    //验证日期的有效期是不是在指定范围内
    if ((strTzdate.replace(/-/g, "/")) < (window.parent._startDate.replace(/-/g, "/"))) {
        window.parent.cihoAlert(msg.other.djrqExtent, null, function () { $("#djdate", $("#" + strDlgIdP050605 + "_divform")).focus(); });
        return;
    }
    if (bSvaeSignP050605 == "1") {          //新增时制单人

        arrListP050605 += "\"czydm\":\"" + window.parent.objLoginInfo.code + "\",";
    }
    else {                                                  //修改时制单人
        arrListP050605 += "\"czydm\":\"" + objRetRecordP050605.Records[0]["czydm"] + "\",";
    }

    //备注
    arrListP050605 += "\"a2\":\"" + trim($("#a2", $("#" + strDlgIdP050605 + "_divform")).val()) + "\"";
    var strOldRole = $("#" + strTableP050605).getCell(iRowIdP050605, "oldRoledm");
    if (!strOldRole) {                              //原规则为空或者不存在！
        window.parent.cihoAlert(msg.cw.oldGzEmp);
        return;
    }
    var strNewRole = $("#" + strTableP050605).getCell(iRowIdP050605, "newRoledm");
    if (!strNewRole) {                           //新规则为空或者不存在！"
        window.parent.cihoAlert(msg.cw.newGzEmp);
        return;
    }
    if (strOldRole == strNewRole) {  //原规则和新规则重名了,请重新选择！
        window.parent.cihoAlert(msg.cw.sameGz);
        return;
    }
    //获得表格的数据
    var strTzje = $("#" + strTableP050605).getCell(iRowIdP050605, "a1");
    if (!strTzje) {                              //"调整金额不能为空！"
        window.parent.cihoAlert(msg.cw.tzMoneyEmp);
        return;
    }
    var strRecord = "{\"Records\":";
    strRecord += "[{";
    if (bSvaeSignP050605 == "2") {
        strRecord += "\"a1\":\"" + strTzje + "\"";
        strRecord += ",\"oldgzguid\":\"" + strOldRole + "\"";
        strRecord += ",\"newgzguid\":\"" + strNewRole + "\"";
        strRecord += ",\"djdate\":\"" + strTzdate + "\"";
        strRecord += "," + arrListP050605 + "}]";
        strRecord += ",\"djbh\":\"";
        strRecord += objRetRecordP050605.Records[0]["djbh"] + "\"";
        strRecord += "}";
    }
    if (bSvaeSignP050605 == "1") {
        strRecord += "\"a1\":\"" + strTzje + "\"";
        strRecord += ",\"oldgzguid\":\"" + strOldRole + "\"";
        strRecord += ",\"newgzguid\":\"" + strNewRole + "\"";
        strRecord += ",\"djbh\":\"\"";
        strRecord += ",\"djtypebh\":\"\"";
        strRecord += ",\"djdate\":\"" + strTzdate + "\"";
        strRecord += "," + arrListP050605 + "}]";
        strRecord += ",\"djdate\":\"" + strTzdate + "\"";
        strRecord += "}";
    }
    return strRecord;
    //释放内存
    arrListP050605 = null;
    strOldRole = null;
    strNewRole = null;
    strTzje = null;
}

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

//监听数据变化的标志位
function dataChangeState(bState) {
    $("#" + strDlgIdP050605 + "_divform").data("change", bState);
}