//=================工资表维护==================
//state:1 修改
//state:2 新增

function openGZB(djbh) {
    try {
        var tbId = strTableP050801;
        var dlgId = strDivP050801;
        var $dlgId = $("#" + dlgId);
        if (djbh) { state = 2; } else { state = 1; }

        creatDiv_ShowDlgHaveTbl(dlgId, "工资表", true, false, tbId, 950);
        var config = ParseData(window.external.DoOptions(tbId, "GetTableConfig", '{"djbh":"' + djbh + '"}'));       // 向后台请求配置信息
        var header = createInputs(config.pageHeader);                                                              // 根据头配置 生成表单元素 
        var footer = createInputs(config.pageFooter);                                                                //根据脚信息   生成表单元素
        $("#" + dlgId + "_divform").append(header+'<table id="' + tbId + '"></table>'+footer);

        $("#" + dlgId + "_pop_box_top").html('<a title="导出" style="cursor:pointer;text-decoration:none" onclick="$(\'#' + tbId + '\').saveCell(cellX, cellY);makeExportData(\'' + tbId + '\',\'工资表\');return false; ">导出</a>');
        var strItemHtml = "<div class=\"clr\"></div>";                                                            //添加保存按钮
        strItemHtml += "<div class=\"box_btn_width\">";
        strItemHtml += "<div class=\"box_btn\">";
        strItemHtml += "<div class=\"btn01\"><a id=\"btnSaveGZB\"  style=\"cursor:pointer\">保存退出</a></div>";
        strItemHtml += "</div></div>";
        $(".pop_box", "#" + dlgId).append(strItemHtml);
        createDjGrid(tbId, config.colNames, config.colModel);
		$("#" + tbId).setLabel("rn", "序号");
		
        var zjCols = [], jsCols = [];                                                                                             //将增加类的列和减少类的列存储到数组中
        var items = config.colModel;
        for (var i = 0; i < items.length; i++) {
            if (items[i].dif == 1) { zjCols.push(items[i].index); }      //增加类
            if (items[i].dif == 2) { jsCols.push(items[i].index); }      //减少类
        }

        $("#" + tbId).data("zjCols", zjCols).data("jsCols", jsCols);
        initGridSet(tbId, dlgId);
        initInputsPropGZB(tbId, dlgId);

        var mylist = [];
        if (state == 2) {    // 修改，为标签赋值
            $("#idMust", "#" + dlgId).text("NO:" + djbh);
            var record = ParseData(window.external.DoOptions(tbId, "GetList", '{"djbh":"' + djbh + '"}'));
            if (record.ReturnCode == 0) {
                $("#djrq", "#" + dlgId).val(record.djrq).attr("disabled", true);
                $("#gzmonth", "#" + dlgId).val(record.gzmonth);
                $("#czymc", "#" + dlgId).val(record.czymc);
                $("#bz", "#" + dlgId).val(escape(record.bz));
                if (record.Records instanceof Array) {
                    mylist = record.Records;
                }
                $("#" + tbId).data("data", { czydm: record.czydm, czymc: record.czymc, djbh: djbh });
            } else {
                window.parent.cihoAlert(record.MSG, msgBox.dlgBtn.Ok);
            }
        } else {                                                                                    //新增，为标签设置默认值
            $("#gzmonth", $dlgId).val(getNowDate().match(/^(\d{4}-\d{2})-\d{2}$/)[1]);
            var gzmonth = $("#gzmonth", $dlgId).val();
            var record = ParseData(window.external.DoOptions(tbId, "GetList", '{"djbh":"","gzmonth":"' + gzmonth + '"}'));
            if (record && record.ReturnCode == 0 && record.Records instanceof Array) {
                mylist = record.Records;
            } else {
                window.parent.cihoAlert(record.MSG, msgBox.dlgBtn.Ok);
            }
            $dlgId.data("czydm", window.parent.objLoginInfo.code);
            $("#djrq", $dlgId).val(getNowDate());
            $("#czymc", $dlgId).val(window.parent.objLoginInfo.name);
        }
        loadGridData(tbId, mylist);
        $("#btnSaveGZB").click(saveGZB);
        $dlgId.data("state", state);
        $dlgId.data("change", false);

        $(".layoutpanel").css("z-index", "50000009");
        setTimeout('$("#bz","#"+strDivP050801).focus();', 100);
        $dlgId = null;
    } catch (e) { }
}
//初始化grid事件
function initGridSet(tbId, dlgId) {
    var $tbId = $("#" + tbId);
    if (tbId == "Tp050801") {
        $tbId.setGridParam({
            afterEditCell: function (rowId, cellname, value, iRow, iCol) {
                try {
                    var zydm = $(this).getCell(rowId, "zydm");
                    if (!zydm) { $(this).restoreCell(iRow, iCol); return; }
                    cellX = iRow; cellY = iCol;
                    var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
                    item.val(value);
                    item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                    item.change(function () { changeZt(tbId, rowId); });
                    $tbId = null;
                } catch (e) { }
            },
            afterSaveCell: function (rowId, cellname, value, iRow, iCol) {
                sumGridTotal(tbId);
                $tbId = null;
            }
        });
    }
    if (tbId == "Tp050803") {
        $tbId.setGridParam({
            afterEditCell: function (rowId, cellname, value, iRow, iCol) {
                try {
                    var zydm = $(this).getCell(rowId, "zydm");
                    if (!zydm) { $(this).restoreCell(iRow, iCol); return; }
                    cellX = iRow; cellY = iCol;
                    var item = $("#" + rowId + " :input[name='" + cellname + "']", this);
                    item.val(value);
                    item.autoNumeric({ mDec: window.parent.strMoneyPlace, aSep: "" }).focus(function () { this.select(); }).css("ime-mode", "disabled");
                    item.change(function () { changeZt(tbId, rowId); });
                    $tbId = null;
                } catch (e) { }
            },
            afterSaveCell: function (rowId, cellname, value, iRow, iCol) {
                try {
                    if (cellname == "sfgz") {
                        var yfgz = $(this).getCell(rowId, "yfhj") * 1;
                        var ye = yfgz - value * 1;
                        $(this).setCell(rowId, "ye", ye);
                        sumGridTotal(tbId);
                    }
                    $tbId = null;
                } catch (e) { }
            }
        });
        bindDelEvent(tbId);
    }
    addColFormater(tbId);
    $("#" + tbId).setGridHeight(141);
}

