var bLoadComplete = false;
var searchParam = {};
var cellX, cellY;

function pageLoad_P0501() {
    try {
        initInputsP0501();
        var config = ParseData(window.external.DoOptions(strTableP0501, "GetTableConfig", "{}"));
        createGrid(strTableP0501, config.colNames, config.colModel, [], null, null, true, alterRowDataP0501);
        bindGridEventP0501();
        $("#" + strTableP0501).setColProp("je", { formatter: formatMoneyPlace });
        createPage(strPageP0501, strTableP0501);
        resizeGrid(strTableP0501, true, true);
        searchDataClick_P0501(1);
        config = null;
    } catch (e) { }
}

//初始化管理界面的表单元素
function initInputsP0501() {
    $("#sjtype").combobox();
    $("#zcxm,#zhdm").cihoComboTree({ width: 120, showMode: "all" });

    addTreeArrowClass();
    addArrowClass();

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

    //初始化时间类别combobox，并加载数据
    $("#sjtype").combobox({
        width: _iWidth100,
        listWidth: _iWidth100,
        valueField: "dm",
        textField: "mc",
        panelHeight: 102,
        editable: false,
        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);

    //为支出项目combotree加载数据
    var zcxmlist = ParseData(window.external.DoOptions(strTableP0501, "GetTreeList", '{"flag":"1","zt":""}'));
    if (zcxmlist && zcxmlist.Records instanceof Array) {
        zcxmlist.Records.unshift({ "id": "", "text": "全部支出项目" });
        $("#zcxm").cihoComboTree("loadData", zcxmlist.Records);
        $("#zcxm").cihoComboTree("setValue", "");
    }

    //为付款账户combotree加载数据
    var kmlist = ParseData(window.external.DoOptions(strTableP0501, "GetTreeList", '{"flag":"2","zt":""}'));
    if (kmlist && kmlist.Records instanceof Array) {
        kmlist.Records.unshift({ "id": "", "text": "全部付款账户" });
        $("#zhdm").cihoComboTree("loadData", kmlist.Records);
        $("#zhdm").cihoComboTree("setValue", "");
    }

    //为时间类别赋默认值
    $("#sjtype").combobox("setValue", "本月");
    dateExtentCalculation("本月", "sdate", "edate");

    bLoadComplete = true;
    addArrowClass();
    options = zcxmlist = kmlist = null;
}

//为管理界面的grid绑定事件
function bindGridEventP0501() {
    $("#" + strTableP0501).setGridParam({
        //  为管理页面创建浮动按钮
        onSelectRow: function (rowId) {
            try {
                var selItem = $(this).getRowData(rowId);
                if (selItem.djbh) {
                    var strBtns = '<a href="#" onclick="alterRowDataP0501(2,' + rowId + ');return false; ">修改</a>-<a herf="#" onclick="delRowDataP0501(' + rowId + ');return false; ">删除</a>';
                    createFloatButton.call(this, rowId, strBtns);
                }
                selItem = null;
            } 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 delRowDataP0501(rowId) {
    try {
        var delItem = $("#" + strTableP0501).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(strTableP0501, "Delete", '{"djbh":"' + delItem.djbh + '"}'));
                    if (s.ReturnCode == 0) {
                        searchDataClick_P0501(2);
                    } else {
                        window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
                    }
                }
            }
        });
    } catch (e) { }
}

//打开修改页面
function alterRowDataP0501(altertype, rowId) {
    var alterItem = $("#" + strTableP0501).getRowData(rowId);
    //根据单据编号打开修改页面
    openZc(alterItem.djbh);
}

//查询按钮的方法
function searchDataClick_P0501(flag) {
    try {
        var sdate = $("#sdate").val();
        var edate = $("#edate").val();
        var zcxm = $("#zcxm").cihoComboTree("getValue");
        var zhdm = $("#zhdm").cihoComboTree("getValue");

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

//日期范围修改方法
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;";
    }
}

