var strTableP051504_fyd = "Tp050101";
var strTableP051504_fpd = "Tp050102";
var strDivP051504_fyd = "divP051504";
var strDivP051504_fpd = "divP05150401";
var cellX;
var cellY;
//////////////////////////////////////
//打开费用支出窗口
function openZc_P051504(djbh) {
    try {
        var tbId = strTableP051504_fyd, dlgId = strDivP051504_fyd;
        var $tbId = $("#" + tbId), $dlgId = $("#" + dlgId);
                                         //保存窗口状态信息
        $dlgId.unbind("keydown keypress").bind("keydown keypress", function () { if (event.keyCode == 13) { return false; } });
        creatDiv_ShowDlgHaveTbl(dlgId, "费用支出单", false, false, tbId, 700);  //创建弹出窗口
        createElements(tbId, dlgId);                                          //创建表单元素
        initGridSetP050101(tbId, dlgId);                                      //为grid绑定事件
        initInputsProp(tbId, dlgId);                                          //创建表单元素
        $("#bz", $dlgId).focus();                                               //初始进来时给备注上加上焦点
        var mylist = [];                                                            //修改，页头页脚初始值
        //去后台请求修改信息
        var data = ParseData(window.external.DoOptions(tbId, "GetList", '{ "djbh": "' + djbh + '" }'));
        if (data && data.ReturnCode == 0) {
            //为单据编号和单据时间赋值
            $("#idMust", $dlgId).append('NO:<span id="djbh">' + djbh + '</span>');
            $("#djdate", $dlgId).attr("disabled", true).val(data.djdate);

            //为账户combotree赋值
            var $zhmc = $("#zhmc", $dlgId);
            $zhmc.cihoComboTree("setValue", data.zhdm);
            $zhmc.cihoComboTree("setText", data.zhmc);

            //为制单人、备注赋值
            $("#czymc", $dlgId).val(data.czymc);
            $("#bz", $dlgId).val(escape(data.bz));
            if (data.Records instanceof Array) { mylist = data.Records };
            $dlgId.data("data", { djbh: djbh, zhdm: data.zhdm, zhmc: data.zhmc, czydm: data.czydm, czymc: data.czymc }); //将修改信息存放在dialog里面
            $zhmc = null;
        } else {
            window.parent.cihoAlert(data.MSG, msgBox.dlgBtn.Ok);
        }

        //为jqgrid加载数据
        loadGridData(tbId, mylist);
        resizeGridScroll(tbId);
        $dlgId.data("change", false);
        setTimeout('$("#bz", "#"+strDivP051504_fyd).focus();', 100);
        $(".layoutpanel").css("z-index", "50000009");

        $dlgId = $tbId = null;
    } catch (e) { }
}

//为grid定义事件
function initGridSetP050101(tbId, dlgId) {
    $("#" + tbId).setGridParam({
        "afterEditCell": function (rowId, cellname, value, iRow, iCol) {
            cellX = iRow; cellY = iCol;
        }
    });

    //格式化grid
    addColFormater(tbId);

    //在grid上绑定一个数组，用来存储删除数据
    $("#" + tbId).data("records", []);
    //$("#gbox_" + tbId).css("height", "157px");
    $("#" + tbId).setGridHeight(141);
}

//添加分配按钮
function addFpButton(rowId) {
    var $tbId = $("#" + strTableP051504_fyd);
    var kmdm = $tbId.getCell(rowId, "kmdm");
    var je = $tbId.getCell(rowId, "je") * 1;
    var fyfp = $tbId.getCell(rowId, "fyfp");             //费用分配列没有任何图标
    if (!$.trim(fyfp) && je && kmdm) {                   //没有已分配信息，并且科目和金额已经填好，则未费用分配列添加费用分配图标
        $tbId.setCell(rowId, "fyfp", "<div class = 'name'><div class='wfp'><div class='add'><a href=\"#\" title=\"分配费用\" onclick=\"openFYFP_P051504(" + rowId + ");return false; \"></a></div></div></div>");
    }
    $tbId = null;
}


