//打开费用分配窗口

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

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

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

        var tbId = strTableP050102, dlgId = strDivP050102, $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="avgMoney(' + item.je + ');return false; ">平均分配</a>|<a href="#" title="按销售额比例分配" onclick="scaleMoney(' + item.je + ',\'' + item.zydm + '\');return false; ">按销售额比例分配</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>';
        strItemHtml += '<ul id="ok"><li class="client_btn"><a href=\"#\">确定</a></li></ul></div></div>';
        $("#" + dlgId + "_pop_box_top").after(strItemHtml);

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

        //添加保存按钮按钮
        var strItemHtml = "<div class=\"clr\"></div>";
        strItemHtml += "<div class=\"box_btn_width\">";
        strItemHtml += "<div class=\"box_btn\">";
        strItemHtml += "<div class=\"btn01\"><a href=\"#\" id=\"btnSaveFp\"  style=\"cursor:pointer\">保存</a></div>";
        strItemHtml += "</div></div>";
        $(".pop_box", $dlgId).append(strItemHtml);

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

        // 向后台请求grid配置信息
        var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", "{}"));
        createDjGrid(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("序号");
        $(".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; "/>');

        //=========================调节操作列的配置信息====================
        //        for (var i in config.colModel) {
        //            if (config.colModel[i].index == "cz") {
        //                config.colModel[i].align = "center";
        //                break;
        //            }
        //        }
        //=========================调节操作列的配置信息=====================

        //为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);

        //计算未分配金额
        var wfpje = (item.je * 1 || 0) - ($tbId.footerData("get").je * 1 || 0);

        //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; });

        //保存分配信息
        $("#btnSaveFp", $dlgId).click(saveTableP050102);

        //根据选中的客户查询药品信息
        $("#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) { }
}


//保存分配信息
function saveTableP050102() {
    var dlgId = strDivP050102, tbId = strTableP050102;
    $("#" + tbId).saveCell(cellX, cellY);

    if (!authMyBillsTp050102(tbId, dlgId)) { return false; };            //验证单据信息

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

    var delItems = $tbId.data("records");       //保存删除信息
    var records = [];                           //保存分配信息

    var ids = $tbId.getDataIDs();
    for (var i = 0; i < ids.length; i++) {
        var item = $tbId.getRowData(ids[i]);
        if (item.flag) {
            //只有分配金额大于0的才保存到数据库，否则保存就删除
            if (item.je * 1 > 0) {
                var record = '{"mxguid":"' + item.mxguid + '","je":"' + item.je + '","khdm":"' + item.khdm + '","khmc":"' + item.khmc + '","spdm":"' + item.spdm + '","spmc":"' + item.spmc + '","flag":"' + item.flag + '"}';
                records.push(record);
            } else if (item.mxguid) {
                delItems.push('{"mxguid":"' + item.mxguid + '","flag":"3"}');
            }
        }
    }

    var jsonStr = records.toString();

    var yfpje = $tbId.footerData("get").je * 1;

    //费用支出单
    var $grid = $("#" + strTableP050101);
    var rowId = $dlgId.data("rowId");

    //如果有删除信息，则将费用支出单里的删除信息与删除信息连接
    if (delItems instanceof Array && delItems.length > 0) {
        //根据分配rowId 获取删除信息

        var dellist = $grid.getCell(rowId, "scxx");

        if (dellist) {//如果存在删除信息，则将删除信息联合
            dellist = dellist + "," + delItems;
        } else {      //否则只将分配单里的删除信息保存到费用支出单
            dellist = delItems;
        }
        $grid.setCell(rowId, "scxx", dellist);
    }

    $grid.setCell(rowId, "fpxx", jsonStr || null);                      //保存分配信息到费用支出单
    $grid.setCell(rowId, "fpje", yfpje);                             //保存分配金额到费用支出单

    //如果已分配金额大于0，则将费用支出单里的费用分配显示为已分配，否则只显示分配按钮
    if (yfpje > 0) {
        $grid.setCell(rowId, "fyfp", "<div class = 'name '><div class='yfp'><a  title=\"已经分配\" ></a></div><div class='add'><a href=\"#\" title=\"分配费用\" onclick=\"openFYFP(" + rowId + ");return false; \"></a></div></div>");
    } else {
        $grid.setCell(rowId, "fyfp", "<div class = 'name '><div class='wfp'><a  title=\"未分配\" ></a></div><div class='add'><a href=\"#\" title=\"分配费用\" onclick=\"openFYFP(" + rowId + ");return false; \"></a></div></div>");
    }
    changeZt(strTableP050101, rowId);
    cihoDlgClose(dlgId)
    return false;
}

//为grid绑定事件
function initGridSetP050102(tbId, dlgId) {
    $("#" + tbId).setGridParam({
        "afterSaveCell": function (rowId, cellname, value) {
            try {                                                       //保存完分配额后计算合计
                if (cellname == "je") { sumGridTotal(this.id); }
            } catch (e) { }
        },
        "afterEditCell": function (rowId, cellname, value, iRow, iCol) {
            try {
                cellX = iRow; cellY = iCol;
                var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
                switch (cellname) {
                    case "spmc":

                        //为药品绑定combobox
                        item.combobox({ valueField: "dm", textField: "mc", width: _iWidth120 });

                        //加载combobox数据
                        var yplist = getComboboxData("Tspxx");
                        yplist.push({ "mc": "<font color='red'>添加药品</font>", "dm": "-1" });
                        item.combobox("loadData", yplist);

                        //为combobox赋值
                        var ypdm = $(this).getCell(rowId, "spdm");
                        item.combobox("setValue", ypdm);
                        if (item.combobox("getText") == ypdm) {
                            item.combobox("setText", value);
                        }

                        item.combobox('focus');

                        //为combobox绑定事件
                        item.combobox({
                            onChange: function (newValue) {
                                if (newValue) {
                                    $("#" + tbId).setCell(rowId, "spdm", newValue);
                                }
                                else {
                                    $("#" + tbId).setCell(rowId, "spdm", null);
                                }
                                changeZt(tbId, rowId);
                            },
                            onSelect: function (item) {
                                if (item.dm == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "药品", table: "Tflxx" }, { model: "Tspxx", jquery: $(this) });
                                    $(this).combobox("setValue", "");
                                }
                            },
                            afterChange: function (newValue, newText) {
                                if (newValue == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "药品", table: "Tflxx" }, { model: "Tspxx", jquery: $(this) });
                                    ciho.showTypeDialog();
                                    $(this).combobox("setValue", "");
                                }
                            }
                        });
                        break;
                    case "khmc":

                        //为客户绑定combobox
                        item.combobox({ valueField: "dm", textField: "mc", width: _iWidth120 });

                        //为combobox加载数据
                        var khlist = getComboboxData("Tkhxx1");
                        khlist.push({ "mc": "<font color='red'>添加客户</font>", "dm": "-1" });
                        item.combobox("loadData", khlist);

                        //为combobox赋值
                        var khdm = $(this).getCell(rowId, "khdm");
                        item.combobox("setValue", khdm);
                        item.combobox("setText", value);
                        if (item.combobox("getText") == khdm) {
                            item.combobox("setText", value);
                        }
                        item.combobox('focus');

                        //为combobox绑定事件
                        item.combobox({
                            onChange: function (newValue) {
                                if (newValue) {
                                    $("#" + tbId).setCell(rowId, "khdm", newValue);
                                }
                                else {
                                    $("#" + tbId).setCell(rowId, "khdm", null);
                                }
                                changeZt(tbId, rowId);
                            },
                            onSelect: function (item) {
                                if (item.dm == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "客户", table: "Tflxx" }, { model: "Tkhxx", jquery: $(this) });
                                    $(this).combobox("setValue", "");
                                }
                            },
                            afterChange: function (newValue, newText) {
                                if (newValue == "-1") {
                                    ciho.IniData({ id: "divAddType", title: "客户", table: "Tflxx" }, { model: "Tkhxx", jquery: $(this) });
                                    ciho.showTypeDialog();
                                    $(this).combobox("setValue", "");
                                } else {
                                    $(this).combobox("setText", newText.replace(/&nbsp;/g, ""));
                                }
                            }
                        });
                        break;
                    case "je":

                        //为分配额文本框赋值
                        item.val(value);
                        //绑定事件
                        item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                        item.change(function () { changeZt(tbId, rowId); });
                        break;
                }
                $(".layoutpanel").css("z-index", "50000009");
            } catch (e) { }
        }
    });

    //格式化grid
    addColFormater(tbId);

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

    //为grid绑定删除事件
    bindDelEvent(tbId);
    $("#" + tbId).setGridHeight(141);
}