//关闭窗口
function closeMyDlg(dlgId, strType, strTableName) {
    try {
        var isChange = $("#" + dlgId).data("change");
        if (isChange) {
            window.parent.cihoAlert(msg.other.haveChange, 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(tbId) {
    $("#" + tbId).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(\'' + tbId + '\',' + this.id + ');return false; ">删除</a>';
            $("#" + tbId).setCell(this.id, "cz", btn);
        }
        if (e.type == "mouseleave") {
            $("#" + tbId).setCell(this.id, "cz", null);
        }
    });
}

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

//创建单据grid
function createDjGrid(tbId, cNames, cModel) {
    $("#" + tbId).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  class=\"easyui-combobox\" name="' + options.name + '" id="' + options.id + '"></select>');
}
function my_value(ele) {
    return ele.combobox('getText');
}

//创建窗口input元素和grid
function createElements(tbId, dlgId) {
    var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", "{}"));      // 向后台请求配置信息
    var header = createInputs(config.pageHeader);                                         // 根据头配置 生成表单元素 
    var footer = createInputs(config.pageFooter);                                         //根据脚信息   生成表单元素
    $("#" + dlgId + "_divform").append(header+'<table id="' + tbId + '"></table>'+footer); //将表单元素添加到窗口中
    createDjGrid(tbId, config.colNames, config.colModel);                                 //创建grid

    var vCols = [];                                                                       //根据配置信息，将grid中可见并可编辑的列信息保存到数组中
    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;
}

//初始化表单元素
function initInputsProp(tbId, dlgId) {
    var $dlgId = $("#" + dlgId);

    //定义单据日期、付款账户、备注的宽度
    $("#djdate,#zhmc", $dlgId).parent().addClass("inp_70");
    $("#bz", $dlgId).parent().addClass("bz");

    //绑定日期控件
    inputAndBindData("djdate", false, $dlgId, function () { $("#" + dlgId).data("change", true); });

    //创建付款账户combotree
    $("#zhmc", $dlgId).cihoComboTree({
        width: 120,
        showBox: false,
        showMode: "all",
        onSelect: function (item) {
            changeZt(tbId);
        }
    });

    //加载combotree数据
    var kmlist = ParseData(window.external.DoOptions(strTableP0501, "GetTreeList", '{"flag":"2","zt":"true"}'));
    if (kmlist && kmlist.Records instanceof Array) {
        $("#zhmc", $dlgId).cihoComboTree("loadData", kmlist.Records);
        //$("#zhmc", $dlgId).cihoComboTree("setText", "现金");
    }

    //为单据日期和备注注册事件
    $("#djdate,#bz", $dlgId).focus(function () { $(this).select(); }).change(function () { $("#" + dlgId).data("change", true); });
    kmlist = null;
}

//为grid的列添加格式化函数
function addColFormater(tbId) {
    var $tbId = $("#" + tbId);

    //格式化金额
    $tbId.setColProp("je", { formatter: formatMoney });

    //格式化费用支出单
    if (tbId == strTableP050101) {
        $tbId.setColProp("zymc", { editoptions: { custom_element: my_input, custom_value: my_value} });
        $tbId.setColProp("kmmc", { editoptions: { custom_element: my_inputTree, custom_value: my_valueTree} });

        //格式化费用分配
    } else if (tbId == strTableP050102) {
        $tbId.setColProp("khmc", { editoptions: { custom_element: my_input, custom_value: my_value} });
        $tbId.setColProp("spmc", { editoptions: { custom_element: my_input, custom_value: my_value} });
    }
}
function formatMoney(cellValue) {
    if (!isNaN(parseFloat(cellValue)) && (cellValue * 1)) {
        return parseFloat(cellValue).toFixed(window.parent.strMoneyPlace);
    }
    else {
        return "&nbsp;";
    }
}
//改变表单的状态
function changeZt(tbId, rowId) {
    if (tbId == strTableP050101) {
        $("#" + strDivP050101).data("change", true);
    } else {
        $("#" + strDivP050102).data("change", true);
    }
    if (rowId) {
        var $tbId = $("#" + tbId);
        var item = $tbId.getRowData(rowId);
        if (item.mxguid) {
            $tbId.setCell(rowId, "flag", 2);                               //2代表更新
        } else {
            $tbId.setCell(rowId, "flag", 1);                               //1代表新增
        }
        item = null;
    }
}

//加载窗口grid数据，并计算合计
function loadGridData(tbId, mylist) {
    var $tbId = $("#" + tbId);
    var count = mylist.length > 5 ? mylist.length : 5;

    //添加行并为行分配id，并计算合计
    var hjje = 0;
    for (var i = 0; i < count; i++) {
        if (mylist[i]) {                                                                         //添加后台数据行
            hjje += parseFloat(mylist[i].je);

            //如果为费用支出单，则修改费用分配列
            if (tbId == strTableP050101) {
                if (mylist[i].fpje * 1 > 0) {   //如果分配金额大于0，则说明已经分配
                    mylist[i].fyfp = "<div class = 'name'><div class='yfp'><a href=\"#\" title=\"已经分配\" ></a></div><div class='add'><a href=\"#\" title=\"分配费用\" onclick=\"openFYFP(" + (i + 1) + ");return false; \"></a></div></div>";
                } else {                        //否则就是未分配金额
                    mylist[i].fyfp = "<div class = 'name'><div class='add'><a href=\"#\" title=\"分配费用\" onclick=\"openFYFP(" + (i + 1) + ");return false; \"></a></div></div>";
                }
            }
            $tbId.addRowData(i + 1, mylist[i]);                      //添加后台数据行
        }
        else {                                                                                     //添加空行
            $tbId.addRowData(i + 1, {});
        }
    }
    $tbId.footerData("set", { rn: "合计", je: hjje });
    $tbId.data("nextNum", count + 1);
    resizeGridScroll(tbId);
}

//计算grid合计
function sumGridTotal(tbId) {
    var hjje = 0;
    var $tbId = $("#" + tbId);
    var ids = $tbId.getDataIDs();
    for (var i = 0; i < ids.length; i++) {
        var item = $tbId.getRowData(ids[i]);
        hjje += isNaN(item.je) ? 0 : item.je * 1;
    }
    $tbId.footerData("set", { rn: "合计", je: hjje });

    //如果是费用分配窗口，则还要计算未分配金额
    if (tbId == strTableP050102) {
        var scaleMoney = $("#scaleMoney").data("scaleMoney") - hjje;
        $("#scaleMoney").text(scaleMoney.toFixed(window.parent.strMoneyPlace));
    }
    $tbId = null;
}

////========================公共方法========================
//function refreshMyCombobox(strModels) {
//    for (var i = 0; i < strModels.length; i++) {
//        var data;
//        //这里是当前页面有的comgbobox
//        if (strModels[i] == "Tkhxx") {
//            data = getComboboxData(strModels[i] + "2");
//            reLoadCombobox("khdm", data);
//        }
//        if (strModels[i] == "TZyxx") {
//            data = getComboboxData(strModels[i] + "2");
//            reLoadCombobox("zydm", data);
//        }
//        if (strModels[i] == "Tspxx") {
//            data = getComboboxData(strModels[i] + "2");
//            data.unshift({ dm: "", mc: "全部药品" });
//            reLoadCombobox("spdm", data);
//        }
//    }
//}


//保存单据，
//afterSave：1：保存退出
//                  2：保存增加
//tbId：        1：报损：Tp050101
//                  2：报溢：Tp050102
function saveMyData(dlgId, afterSave, tbId) {
    try {
        //添加分类
        if (tbId == ciho.layal.table) {
            ciho.saveType(); return;
        }
        if (tbId == strTableP050102) {                                                               //保存Tp050102
            saveTableP050102(dlgId, afterSave, tbId);
        } else {                                                                                            //保存Tp050101
            saveTableP050101(dlgId, afterSave, tbId);
        }
    } catch (e) { }
}

//对单据进行初始化
function resetGrid(tbId, dlgId) {
    try {
        var $dlgId = $("#" + dlgId), $tbId = $("#" + tbId);

        $("#idMust", $dlgId).empty();
        $("#djdate", $dlgId).val(getNowDate()).attr("disabled", false);

        $("#zhmc", $dlgId).cihoComboTree("setText", "现金");
        $("#czymc", $dlgId).attr("disabled", true).val(window.parent.objLoginInfo.name);
        $("#bz", $dlgId).val("");
        $dlgId.data("change", false).data("state", 1).data("data", {});

        $tbId.data("records", []);
        $tbId.clearGridData();
        loadGridData(tbId, []);
        setTimeout('$("#bz", "#"+strDivP050101).focus();', 100);
    } catch (e) { }
}

//删除窗口中的grid数据
function delDjRow(tbId, rowId) {
    try {
        var $tbId = $("#" + tbId);
        $tbId.saveCell(cellX, cellY);
        var delItem = $tbId.getRowData(rowId);
        var vCols = $tbId.data("vCols");
        if (delItem.flag && !isRowEmpty(delItem, vCols)) {              //如果有操作标示，或者行不为空，就提示是否要删除
            window.parent.cihoAlert(msg.del.delConfirm, msgBox.dlgBtn.YesNo, function (strRet) {
                if (msgBox.dlgRst.Yes == strRet) {
                    var $grid = $("#" + tbId);
                    var row = $grid.getRowData(rowId);
                    $grid.delRowData(rowId);
                    if (row.mxguid) {                                   //如果存在mxguid则保持到records数组里
                        var records = $grid.data("records");
                        records.push('{"mxguid":"' + row.mxguid + '","flag":"3"}');
                        $grid.data("records", records);
                        changeZt(tbId);                                //改变窗口的状态
                    }
                    sumGridTotal(tbId);
                    resizeGridScroll(tbId);
                }
            });
        }
        else {
            $tbId.delRowData(rowId);
            if (delItem.mxguid) {                                   //如果存在mxguid则保持到records数组里
                var records = $tbId.data("records");
                records.push('{"mxguid":"' + delItem.mxguid + '","flag":"3"}');
                $tbId.data("records", records);
                changeZt(tbId);                                      //改变窗口的状态
            }
            sumGridTotal(tbId);
            resizeGridScroll(tbId);
        }

    } catch (e) { }
}

//创建表单元素
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 += '<input id="' + Item.index + '" type="text" class="ciho-Input" />';
                strForm += "</li>";
            }
        }
    }
    strForm += "</ul>";
    return strForm;
}