//////////////////////////////
//创建窗口input元素和grid
function createElements(tbId, dlgId) {
    var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", "{}"));      // 向后台请求配置信息
    for (var i = 0; i < config.colModel.length; i++) {
        if (config.colModel[i].index == "cz") {
            config.colModel[i].hidden = true;
        }
    }
    var header = createFyInputs(config.pageHeader);                                         // 根据头配置 生成表单元素 
    var footer = createFyInputs(config.pageFooter);                                         //根据脚信息   生成表单元素
    $("#" + dlgId + "_divform").append(header).append('<table id="' + tbId + '"></table>').append(footer); //将表单元素添加到窗口中
    createFyDjGrid(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);
    //$("table.ui-jqgrid-htable th:first", "#" + dlgId).text("序号");
    $("#" + tbId).setLabel("rn", "序号");
    config = null;
}

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

    //定义单据日期、付款账户、备注的宽度
    $("#djdate,#zhmc", $dlgId).parent().addClass("inp_70");
    $("#bz", $dlgId).parent().addClass("bz");
    //创建付款账户combotree
    $("#zhmc", $dlgId).cihoComboTree({
        width: 120,
        showBox: false,
        showMode: "all"
    });
}

//创建表单元素
function createFyInputs(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 + "' disabled ";
                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" disabled />';
                strForm += "</li>";
            }
        }
    }
    strForm += "</ul>";
    return strForm;
}

//为操作按钮注册事件
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);
        $tbId = null;
    } catch (e) { }
}

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

//计算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 == strTableP051504_fpd) {
        var scaleMoney = $("#scaleMoney").data("scaleMoney") - hjje;
        $("#scaleMoney").text(scaleMoney.toFixed(window.parent.strMoneyPlace));
    }
    $tbId = null;
}

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

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

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

//加载窗口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 == strTableP051504_fyd) {
                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_P051504(" + (i + 1) + ");return false; \"></a></div></div>";
                } else {                        //否则就是未分配金额
                    mylist[i].fyfp = "<div class = 'name'><div class='add'><a href=\"#\" title=\"分配费用\" onclick=\"openFYFP_P051504(" + (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);
}


//改变表单的状态
function changeZt(tbId, rowId) {
    if (tbId == strTableP051504_fyd) {
        $("#" + strDivP051504_fyd).data("change", true);
    } else {
        $("#" + strDivP051504_fpd).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;
    }
}

//打开费用分配窗口