//平均分配金额
function avgMoney(sum) {
    try {
        var tbId = strTableP050102;
        var $tbId = $("#" + tbId);
        $tbId.saveCell(cellX, cellY);
        var ids = $tbId.getDataIDs();
        var itemcount = 0;
        var hash = [];

        //验证重复行
        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.spdm || item.khdm) {
                itemcount++;
                for (var j = 0; j < hash.length; j++) {
                    if (item.spdm == hash[j].spdm && item.khdm == hash[j].khdm) {
                        window.parent.cihoAlert(msg.other.dnh + (j + 1) + "】行与第【" + (i + 1) + "】行重复！", msgBox.dlgBtn.Ok);
                        return;
                    }
                }
                hash.push(item);
            }
        }
        if (!itemcount) return;
        //平均分配
        var avg = Math.floor(sum * Math.pow(10, window.parent.strMoneyPlace) / itemcount);                                 //向下舍入,求平均数
        var rest = sum * Math.pow(10, window.parent.strMoneyPlace);
        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.spdm || item.khdm) {
                rest = rest - avg;
                if (rest < avg) {
                    $tbId.setCell(ids[i], "je", (avg + rest) / Math.pow(10, window.parent.strMoneyPlace));
                } else {
                    $tbId.setCell(ids[i], "je", avg / Math.pow(10, window.parent.strMoneyPlace));
                }
            } else {
                $tbId.setCell(ids[i], "je", null);
            }
        }
        sumGridTotal(tbId);
        $("#" + strDivP050102).data("change", true);
    } catch (e) { }
}