//保存工资表
function saveGZB() {
    try {
        if (!authMyBillsP050801()) { return false; }
        var tbId = strTableP050801;
        var dlgId = strDivP050801;
        var $tbId = $("#" + tbId);
        var $dlgId = $("#" + dlgId);
        var state = $dlgId.data("state");

        var ids = $tbId.getDataIDs();
        var zjCols = $tbId.data("zjCols");
        var jsCols = $tbId.data("jsCols");
        var records = [], inputs = [];
        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.zydm) {
                var record = '{"zydm":"' + item.zydm + '"';
                for (var j = 0; j < zjCols.length; j++) {
                    record += ',"' + zjCols[j] + '":"' + item[zjCols[j]] + '"';
                }
                for (var k = 0; k < jsCols.length; k++) {
                    record += ',"' + jsCols[k] + '":"' + item[jsCols[k]] + '"';
                }
                record += ',"yfgz":"' + item.yfgz + '"}';
                records.push(record);
            }
        }
        var djdate = $dlgId.find("#djrq").val();
        inputs.push('"djdate":"' + djdate + '"');
        var gzmonth = $dlgId.find("#gzmonth").val();
        inputs.push('"gzmonth":"' + gzmonth + '"');
        var bz = trim($dlgId.find("#bz").val());
        inputs.push('"bz":"' + trim(bz) + '"');

        if (state == 1) {
            inputs.push('"czydm":"' + window.parent.objLoginInfo.code + '"');
            var jsonStr = '{' + inputs + ',"Records":[' + records + ']}';
            s = ParseData(window.external.DoOptions(tbId, "Add", jsonStr));
        } else if (state == 2) {
            inputs.push('"czydm":"' + $tbId.data("data").czydm + '"');
            inputs.push('"djbh":"' + $tbId.data("data").djbh + '"');
            var jsonStr = '{' + inputs + ',"Records":[' + records + ']}';
            s = ParseData(window.external.DoOptions(tbId, "Edit", jsonStr));
        }
        if (s && s.ReturnCode == 0) {
            cihoDlgClose(dlgId);
            searchDataClick_P0508(0);
            resizeGridScroll(strTableP0508);
        }
        else {
            window.parent.cihoAlert(s.MSG, msgBox.dlgBtn.Ok);
        }
        return false;
    } catch (e) { }
}