//格式化grid中的treegrid
function my_inputTree(value, options) {
    var strHtml = "<input id=\"" + options.id + "\" class=\"ciho-Input\"  name=\"" + options.name + "\">";
    return $(strHtml);
}
function my_valueTree(ele) {
    return ele.cihoComboTree('getText');
}

//打开费用分配设置
function openSet() {
    try {
        $("#" + strDivP050103).unbind("keydown keypress").bind("keydown keypress", function () { if (event.keyCode == 13) { saveSet(); cihoDlgClose(strDivP050103); } });
        creatDiv_ShowDlgHaveTbl(strDivP050103, "费用分配统计设置", false, false, "set", 300);
        $("#" + strDivP050103 + "_divform").html("<ul><li class='inp_70'  style=\"text-align:center\" >按比例分配时，根据<input type='text' id='month'/>个月之内的销售</li></ul>");
        var strItemHtml = "<div class=\"clr\"></div>";
        strItemHtml += "<div class=\"box_btn_width\">";
        strItemHtml += "    <div class=\"box_btn\">";
        strItemHtml += "        <div class=\"btn01\"><a id=\"btnSave\"  style=\"cursor:pointer\">保存</a></div>";
        strItemHtml += "    </div>";
        strItemHtml += "</div>";
        $(".pop_box", "#" + strDivP050103).append(strItemHtml);
        $("#month", "#" + strDivP050103).autoNumeric({ mDec: 0, aSep: "", mNum: 2 }).focus(function () { this.select(); }).css("ime-mode", "disabled");

        var s = ParseData(window.external.DoOptions(strTableP0501, "GetSingle", "{}"));
        if (s.ReturnCode == 0) {
            $("#month", "#" + strDivP050103).val(s.a3);
            $("#month", "#" + strDivP050103).focus();           //设置焦点
        }

        $("#btnSave", "#" + strDivP050103).click(saveSet);
    } catch (e) { }
}