//按比例分配金额
function scaleMoney(sum, zydm) {
    try {
        var tbId = strTableP050102;
        var $tbId = $("#" + strTableP050102);

        $tbId.saveCell(cellX, cellY);
        var ids = $tbId.getDataIDs();
        var itemcount = 0;
        var hash = [];
        var records = [];
        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.spdm || item.khdm) {
                itemcount++;

                //验证客户
                if (!item.khdm) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.kh.lnEmpOrNotExit, msgBox.dlgBtn.Ok);
                    return;
                }

                //验证药品
                if (!item.spdm) {
                    window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.yp.lnEmpOrNotExit, msgBox.dlgBtn.Ok);
                    return;
                }

                //验证行重复
                for (var j = 0; j < hash.length; j++) {
                    if (item.spdm == hash[j].spdm && item.khdm == hash[j].khdm) {
                        window.parent.cihoAlert(msg.other.dnh + (j + 1) + "】行与第【" + (i + 1) + "】行重复！", msgBox.dlgBtn.Ok);
                        return;
                    }
                }
                hash.push(item);
                var tempstr = '{"id":"' + ids[i] + '","spdm":"' + item.spdm + '","khdm":"' + item.khdm + '"}';
                records.push(tempstr);
            }
        }

        if (!itemcount) return;

        for (var i = 0; i < ids.length; i++) {
            $tbId.setCell(ids[i], "je", null);
        }

        //从后台取出比例金额，如果不成功则平均分配
        if ($("#relation input:checked").length > 0) {
            var jsonStr = '{"zydm":"' + zydm + '","flag":"2","Records":[' + records + ']}';
            var total = 0;
            var s = ParseData(window.external.DoOptions(tbId, "DoOthers", jsonStr));

            if (s && s.ReturnCode == 0 && s.Records instanceof Array) {
                for (var i = 0; i < s.Records.length; i++) {
                    if (i == (s.Records.length - 1)) {
                        $tbId.setCell(s.Records[i].id, "je", sum - total);
                    } else {
                        $tbId.setCell(s.Records[i].id, "je", s.Records[i].szbl * sum);
                        total += (s.Records[i].szbl * sum).toFixed(window.parent.strMoneyPlace) * 1;
                    }
                }
            }
        } else {                                                                                        //计算平均数

            //平均分配
            var avg = Math.floor(sum * Math.pow(10, window.parent.strMoneyPlace) / itemcount);                                 //向下舍入,求平均数
            var rest = sum * Math.pow(10, window.parent.strMoneyPlace);
            for (var i = 0; i < ids.length; i++) {
                var item = $tbId.getRowData(ids[i]);
                if (item.spdm || item.khdm) {
                    rest = rest - avg;
                    if (rest < avg) {
                        $tbId.setCell(ids[i], "je", (avg + rest) / Math.pow(10, window.parent.strMoneyPlace));
                    } else {
                        $tbId.setCell(ids[i], "je", avg / Math.pow(10, window.parent.strMoneyPlace));
                    }
                } else {
                    $tbId.setCell(ids[i], "je", null);
                }
            }
        }

        sumGridTotal(tbId);
        $("#" + strDivP050102).data("change", true);
    } catch (e) { }
}

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

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

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

        //获取删除信息
        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);
        sumGridTotal(tbId);
        $("#" + strDivP050102).data("change", true);
        $("div.kh", "#" + strDivP050102).slideUp("normal");
    } catch (e) { }
}