//保存单据，
//afterSave：1：保存退出
//                  2：保存增加
function authMyBillsP050801() {
    try {
        var $tbId = $("#" + strTableP050801);
        $tbId.saveCell(cellX, cellY);

        var maxAmount = window.top._MaxPerBill;


        var footerData = $tbId.footerData("get");
        var zjCol = $tbId.data("zjCols");

        var djEmp = true, djOver = false;
        for (var i = 0; i < zjCol.length; i++) {
            if (footerData[zjCol[i]] * 1 > 0) {
                djEmp = false;
                break;
            }
            if (footerData[zjCol[i]] * 1 > maxAmount) {
                djOver = true;
                break;
            }
        }
        if (djEmp && !djOver) {
            var jsCol = $tbId.data("jsCols");
            for (var i = 0; i < jsCol.length; i++) {
                if (footerData[jsCol[i]] * 1 > 0) {
                    djEmp = false;
                    break;
                }
                if (footerData[jsCol[i]] * 1 > maxAmount) {
                    djOver = true;
                    break;
                }
            }
        }

        var yfgz = /^\d+(\.\d+)?$/.test($tbId.footerData("get").yfgz) ? $tbId.footerData("get").yfgz * 1 : 0;
        if (yfgz > maxAmount) { djOver = true; }

        if (djEmp) {
            window.parent.cihoAlert("工资单不能为空！", msgBox.dlgBtn.Ok);
            return false;
        }

        if (djOver) {
            window.parent.cihoAlert("单据金额过大！", msgBox.dlgBtn.Ok);
            return false;
        }

        var $dlgId = $("#" + strDivP050801);
        var $djdate = $dlgId.find("#djrq");
        var djdate = $dlgId.find("#djrq").val();

        if (!djdate) {
            window.parent.cihoAlert("工资表日期不能为空！", msgBox.dlgBtn.Ok, function () { $djdate.select(); $tbId = $dlgId = $djdate = null; });
            return false;
        } else {
            var djdate = djdate.replace(/\-/g, "/");
            if (djdate < window.top._startDate) {
                window.parent.cihoAlert(msg.other.djrqExtent, msgBox.dlgBtn.Ok, function () { $djdate.select(); $tbId = $dlgId = $djdate = null; });
                return false;
            }
        }

        var $gzmonth = $dlgId.find("#gzmonth");
        var gzmonth = $gzmonth.val();
        if (!/^\d{4}-\d{2}$/.test(gzmonth)) {
            window.parent.cihoAlert("请输入正确的工资月份！", msgBox.dlgBtn.Ok, function () { $gzmonth.select(); $tbId = $dlgId = $djdate = $gzmonth = null; });

            return false;
        } else {
            gzmonth = gzmonth.replace(/\-/g, "/") + "/01";
            if (gzmonth < window.top._startDate) {
                window.parent.cihoAlert(msg.other.gzyfExtent, function () { $djdate.select(); $tbId = $dlgId = $djdate = $gzmonth = null; });
                return false;
            }
        }
        return true;
    } catch (e) { }
}

