var searchParam = {};
var cellX, cellY, records = [], alterdata = {};
var bLoadComplete = false;

function pageLoad_P0507() {
    try {
        initInputsP0507();
        var config = ParseData(window.external.DoOptions(strTableP0507, "GetTableConfig", "{}"));
        createGrid(strTableP0507, config.colNames, config.colModel, [], null, null, true, alterRowDataP0507);
        bindGridEventP0507();
        $("#" + strTableP0507).setColProp("a1", { formatter: formatMoneyPlace });
        createPage(strPageP0507, strTableP0507);
        resizeGrid(strTableP0507, true, true);
        searchDataClick_P0507(1);
    } catch (e) { }
}

//初始化管理界面的表单元素
function initInputsP0507() {
    $("#sjtype,#fykmmc,#jsrdm,#ytdx").combobox();
    addArrowClass();

    //为起始时间和结束时间绑定日期控件
    inputAndBindData("sdate", false, "", dateChange);
    inputAndBindData("edate", false, "", dateChange);

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

    //初始化费用科目combobox并加载数据
    $("#fykmmc").combobox({                           //费用科目
        width: _iWidth100,
        listWidth: _iWidth100,
        valueField: "kmdm",
        textField: "mc",
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "费用科目") {
                $(this).combobox("setText", "");
            }
        }
    });
    var kmlist = ParseData(window.external.DoOptions(strTableP0507, "GetComboBoxData", '{"flag":"1"}'));

    if (kmlist.ReturnCode == 0 && kmlist.Records instanceof Array) {
        kmlist.Records.unshift({ "kmdm": "", "mc": "费用科目" });
        $("#fykmmc").combobox("loadData", kmlist.Records);
    }

    //初始化预提对combobox并加载数据
    $("#ytdx").combobox({             //预提对象
        width: _iWidth150,
        listWidth: _iWidth150,
        valueField: "ytdx",
        textField: "mc",
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "预提对象") {
                $(this).combobox("setText", "");
            }
        }
    });
    var ytlist = ParseData(window.external.DoOptions(strTableP0507, "GetComboBoxData", '{"flag":"2"}'));
    if (ytlist.ReturnCode == 0 && ytlist.Records instanceof Array) {
        ytlist.Records.unshift({ "ytdx": "", "mc": "预提对象" });
        $("#ytdx").combobox("loadData", ytlist.Records);
    }

    //初始化费用经手人combobox并加载数据
    $("#jsrdm").combobox({                                             //费用经手人
        width: _iWidth100,
        listWidth: _iWidth100,
        valueField: "zydm",
        textField: "mc",
        onblur: function () {
            if ($(this).combobox("getText") == "") {
                $(this).combobox("setValue", "");
            }
        },
        onfocus: function () {
            if ($(this).combobox("getText") == "费用经手人") {
                $(this).combobox("setText", "");
            }
        }
    });
    var zylist = ParseData(window.external.DoOptions(strTableP0507, "GetComboBoxData", '{"flag":"3"}'));
    if (zylist.ReturnCode == 0 && zylist.Records instanceof Array) {
        zylist.Records.unshift({ "zydm": "", "mc": "费用经手人" });
        $("#jsrdm").combobox("loadData", zylist.Records);
    }
    bLoadComplete = true;
    //为费用科目、费用经手人、预提对象、时间类型设置默认值
    $("#fykmmc,#jsrdm,#ytdx").combobox("setValue", "");
    $("#sjtype").combobox("setValue", "本月");
    dateExtentCalculation("本月", "sdate", "edate");

    addArrowClass();
}

//grid双击事件
function alterRowDataP0507(altertype, rowid) {
    var alterItem = $("#" + strTableP0507).getRowData(rowid);
    //打开预提费用支付窗口
    openYtzf(alterItem.djbh);
}

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

//为管理界面jqgrid绑定事件
function bindGridEventP0507() {
    $("#" + strTableP0507).setGridParam({
        //创建浮动按钮
        onSelectRow: function (rowId) {
            try {
                selRowId = rowId;
                var selItem = $(this).getRowData(rowId);
                if (selItem.djbh) {
                    var strBtns = '<a herf="#" onclick="alterRowDataP0507(2,' + rowId + ');return false; ">修改</a>-<a herf="#" onclick="delRowDataP0507(' + rowId + ');return false; ">删除</a>';
                    createFloatButton.call(this, rowId, strBtns);
                }
            } catch (e) { }
        },
        onSortCol: function (index, colindex, sortorder) {
            try {
                searchParam.sortfield = index;
                searchParam.orderby = sortorder;
                loadGridData_Page(searchParam);
                $("div.operate").hide();
                return "stop";
            } catch (e) { }
        }
    });
}