//使grid中的所有客户与checkbox中的客户保持一致
function reCheckKH() {
    try {
        var tbId = strTableP050102;
        var $tbId = $("#" + tbId);

        $("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(strTableP050102, "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) { }
}

//验证费用分配
function authMyBillsTp050102() {
    var tbId = strTableP050102;

    var dfpje = $("#scaleMoney", "#" + strDivP050102).text() * 1;

    //验证分配金额
    if (dfpje < 0) {//"待分配金额为负数！"
        window.parent.cihoAlert(msg.cw.dafpjeisNegatives, msgBox.dlgBtn.Ok);
        return false;
    }

    var $tbId = $("#" + tbId);
    $tbId.saveCell(cellX, cellY);
    var hash = [];
    var ids = $tbId.getDataIDs();

    for (var i = 0, len = ids.length; i < len; i++) {
        var item = $tbId.getRowData(ids[i]);

        //只验证有分配额的行
        if (item.flag && item.je * 1 > 0) {

            //验证客户
            if (!item.khdm) {//"】行的客户为空或不存在！"
                window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.kh.lnEmpOrNotExit, msgBox.dlgBtn.Ok);
                return false;
            }

            //验证药品
            if (!item.spdm) {//"】行的药品为空或不存在！"
                window.parent.cihoAlert(msg.other.dnh + (i + 1) + msg.sz.yp.lnEmpOrNotExit, msgBox.dlgBtn.Ok);
                return false;
            }

            //验证行重复
            for (var j = 0; j < hash.length; j++) {
                if (item.spdm == hash[j].spdm && item.khdm == hash[j].khdm) {
                    window.parent.cihoAlert(msg.other.dnh + (j + 1) + "】行与第【" + (i + 1) + "】行重复！", msgBox.dlgBtn.Ok);
                    return false;
                }
            }
            hash.push(item);
        }
    }
    return true;
}