function openFYFP_P051504(rowId) {
    try {
        $("#" + strTableP051504_fyd).saveCell(cellX, cellY);
        var item = $("#" + strTableP051504_fyd).getRowData(rowId);          //获取费用分配行

        if (!item.je * 1) {                                             //如果费用分配行没有金额信息，则返回
            window.parent.cihoAlert(msg.skd.notFenPei);
            return;
        }

        //-----------------------------------------创建费用分配窗口--------------------------------------------

        var tbId = strTableP051504_fpd, dlgId = strDivP051504_fpd, $dlgId = $("#" + dlgId);
        $dlgId.unbind("keydown keypress").bind("keydown keypress", function () { if (event.keyCode == 13) { return false; } });
        //创建费用分配窗口
        creatDiv_ShowDlgHaveTbl(dlgId, "费用分配", true, false, tbId, 600);

        //创建顶部的分配按钮
        $("#" + dlgId + "_pop_box_top").html('<a href="#" title="平均分配" onclick="">平均分配</a>|<a href="#" title="按销售额比例分配" onclick="">按销售额比例分配</a>');

        //创建选择客户下拉层
        strItemHtml = '<div class="client">';
        strItemHtml += '<div class="client_top"><a href="#" id="expand">客户选择</a>待分配金额：<span id="scaleMoney"></span></div>';
        strItemHtml += '<div class="kh"><ul id="relation"></ul>';
        strItemHtml += '<ul id="more" style="display: none;"></ul></div></div>';
        //strItemHtml += '<ul id="ok"><li class="client_btn"><a href=\"#\">确定</a></li></ul>';
        $("#" + dlgId + "_pop_box_top").after(strItemHtml);

        //创建grid表格
        $("#" + dlgId + "_divform").append("<table id='" + tbId + "'></table>");

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

        // 向后台请求grid配置信息
        var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", "{}"));
        for (var j in config.colModel) {
            if (config.colModel[j].index == "cz") {
                config.colModel[j].hidden = true;
            }
        }
        createFyDjGrid(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);

        //修饰grid
        //$("table.ui-jqgrid-htable th:first", $dlgId).text("序号");
        $("#" + tbId).setLabel("rn", "序号");

        //为grid绑定事件
        initGridSetP050102(tbId, dlgId);

        var mylist = [];
        if (item.mxguid && !item.fpxx && !item.scxx) {                  //如果改行有mxguid，但是没有分配信息和删除信息就去后台请求分配信息
            var s = ParseData(window.external.DoOptions(tbId, "GetList", '{"zbmxguid":"' + item.mxguid + '","flag":"1"}'));
            if (s && s.ReturnCode == 0 && s.Records instanceof Array) {
                mylist = s.Records;
            }
        } else if (item.fpje * 1 > 0) {                                 //如果已分配，则请求前台信息
            mylist = ParseData("[" + item.fpxx + "]");
        }

        //为客户下拉层加载checkbox
        addCheckbox(item.zydm, dlgId);

        //加载数据
        loadGridData(tbId, mylist);
        resizeGridScroll(tbId);
        //计算未分配金额
        var wfpje = item.je * 1 - $tbId.footerData("get").je * 1;

        //id为scaleMoney的span上面保存着未分配金额和金额总额
        $("#scaleMoney", $dlgId).data("scaleMoney", item.je).text(wfpje.toFixed(window.parent.strMoneyPlace));

        //---------------------------------注册事件----------------------------------

        reCheckKH();

        //为展开客户按钮注册事件
        $("#expand", $dlgId).click(function () {
            $("div.kh", "#" + dlgId).slideToggle("normal");
            $(this).toggleClass("active");
            reCheckKH();
            return false;
        });

        //查看其他客户
        $("#btnMore", $dlgId).click(function () { $("#more", "#" + dlgId).slideToggle("normal"); return false; });

        //根据选中的客户查询药品信息
        $("#ok a", $dlgId).click(function () { search(item.zydm); return false; });


        $("div.client", $dlgId).addClass("zidx");
        $dlgId.data("change", false);
        $dlgId.data("rowId", rowId);

    } catch (e) { }
}

//为grid绑定事件
function initGridSetP050102(tbId, dlgId) {

    //格式化grid
    addColFormater(tbId);

    //在grid上绑定一个数组，用来存储删除数据
    $("#" + tbId).data("records", []);

    //$("#gbox_" + tbId).css("height", "157px");
    $("#" + tbId).setGridHeight(141);
}