function saveSet() {
    var month = $("#month", "#" + strDivP050103).val() * 1;
    if (!month) {//"统计范围不能为空！"
        window.parent.cihoAlert(msg.cw.tjfwNotEmp, msgBox.dlgBtn.Ok, function () { $("#month", "#" + strDivP050103).focus(); });
        return;
    }
    var s = ParseData(window.external.DoOptions(strTableP0501, "Edit", '{"a3":"' + month + '"}'));
    if (s.ReturnCode != 0) {
        window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
    } else {
        cihoDlgClose(strDivP050103);
    }
    return false;
}

/// <summary>基本资料修改刷新</summary>
function refreshMyCombobox(strModels) {
    for (var i = 0; i < strModels.length; i++) {
        if (strModels[i] == "TKjkm") {
            var s = ParseData(window.external.DoOptions(strTableP0501, "GetTreeList", '{"flag":"1","zt":""}'));
            if (s.ReturnCode == 0 && s.Records instanceof Array) {
                s.Records.unshift({ "id": "", "text": "全部支出项目" });
                $("#zcxm").cihoComboTree("loadData", s.Records);
                $("#zcxm").cihoComboTree("setValue", "");
            }
        }
        if (strModels[i] == "TKjkm") {
            var s = ParseData(window.external.DoOptions(strTableP0501, "GetTreeList", '{"flag":"2","zt":""}'));
            if (s.ReturnCode == 0 && s.Records instanceof Array) {
                s.Records.unshift({ "id": "", "text": "全部付款账户" });
                $("#zhdm").cihoComboTree("loadData", s.Records);
                $("#zhdm").cihoComboTree("setValue", "");
            }
        }
    }
}

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