//管理界面查询信息
function searchDataClick_P0507(flag) {
    try {
        var sdate = $("#sdate").val();
        var edate = $("#edate").val();
        var kmdm = $("#fykmmc").combobox("getValue");
        var zydm = $("#jsrdm").combobox("getValue");
        var ytdx = $("#ytdx").combobox("getValue");

        if (kmdm == undefined) { $("#fykmmc").combobox("setValue", ""); kmdm = ""; }
        if (zydm == undefined) { $("#jsrdm").combobox("setValue", ""); zydm = ""; }
        if (ytdx == undefined) { $("#ytdx").combobox("setValue", ""); ytdx = ""; }

        if (flag == 1) {
            searchParam.sortfield = "djdate";
            searchParam.orderby = "desc";
        }
        searchParam.flag = flag;
        searchParam.where = '"sdate":"' + sdate + '","edate":"' + edate + '","kmdm":"' + kmdm + '","zydm":"' + zydm + '","ytdx":"' + ytdx + '"';
        var s = loadGridData_Page(searchParam);
        searchParam.flag = 0;
        if (s.Records.length == 0) {
            s.hjje = "&nbsp;";
        }
        $("#" + strTableP0507).footerData("set", { rn: "合计", a1: s.hjje }, true);
    } catch (e) { }
}

//加载窗口grid数据，并计算合计
function loadGridData(strTableName, mylist) {
    $("#" + strTableName).clearGridData();
    var count = mylist.length > 5 ? mylist.length : 5;
    //添加行并为行分配id，并计算合计
    var kzfje = 0, bczfje = 0;
    for (var i = 0; i < count; i++) {
        if (mylist[i]) {                                                                         //添加后台数据行
            kzfje += parseFloat(mylist[i].kzfje);
            bczfje += parseFloat(mylist[i].bczfje);
            $("#" + strTableName).addRowData(i + 1, mylist[i]);      //添加后台数据行
        }
        else {                                                                                     //添加空行
            $("#" + strTableName).addRowData(i + 1, {});
        }
    }
    $("#" + strTableName).footerData("set", { rn: "合计", kzfje: kzfje, bczfje: bczfje }, true);
    $("#" + strTableName).data("nextNum", count + 1);

    resizeGridScroll(strTableName);

}

//关闭窗口
function closeMyDlg(dlgId, strType, strTableName) {
    try {
        var isChange = $("#" + dlgId).data("change");
        if (isChange) {
            window.parent.cihoAlert(
            msg.other.haveChange  //message information
            , msgBox.dlgBtn.YesNoCancel     //按钮类型msgBox.dlgBtn.YesNo  msgBox.dlgBtn.YesNoCancel
            , function (strRet) {//回调函数
                if (msgBox.dlgRst.Yes == strRet) {
                    saveMyData(dlgId, 1, strTableName);
                }
                else if (msgBox.dlgRst.No == strRet) {
                    cihoDlgClose(dlgId);
                }
            }
        );
        } else {
            cihoDlgClose(dlgId);
        }
    } catch (e) { }
}

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

//删除窗口中的grid数据
function delDjRow(rowId) {
    try {
        $("#" + strTableP050701).saveCell(cellX, cellY);
        var delItem = $("#" + strTableP050701).getRowData(rowId);
        if (delItem.mxguid || delItem.gzguid) {//如果有商品代码
            window.parent.cihoAlert(
                    msg.del.delConfirm,
                     msgBox.dlgBtn.YesNo,
                     function (strRet) {
                         if (msgBox.dlgRst.Yes == strRet) {
                             if (delItem.glsl > 0) {
                                 window.parent.cihoAlert(msg.del.delForbid, msgBox.dlgBtn.Ok);
                             } else {
                                 $("#" + strTableP050701).delRowData(rowId);
                                 if (delItem.mxguid) {
                                     records.push('{"mxguid":"' + delItem.mxguid + '","flag":"3"}');
                                     changeZt(strTableP050701);
                                 }
                                 sumGridTotal(strTableP050701);
                                 resizeGridScroll(strTableP050701);
                             }
                         }
                     }
                );
        }
        else {
            $("#" + strTableP050701).delRowData(rowId);
            sumGridTotal(strTableP050701);
            resizeGridScroll(strTableP050701);
        }

    } catch (e) { }
}

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

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

        $("#idMust", "#" + dlgId).empty();
        $("#djdate", "#" + dlgId).val(getNowDate());
        $("#djdate", "#" + dlgId).attr("disabled", false);
        $("#kmdm,#zydm,#fykmdm", "#" + dlgId).combobox("setValue", "");
        $("#kmdm,#zydm,#fykmdm", "#" + dlgId).combobox("enable");
        $("#czydm", "#" + dlgId).attr("disabled", true).val(window.parent.objLoginInfo.name);
        $("#bz", "#" + dlgId).val("");
        $("#" + dlgId).data("change", false);
        alterdata = {};
        setTimeout(' $("#bz", "#" + strDivP050701).focus();', 100);
    } catch (e) { }
}

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

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