//根据职员代码去后台搜索关联信息
function search(zydm) {
    try {
        var tbId = strTableP051504_fpd;
        var $tbId = $("#" + strTableP051504_fpd);

        $tbId.saveCell(cellX, cellY);
        var khdms = [];
        var khlink = [];
        var khmore = [];
        var items = [];
        var ids = $tbId.getDataIDs();

        var $checkedChks = $("div.kh input:checkbox:checked", "#" + strDivP051504_fpd);

        //获取删除信息
        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.khdm) {
                var hasKh = false;
                $checkedChks.each(function () {
                    if (this.id == item.khdm) {                             //用户选中项里面存在这个客户
                        hasKh = true;
                        items.push({ "je": item.je, "cz": "", "spmc": item.spmc, "spdm": item.spdm, "khmc": item.khmc, "khdm": item.khdm, "flag": item.flag, "mxguid": item.mxguid });
                    }
                });
                if (!hasKh && item.mxguid) {                                //如果不存在此客户,就删除
                    var delItems = $tbId.data("records");
                    delItems.push('{"mxguid":"' + item.mxguid + '","flag":"3"}');
                    $tbId.data("records", delItems);
                }
                hasKh = false;
            }
        }


        //获取已选中的信息
        $checkedChks.each(function () {
            var hasKh = false;
            for (var i = 0; i < ids.length; i++) {
                var item = $tbId.getRowData(ids[i]);
                if (this.id == item.khdm) {                                 //grid里面有这个checkbox的信息
                    hasKh = true;
                }
            }
            if (!hasKh) {                                                   //如果grid里面不存在这个客户 
                if (this.name != "t") {                                     //如果是其他
                    khmore.push({ "khdm": this.id, "khmc": this.value, "cz": "", "flag": "1" });
                } else {                                                    //如果是关联客户
                    khdms.push('"' + this.id + '"');
                    khlink.push({ "khdm": this.id, "khmc": this.value, "flag": "1" });
                }
            }
        });

        if (khdms.length > 0) {
            var s = ParseData(window.external.DoOptions(tbId, "GetList", '{"zydm":"' + zydm + '","Records": [' + khdms + '],"flag":"2" }'));
            if (s && s.ReturnCode == 0 && s.Records instanceof Array && s.Records.length > 0) {
                items = items.concat(s.Records).concat(khmore);
            } else {
                items = items.concat(khlink);
            }
        } else {
            items = items.concat(khmore);
        }

        $tbId.clearGridData();
        loadGridData(tbId, items);
        $("#" + strDivP051504_fpd).data("change", true);
        $("div.kh", "#" + strDivP051504_fpd).slideUp("normal");
    } catch (e) { }
}

//使grid中的所有客户与checkbox中的客户保持一致
function reCheckKH() {
    try {
        var tbId = strTableP051504_fpd;
        var $tbId = $("#" + tbId);
        $("div.kh input:checkbox").attr("disabled", "disabled");
        $("div.kh input:checkbox").attr("checked", false);
        var ids = $tbId.getDataIDs();
        for (var i = 0; i < ids.length; i++) {
            var khdm = $tbId.getCell(ids[i], "khdm");
            if (khdm) {
                $("#" + khdm, "div.kh").attr("checked", true);
            }
        }
    } catch (e) { }
}


// 添加checkbox
//根据职员代码，去后台请求关联客户
function addCheckbox(zydm, dlgId) {
    try {
        var s = ParseData(window.external.DoOptions(strTableP051504_fpd, "DoOthers", '{ "zydm": "' + zydm + '","flag":"1" }'));
        if (s && s.ReturnCode == 0 && s.Records instanceof Array) {
            var records = s.Records;
            var $relation = $("#relation", "#" + dlgId);
            var $more = $("#more", "#" + dlgId);
            for (var i = 0; i < records.length; i++) {

                //flag为true代表有业务关联、否则为没有业务关联的客户
                if (records[i].flag == "true") {    //将关联客户添加到关联ul
                    $relation.append('<li><input id="' + records[i].khdm + '" type="checkbox" value="' + records[i].khmc + '" name="t"/><label for="' + records[i].khdm + '">' + records[i].khmc + '</label></li>');
                }
                else {                              //将非关联客户添加到非关联ul
                    $more.append('<li><input id="' + records[i].khdm + '" type="checkbox" value="' + records[i].khmc + '"/><label for="' + records[i].khdm + '">' + records[i].khmc + '</label></li>');
                }
            }
            $relation.append('<li><a href="#" id="btnMore" >更多>></a></li>');
        }
    } catch (e) { }
}