//初始化工资表中的表单元素
function initInputsPropGZB(tbId, dlgId, djdate) {
    function reloadTC() {                                                   //加载提成数据
        $("#" + tbId).saveCell(cellX, cellY);
        var month = $("#gzmonth", "#" + dlgId).val();
        if (/^\s*\d{4}-\d{2}\s*$/.test(month)) {
            var s = ParseData(window.external.DoOptions(tbId, "DoOthers", '{"gzmonth":"' + month + '"}'));
            var ids = $("#" + tbId).getDataIDs();
            if (s.ReturnCode == 0 && s.Records instanceof Array) {
                var list = s.Records;
                for (var i = 0; i < ids.length; i++) {
                    var item = $("#" + tbId).getRowData(ids[i]);
                    if (item.zydm) {
                        $("#" + tbId).setCell(ids[i], "c2d8aaed-f7bb-4b3e-90ae-1aff05077215", 0);
                        for (var j = 0; j < list.length; j++) {
                            if (list[j].zydm == item.zydm) {
                                $("#" + tbId).setCell(ids[i], "c2d8aaed-f7bb-4b3e-90ae-1aff05077215", list[j].je);
                                break;
                            }
                        }
                    }
                }
            }
            sumGridTotal(tbId);
        } else {
            window.parent.cihoAlert("月份格式不正确！", msgBox.dlgBtn.Ok, function () { $("#gzmonth", "#" + dlgId)[0].select(); });
            return false;
        }
        changeZt(tbId);
    }
    inputAndBindData("djrq", false, "#" + dlgId, function () { changeZt(tbId); });
    $("#gzmonth", "#" + dlgId).monthpicker({ onSelect: reloadTC });
    $("#gzmonth", "#" + dlgId).attr("readonly", true).change(reloadTC);
    $("#bz", "#" + dlgId).parent().addClass("bz");
    $("#djrq,#gzmonth,#czymc", "#" + dlgId).parent().addClass("inp_70");
    $("#djrq,#bz", "#" + dlgId).change(function () { changeZt(tbId); }).focus(function () { $(this).select(); });
    $("#czymc", "#" + dlgId).attr("disabled", true);
}


//加载窗口grid数据，并计算合计
function loadGridData(tbId, mylist) {
    var count = mylist.length > 5 ? mylist.length : 5;
    var $tbId = $("#" + tbId);
    if (tbId == "Tp050801") {
        var zjCols = $tbId.data("zjCols");                          //增加类、所有列的列名
        var jsCols = $tbId.data("jsCols");                          //减少类、所有列的列名
        var total = { rn: "合计", yfgz: 0 };

        for (var i = 0; i < count; i++) {
            if (mylist[i]) {                                                                         //添加后台数据行
                for (var j = 0; j < zjCols.length; j++) {
                    if (total[zjCols[j]]) {
                        total[zjCols[j]] = total[zjCols[j]] * 1 + mylist[i][zjCols[j]] * 1;
                    } else {
                        total[zjCols[j]] = mylist[i][zjCols[j]] * 1;
                    }
                }
                for (var k = 0; k < jsCols.length; k++) {
                    if (total[jsCols[k]]) {
                        total[jsCols[k]] = total[jsCols[k]] * 1 + mylist[i][jsCols[k]] * 1
                    } else {
                        total[jsCols[k]] = mylist[i][jsCols[k]] * 1;
                    }
                }
                total.yfgz += mylist[i].yfgz * 1;
                $tbId.addRowData(i + 1, mylist[i]);                                   //添加后台数据行
            }
            else {                                                                                  //添加空行
                $tbId.addRowData(i + 1, {});
            }

        }
        $tbId.footerData("set", total, true);

        resizeGridScroll(tbId);

    } else if (tbId == "Tp050802") {
        for (var i = 0; i < count; i++) {
            if (mylist[i]) {
                $tbId.addRowData(i + 1, mylist[i]);
            }
        }
    } else if (tbId == "Tp050803") {
        var yfhj = 0, sfhj = 0, ye = 0;
        for (var i = 0; i < count; i++) {
            if (mylist[i]) {                                                                         //添加后台数据行
                yfhj += isNaN(mylist[i].yfhj * 1) ? 0 : mylist[i].yfhj * 1;
                sfhj += isNaN(mylist[i].sfgz * 1) ? 0 : mylist[i].sfgz * 1;
                ye += isNaN(mylist[i].ye * 1) ? 0 : mylist[i].ye * 1;
                $tbId.addRowData(i + 1, mylist[i]);                                                  //添加后台数据行
            }
            else {                                                                                  //添加空行
                $tbId.addRowData(i + 1, {});
            }
        }
        $tbId.footerData("set", { rn: "合计", yfhj: yfhj, sfgz: sfhj, ye: ye }, true);

        resizeGridScroll(tbId);

    }
    $tbId.data("nextNum", count + 1);

    $tbId = null;
}