//改变对话框或数据行的状态
//如果只提供表格id，则只改变窗口的状态标志
function changeZt(tbId, rowId) {
    if (tbId == "Tp050701") {
        $("#" + strDivP050701).data("change", true);
    }
    if (rowId) {
        var item = $("#" + strTableP050701).getRowData(rowId);
        if (item.mxguid) {
            $("#" + strTableP050701).setCell(rowId, "flag", 2);                               //2代表更新
        } else {
            $("#" + strTableP050701).setCell(rowId, "flag", 1);                               //1代表新增
        }
    }
}
//计算grid脚部合计
function sumGridTotal(tbId) {
    var kzfje = 0, bczfje = 0;
    var tb = $("#" + tbId);
    var ids = tb.getDataIDs();
    for (var i = 0; i < ids.length; i++) {
        var tempItem = tb.getRowData(ids[i]);
        kzfje += isNaN(tempItem.kzfje) ? 0.00 : tempItem.kzfje * 1;
        bczfje += isNaN(tempItem.bczfje) ? 0.00 : tempItem.bczfje * 1;
    }
    tb.footerData("set", { rn: "合计", kzfje: kzfje, bczfje: bczfje }, true);
}

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

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

//创建窗口input元素和grid
function createElements(strTableName, dlgId) {
    var config = ParseData(window.external.DoOptions(strTableName, "GetTableConfig", "{}")); // 向后台请求配置信息
    var header = createInputs(config.pageHeader);                                            // 根据头配置 生成表单元素 
    var footer = createInputs(config.pageFooter);                                           //根据脚信息   生成表单元素

    $("#" + dlgId + "_divform").append(header+'<table id="' + strTableName + '"></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(strTableName, config.colNames, config.colModel);
    $("#" + strTableName).setLabel("rn", "序号");
}

//创建表单元素
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>";
            }
        }
    }
    strForm += "</ul>";
    return strForm;
}

//grid列的格式化
function addColFormater(tbId) {
    var $tbId = $("#" + tbId);
    $tbId.setColProp("kzfje", { formatter: formatMoneyPlace });
    $tbId.setColProp("bczfje", { formatter: formatMoneyPlace });
    $tbId.setColProp("fykmmc", { editoptions: { custom_element: my_input, custom_value: my_value} });
    $tbId.setColProp("ytdx", { editoptions: { custom_element: my_input, custom_value: my_value} });
}

function refreshInfos(obj) {
    if (obj && obj.page && obj.flag) {
        if (obj.page == "p0506" && obj.flag == "1") {
            var kmlist = ParseData(window.external.DoOptions(strTableP0507, "GetComboBoxData", '{"flag":"1"}'));
            if (kmlist.ReturnCode == 0 && kmlist.Records instanceof Array) {
                kmlist.Records.unshift({ "kmdm": "", "mc": "费用科目" });
                $("#fykmmc").combobox("loadData", kmlist.Records);
            }
            $("#fykmmc").combobox("setValue", "");

            var ytlist = ParseData(window.external.DoOptions(strTableP0507, "GetComboBoxData", '{"flag":"2"}'));
            if (ytlist.ReturnCode == 0 && ytlist.Records instanceof Array) {
                ytlist.Records.unshift({ "ytdx": "", "mc": "预提对象" });
                $("#ytdx").combobox("loadData", ytlist.Records);
            }
            $("#ytdx").combobox("setValue", "");

            var zylist = ParseData(window.external.DoOptions(strTableP0507, "GetComboBoxData", '{"flag":"3"}'));
            if (zylist.ReturnCode == 0 && zylist.Records instanceof Array) {
                zylist.Records.unshift({ "zydm": "", "mc": "费用经手人" });
                $("#jsrdm").combobox("loadData", zylist.Records);
            }
            $("#jsrdm").combobox("setValue", "");
        }
    }
}