//计算footer统计信息==============在grid中调用
function sumGridTotal(tbId) {
    var $tbId = $("#" + tbId);
    var ids = $tbId.getDataIDs();
    if (tbId == "Tp050801") {
        var zjCols = $tbId.data("zjCols");                          //增加类、所有列的列名
        var jsCols = $tbId.data("jsCols");                          //减少类、所有列的列名
        var total = { rn: "合计", yfgz: 0 };

        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            if (item.zydm) {                                                                         //只计算有职员的行
                var zjMoney = 0, jsMoney = 0;
                for (var j = 0; j < zjCols.length; j++) {
                    if (total[zjCols[j]] && !isNaN(total[zjCols[j]] * 1)) {
                        total[zjCols[j]] = total[zjCols[j]] * 1 + item[zjCols[j]] * 1;
                    } else if (item[zjCols[j]] * 1) {
                        total[zjCols[j]] = item[zjCols[j]] * 1;
                    } else {
                        total[zjCols[j]] = "&nbsp;";
                    }
                    zjMoney += item[zjCols[j]] * 1;
                }

                for (var k = 0; k < jsCols.length; k++) {
                    if (total[jsCols[k]] && !isNaN(total[jsCols[k]] * 1)) {
                        total[jsCols[k]] = total[jsCols[k]] * 1 + item[jsCols[k]] * 1;
                    } else if (item[jsCols[k]] * 1) {
                        total[jsCols[k]] = item[jsCols[k]] * 1;
                    } else {
                        total[jsCols[k]] = "&nbsp;";
                    }
                    jsMoney += item[jsCols[k]] * 1;
                }
                var yfgz = zjMoney - jsMoney;
                $tbId.setCell(ids[i], "yfgz", yfgz);
                total.yfgz = yfgz + total.yfgz * 1;
            }
        }
        $tbId.footerData("set", total, true);
    } else if (tbId == "Tp050803") {
        var yfhj = 0, sfgz = 0, ye = 0;
        for (var i = 0; i < ids.length; i++) {
            var item = $tbId.getRowData(ids[i]);
            yfhj += isNaN(item.yfhj * 1) ? 0 : item.yfhj * 1;
            sfgz += isNaN(item.sfgz * 1) ? 0 : item.sfgz * 1;
            ye += isNaN(item.ye * 1) ? 0 : item.ye * 1;
        }
        $tbId.footerData("set", { rn: "合计", yfhj: yfhj, sfgz: sfgz, ye: ye }, true);
    }
    $tbId = null;
}

//改变对话框或数据行的状态
//如果只提供表格id，则只改变窗口的状态标志
function changeZt(tbId, rowId) {
    //工资表
    if (tbId == strTableP050801) {
        $("#" + strDivP050801).data("change", true);
    } else if (tbId == strTableP050802) {               //工资构成设置
        $("#divAdd").data("change", true);
    } else {                                            //工资支付
        $("#" + strDivP050803).data("change", true);
    }
    if (rowId) {
        var $tb = $("#" + tbId);
        var item = $tb.getRowData(rowId);
        if (item.mxguid) {
            $tb.setCell(rowId, "zt", 2);                               //2代表更新
        } else {
            $tb.setCell(rowId, "zt", 1);                               //1代表新增
        }
    }
}

//创建表单元素
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()'/></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;
}