shr.defineClass("shr.customer.gtiit.BatchSubmitShemeBillMySubmissionEditEx", shr.compensation.BatchSubmitShemeBillMySubmissionEdit, {

    initalizeDOM: function () {
        shr.customer.gtiit.BatchSubmitShemeBillMySubmissionEditEx.superClass.initalizeDOM.call(this);

    },
    /**
     * 初始化表格头数据
     * @return {[type]} [description]
     */
    getEditGridColModel: function () {
        var _self = this;
        var submitSchemeId = '';
        var ctrlrole = $('#submitScheme').attr('ctrlrole');

        if (ctrlrole == 'promptBox') {
            submitSchemeId = $('#submitScheme').shrPromptBox('getValue').id;
        } else {
            submitSchemeId = $('#submitScheme').val();
        }
        var datasource = _self.getFieldValue('datasource');
        if (datasource == "") {
            datasource = 2;
        }
        //表格处理
        _self.remoteCall({
            method: "getEditGridColModel",
            param: {
                submitSchemeId: submitSchemeId,
                datasource: datasource
            },
            success: function (data) {
                var colModel = data.colModel;

                for (var i = 0; i < data.colNames.length; i++) {
                    var colName = data.colNames[i];
                    if (colName == "Contract Start Time(合同开始时间)") {
                        data.colNames[i] = "Start Time开始时间）"

                    } else if (colName == "Contract End Time(合同结束时间)") {
                        data.colNames[i] = "End Time（结束时间）"
                    }
                }

                _self.colNames = data.colNames;
                _self.colModel = data.colModel;
                if (colModel) {
                    var col;
                    // 初始化数值类型的列，并且获取到精度，用来做保存数据的格式化
                    var reg = new RegExp('^[sS]\\d+');
                    var decimalPrecision = 0;
                    for (var i = 0, size = colModel.length; i < size; i++) {
                        col = colModel[i];
                        if (col.label == "Contract Start Time(合同开始时间)") {
                            col.label = "Start Time开始时间）"

                        }
                        if (col.label == "Contract End Time(合同结束时间)") {
                            col.label = "End Time（结束时间）"
                        }
                        if (col && col.name && col.name && reg.test(col.name) && "numberfield" == col.formatter) {
                            decimalPrecision = col.editoptions.inputJson.decimalPrecision;
                            _self.numTypeFieldMap[col.name] = decimalPrecision;
                        }
                    }
                }
                _self.setSubmitSchemeDescription(data.description);
                _self.renderGridHeader();
            }
        });
    },
    setGridNameEvent: function () {
        var _self = this;
        $entry = $('#entry');
        $entry.jqGrid("option", {
            afterSaveCell: function (rowid, cellname, value, iRow, iCol, rowData) {
                if (cellname == "startTime" || cellname == "endTime" || cellname == "restStartTime" || cellname == "restEndTime") {
                    //发生日期
                    var effectTime = $("#entry").jqGrid("getCell", rowid, "effectDate");
                    var cellTime = $("#entry").jqGrid("getCell", rowid, cellname);
                    if (effectTime && cellTime) {
                        var effectDate = _self.convertTimeZone(effectTime);
                        let year = effectDate.getFullYear();   // 获取年份（4位数）
                        let month = effectDate.getMonth() + 1; // 获取月份（0-11，需要加1）
                        let day = effectDate.getDate();        // 获取日期（1-31）
                        // 格式化为年月日字符串
                        let formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

                        var cellTimeOfDate = new Date(cellTime);
                        let hours = cellTimeOfDate.getHours();     // 获取小时（0-23）
                        let minutes = cellTimeOfDate.getMinutes(); // 获取分钟（0-59）
                        let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
                        $("#entry").jqGrid("setCell", rowid, cellname, formattedDate + " " + formattedTime);
                    }
                    _self.countHourAndMultiple(rowid);
                }
                if (cellname == "effectDate") {
                    //发生日期
                    var effectTime = $("#entry").jqGrid("getCell", rowid, "effectDate");
                    var effectDate = new Date();
                    if (effectTime) {
                        effectDate = new Date(effectTime);
                    }
                    effectDate = _self.convertTimeZone(effectTime);
                    let year = effectDate.getFullYear();   // 获取年份（4位数）
                    let month = effectDate.getMonth() + 1; // 获取月份（0-11，需要加1）
                    let day = effectDate.getDate();        // 获取日期（1-31）
                    // 格式化为年月日字符串
                    let formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

                    //开始时间
                    var startTime = $("#entry").jqGrid("getCell", rowid, "startTime");
                    //结束时间
                    var endTime = $("#entry").jqGrid("getCell", rowid, "endTime");
                    //休息开始时间
                    var restStartTime = $("#entry").jqGrid("getCell", rowid, "restStartTime");
                    //休息结束时间
                    var restEndTime = $("#entry").jqGrid("getCell", rowid, "restEndTime");
                    if (startTime) {
                        var startTimeOfDate = new Date(startTime);
                        let hours = startTimeOfDate.getHours();     // 获取小时（0-23）
                        let minutes = startTimeOfDate.getMinutes(); // 获取分钟（0-59）
                        let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
                        $("#entry").jqGrid("setCell", rowid, "startTime", formattedDate + " " + formattedTime);
                    }
                    if (endTime) {
                        var endTimeOfDate = new Date(endTime);
                        let hours = endTimeOfDate.getHours();     // 获取小时（0-23）
                        let minutes = endTimeOfDate.getMinutes(); // 获取分钟（0-59）
                        let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
                        $("#entry").jqGrid("setCell", rowid, "endTime", formattedDate + " " + formattedTime);
                    }
                    if (restStartTime) {
                        var restStartTimeOfDate = new Date(restStartTime);
                        let hours = restStartTimeOfDate.getHours();     // 获取小时（0-23）
                        let minutes = restStartTimeOfDate.getMinutes(); // 获取分钟（0-59）
                        let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
                        $("#entry").jqGrid("setCell", rowid, "restStartTime", formattedDate + " " + formattedTime);
                    }
                    if (restEndTime) {
                        var restEndTimeOfDate = new Date(restEndTime);
                        let hours = restEndTimeOfDate.getHours();     // 获取小时（0-23）
                        let minutes = restEndTimeOfDate.getMinutes(); // 获取分钟（0-59）
                        let formattedTime = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}`;
                        $("#entry").jqGrid("setCell", rowid, "restEndTime", formattedDate + " " + formattedTime);
                    }
                    _self.countHourAndMultiple(rowid);
                }
            },
            "afterEditCell": function (rowid, colName, value, iRow, iCol, rowData) {
                if (colName === "person") {
                    var id = "#" + iRow + "_person";
                    var option = $(id).shrPromptBox("option");
                    var subWidgetOptions = option.subWidgetOptions
                    subWidgetOptions.multiselect = true;
                    subWidgetOptions.filter = " hrOrgUnit.id = '" + $("#hrOrgUnit").shrPromptBox("getValue").id + "'";
                    subWidgetOptions.otherParams = { adminOrgId: $("#adminOrg").shrPromptBox("getValue").id, hrOrgUnitId: $("#hrOrgUnit").shrPromptBox("getValue").id };
                    $(id).shrPromptBox("option", {
                        "subWidgetOptions": subWidgetOptions,
                        "onchange": function (e, val) {
                            var personData = val.current;
                            var prevPersonData = val.previous;
                            var length = personData.length;
                            var newRowData = [];
                            for (var i = 0; i < length; i++) {
                                var item = personData[i];
                                var updateItem = {};
                                var oldData = $entry.wafGrid("getRowData", rowid);
                                var startDate;
                                var endDate;
                                var isqw;
                                if (item["empOrgRelation.assignType"].alias == "主要任职") {
                                    isqw = true;
                                    _self.remoteCall({
                                        method: "getDateTime",
                                        param: { personId: item["person.id"], type: "Full" },
                                        async: false,
                                        success: function (data) {
                                            startDate = data.startDate
                                            endDate = data.endDate
                                        },
                                        error: function (error) {
                                            console.log(error);
                                        }
                                    });
                                } else if (item["empOrgRelation.assignType"].alias == "兼职任职") {
                                    isqw = false;
                                    _self.remoteCall({
                                        method: "getDateTime",
                                        param: {
                                            personId: item["person.id"],
                                            adminOrgId: item["adminOrg.id"],
                                            positionId: item["position.id"],
                                            hourlywage: item["empOrgRelation.hourlywage"],
                                            type: "Part"
                                        },
                                        async: false,
                                        success: function (data) {
                                            startDate = data.startDate
                                            endDate = data.endDate
                                        },
                                        error: function (error) {
                                            console.log(error);
                                        }
                                    });
                                }


                                if (i == 0) {
                                    // if(!prevPersonData || prevPersonData.id !== item["person.id"]){
                                    if (item.id !== oldData.cmpEmpORelation.id) {
                                        var beginContractDate, endContractDate;
                                        _self.remoteCall({
                                            method: "getContractDate",
                                            param: { positionId: item["position.id"] },
                                            async: false,
                                            success: function (data) {
                                                beginContractDate = data.beginContractDate;
                                                endContractDate = data.endContractDate;
                                            },
                                            error: function () { }
                                        });

                                        updateItem = {
                                            "number": item["person.number"],
                                            "adminOrgUnit": { id: item["adminOrg.id"], name: item["adminOrg.name"] },
                                            "position": { id: item["position.id"], name: item["position.name"] },
                                            "cmpEmpORelation": { id: item.id, name: item.id },
                                            "person": { id: item["person.id"], name: item["person.name"] },
                                            "submitElement": oldData.submitElement,
                                            "id": oldData.id,
                                            "tempId": oldData.tempId,
                                            "effectDate": oldData.effectDate,
                                            "currency": oldData.currency,
                                            "dealStatus": oldData.dealStatus,
                                            "superiorId": item["parentPerson.id"],
                                            "hourlyWage": item["empOrgRelation.hourlywage"],
                                            "beginContractDate": beginContractDate,
                                            "endContractDate": endContractDate,
                                            "superiorName": item["parentPerson.name"]
                                        }

                                        updateItem.beginContractDate = startDate
                                        updateItem.endContractDate = endDate

                                        var newData = _self.updateRow(updateItem, oldData);
                                        $entry.wafGrid("setRowData", rowid, newData);
                                    } else {

                                        oldData.beginContractDate = startDate
                                        oldData.endContractDate = endDate

                                        $entry.wafGrid("setRowData", rowid, oldData);
                                    }
                                } else {
                                    var beginContractDate, endContractDate;
                                    _self.remoteCall({
                                        method: "getContractDate",
                                        param: { positionId: item["position.id"] },
                                        async: false,
                                        success: function (data) {
                                            beginContractDate = data.beginContractDate;
                                            endContractDate = data.endContractDate;
                                        },
                                        error: function () { }
                                    });

                                    var newData = _self.createNewEntryModel();
                                    newData.number = item["person.number"];
                                    newData.person = { id: item["person.id"], name: item["person.name"] };
                                    newData.adminOrgUnit = { id: item["adminOrg.id"], name: item["adminOrg.name"] };
                                    newData.position = { id: item["position.id"], name: item["position.name"] };
                                    newData.cmpEmpORelation = { id: item.id, name: item.id };

                                    newData.superiorId = item["parentPerson.id"];
                                    newData.hourlyWage = item["empOrgRelation.hourlywage"];
                                    newData.beginContractDate = beginContractDate;
                                    newData.endContractDate = endContractDate;
                                    newData.superiorName = item["parentPerson.name"];

                                    newData.beginContractDate = startDate
                                    newData.endContractDate = endDate
                                    newRowData.push(newData);
                                }
                            }
                            if (newRowData.length) {
                                $entry.jqGrid('addBlockData', 'id', newRowData);
                                $("#entry").jqGrid('setGridHeight', 300);
                            }
                            setTimeout(function () {
                                var frozenScrollTop = $(".frozen-bdiv").scrollTop();
                                $("#entry").parents(".ui-jqgrid-bdiv").scrollTop(frozenScrollTop);
                            })
                            _self.countHourAmount();
                        }
                    })
                }
            }
        });
        $entry.delegate('input', 'focus', function () {
            _self.setCellLength();
        });
    },
    //计算分录的工时和总金额
    countHourAndMultiple: function (rowid) {
        //发生日期
        var effectTime = $("#entry").jqGrid("getCell", rowid, "effectDate");
        //开始时间
        var startTime = $("#entry").jqGrid("getCell", rowid, "startTime");
        //结束时间
        var endTime = $("#entry").jqGrid("getCell", rowid, "endTime");
        //休息开始时间
        var restStartTime = $("#entry").jqGrid("getCell", rowid, "restStartTime");
        //休息结束时间
        var restEndTime = $("#entry").jqGrid("getCell", rowid, "restEndTime");
        if (startTime != "" && endTime != "") {
            var startTimeOfDate = new Date(startTime);
            var endTimeOfDate = new Date(endTime);
            var times = 0;
            if (restStartTime != "" && restEndTime != "") {
                var restStartTimeOfDate = new Date(restStartTime);
                var restEndTimeOfDate = new Date(restEndTime);
                var times = restEndTimeOfDate.getTime() - restStartTimeOfDate.getTime();
                if (times < 0) {
                    times = 0;
                }
            }
            var se = endTimeOfDate.getTime() - startTimeOfDate.getTime() - times;
            //工时
            var workHours = se / (3600 * 1000);
            workHours = workHours.toFixed(2);
            //时薪
            var hourlyWage = $("#entry").jqGrid("getCell", rowid, "hourlyWage");
            if (!hourlyWage) {
                hourlyWage = 0;
            }
            //倍数
            var multiple = 1;
            var note = null;
            //判断是否法定节假日和休息日
            if (effectTime) {
                let date = this.convertTimeZone(effectTime);
                let year = date.getFullYear();   // 获取年份（4位数）
                let month = date.getMonth() + 1; // 获取月份（0-11，需要加1）
                let day = date.getDate();        // 获取日期（1-31）
                // 格式化为年月日字符串
                let formattedDate = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;
                _self.remoteCall({
                    type: "post",
                    async: false,
                    method: "workMultiple",
                    param: { "otDate": formattedDate },
                    success: function (res) {
                        if (res.returnType) {
                            if (res.returnType == "0") {
                                //法定节假日
                                multiple = 4;
                                note = "Statuary Holiday,400%of basic salary";
                            } else if (res.returnType == "1") {
                                //休息日
                                note = "Weekend";
                            }
                        }
                    }
                });
            }

            var amount = workHours * hourlyWage * multiple;
            //工时
            $("#entry").jqGrid("setCell", rowid, "totalWorkHours", workHours);
            //总金额
            $("#entry").jqGrid("setCell", rowid, "totalAmount", amount.toFixed(2));
            //说明
            $("#entry").jqGrid("setCell", rowid, "explain", note);
            this.countHourAmount();
        }
    },
    convertTimeZone: function (date) {
        const inputDate = new Date(date);
        const beijingTime = new Date(inputDate.toLocaleString("en-US", { timeZone: "Asia/Shanghai" }));
        return beijingTime;
    },
    //计算单头的总工时和总金额
    countHourAmount: function () {
        var allRowData = $("#entry").jqGrid("getAllRowData");
        var totalWorkHours = 0;
        var totalAmount = 0;
        for (var i = 0; i < allRowData.length; i++) {
            var workHours = allRowData[i].totalWorkHours;
            var amount = allRowData[i].totalAmount;
            totalWorkHours = Number(totalWorkHours) + Number(workHours);
            totalAmount = Number(totalAmount) + Number(amount);
        }
        this.getField("totalWorkHours").shrNumberField("setValue", totalWorkHours);
        this.getField("totalAmount").shrNumberField("setValue", totalAmount);
    },
    verify: function () {
        //_self.setEntryAttr();
        var tds = $("#entry td[class*='dirty-cell']");
        for (var i = 0; i < tds.length; i++) {
            var cur = $(tds[i]);
            var value;
            if (cur.children().length > 0) {
                value = cur.children().attr('value');
            }
            var type = "NUMBER";
            if (!_self.checkNumValid(value, type)) {
                shr.showWarning({
                    message: $.cmpIntegrateI18n.submitBill.label11 /* 请输入正确格式 */,
                    hideAfter: 9
                });
                $(tds[i]).focus();
                $(tds[i]).css({
                    "border": "solid 2px red"
                });
                return false;
            } else {
                $(tds[i]).css({
                    "border": ""
                });
            }
        }

        //校验开始时间和结束时间不能有重叠
        var allRowData = $("#entry").jqGrid("getAllRowData");
        for (var i = 0; i < allRowData.length; i++) {
            var startTime = new Date(allRowData[i]["startTime"]);
            var endTime = new Date(allRowData[i]["endTime"]);
            for (var j = i + 1; j < allRowData.length; j++) {
                var nextStartTime = new Date(allRowData[j]["startTime"]);
                var nextEndTime = new Date(allRowData[j]["endTime"]);
                if (startTime < nextEndTime && nextStartTime < endTime) {
                    shr.showWarning({ message: "Intersection between start and end times" });
                    return false;
                }
            }
        }

        //校验分录只能有一种职位
        var positionSet = new Set();
        //校验分录只能是同一个直接上级
        var superiorSet = new Set();
        for (var i = 0; i < allRowData.length; i++) {
            if (allRowData[i].position) {
                positionSet.add(allRowData[i].position.id);
            } else {
                positionSet.add("");
            }
            if (allRowData[i].superiorId) {
                superiorSet.add(allRowData[i].superiorId);
            } else {
                superiorSet.add("");
            }
        }
        if (positionSet.size > 1) {
            shr.showWarning({ message: "Entries cannot have data from different positions" });
            return false;
        }
        if (superiorSet.size > 1) {
            shr.showWarning({ message: "The direct supervisor corresponding to the employee position in the entry must be consistent" });
            return false;
        }

        var calSchemeField = "submitScheme_el";
        if (_self.getOperateState() == 'VIEW') {
            calSchemeField = "submitScheme";
        }
        var calSchemeId = $("#" + calSchemeField).val();
        //是否勾选校验方案
        var isPlanCheck = true;
        _self.remoteCall({
            type: "post",
            async: false,
            method: "isTakeCheck",
            param: { calSchemeId: calSchemeId },
            success: function (res) {
                isPlanCheck = res.isPlanCheck;
            }
        });
        if (isPlanCheck) {
            for (var i = 0; i < allRowData.length; i++) {
                var beginContractDate = new Date(allRowData[i]["beginContractDate"]);
                var endContractDate = new Date(allRowData[i]["endContractDate"]);
                var effectDate = new Date(allRowData[i]["effectDate"]);
                if (beginContractDate && endContractDate) {
                    //发生日期要在合同开始和结束日期之间
                    if (effectDate < beginContractDate || effectDate > endContractDate) {
                        shr.showWarning({ message: "The occurrence date should be between the start and end dates of the contract" });
                        return false;
                    }
                }
            }

            var flag = true;
            _self.remoteCall({
                type: "post",
                async: false,
                method: "getInductionDate",
                param: {},
                success: function (res) {
                    if (res.enterDate) {
                        var enterDate = new Date(res.enterDate);
                        for (var i = 0; i < allRowData.length; i++) {
                            var effectDate = new Date(allRowData[i]["effectDate"]);
                            //发生日期不能小于入职日期
                            if (effectDate < enterDate) {
                                shr.showWarning({ message: "The occurrence date filled in by the employee cannot be earlier than the start date" });
                                flag = false;
                            }
                        }
                    }
                }
            });
            if (!flag) {
                return flag;
            }
        }

        return true;
    },
    /**
     * 删除行
     */
    deleteRowAction: function (event) {
        var $editGrid = this.getEditGrid(event.currentTarget);
        var submitSchemeId = '';
        var ctrlrole = $('#submitScheme').attr('ctrlrole');
        if (ctrlrole == 'promptBox') {
            submitSchemeId = $('#submitScheme').shrPromptBox('getValue').id;
        } else {
            submitSchemeId = $('#submitScheme').val();
        }
        var ids = $editGrid.jqGrid('getSelectedRows');

        if (!ids || ids.length === 0) {
            shr.showWarning({ message: $.cmpIntegrateI18n.common.selectRowMust /* 请先选择表格中的数据！ */ });
            return;
        }

        var deleteRowIds = "";
        if (ids) {
            for (var i = ids.length - 1; i >= 0; i--) {
                deleteRowIds += ids[i] + ",";
                $editGrid.jqGrid('delRow', ids[i]);
            }
            //新增页面，清除缓存数据
            $("#entry")[0].p.data = [];
            this.clearDelEntryIdsFromDB(submitSchemeId, deleteRowIds);
        }
        var billId = $("#id").val();
        //删除分录时如果这条数据已在数据库中，则会直接删除数据库记录，所以要重新计算单头的总工时和总金额
        _self.remoteCall({
            type: "post",
            async: false,
            method: "countHourAmount",
            param: { "billId": billId },
            success: function (res) {

            }
        });
        this.countHourAmount();
    },
    submitAction: function (event) {
        var _self = this;
        if (_self.validate() && _self.verify()) {

            var allRowData = $("#entry").jqGrid("getAllRowData");
            // 获取当前日期
            let currentDate = new Date();
            // 获取本月的第一天
            let firstDayOfCurrentMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
            // 获取上个月的第一天
            let firstDayOfLastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);
            if (currentDate.getMonth() === 0) {
                // 如果当前月份为1月，需要调整为上一年的12月
                firstDayOfLastMonth.setFullYear(currentDate.getFullYear() - 1);
            }

            var calSchemeField = "submitScheme_el";
            if (_self.getOperateState() == 'VIEW') {
                calSchemeField = "submitScheme";
            }
            var calSchemeId = $("#" + calSchemeField).val();

            var isPlanCheck = true;
            var isCurrentDepart = true;
            //获取是否勾选了 校验方案和离职方案
            _self.remoteCall({
                type: "post",
                async: false,
                method: "isTakeCheck",
                param: { calSchemeId: calSchemeId },
                success: function (res) {
                    isPlanCheck = res.isPlanCheck;
                    isCurrentDepart = res.isCurrentDepart;
                }
            });

            //勾选离职方案
            if (isCurrentDepart) {
                var isDepartMonth = true;
                var cmpOrgRelationId = "";
                for (var i = 0; i < allRowData.length; i++) {
                    cmpOrgRelationId = allRowData[i].cmpEmpORelation.id;
                }
                //判断当月是否有离职生效日期或兼职失效日期在本月的数据
                _self.remoteCall({
                    type: "post",
                    async: false,
                    method: "checkDepartDate",
                    param: { cmpOrgRelationId: cmpOrgRelationId },
                    success: function (res) {
                        isDepartMonth = res.flag;
                    }
                });
                //勾选离职方案后只能提交当月的数据
                if (isDepartMonth) {
                    for (var i = 0; i < allRowData.length; i++) {
                        var effectDate = new Date(allRowData[i]["effectDate"]);
                        if (!(effectDate.getFullYear() == currentDate.getFullYear() && effectDate.getMonth() == currentDate.getMonth())) {
                            shr.showWarning({ message: "Only allow submission of the occurrence date of the current month" });
                            return false;
                        }
                    }
                } else {
                    //当月没有离职或兼职失效数据时不允许提交
                    shr.showWarning({ message: "The selected position does not have a resignation form that takes effect this month, or the expiration date of the part-time job is not within this month, so it cannot be submitted" });
                    return false;
                }
            } else if (isPlanCheck) {
                //校验XX号之后不允许提交
                var submitDateMessage = '';
                _self.remoteCall({
                    type: "post",
                    async: false,
                    method: "checkSumbitDate",
                    param: {},
                    success: function (res) {
                        submitDateMessage = res.resultMessage;
                    }
                });
                if (submitDateMessage) {
                    shr.showWarning({ message: submitDateMessage });
                    return false;
                }

                //勾选校验方案只能提交上月的数据
                for (var i = 0; i < allRowData.length; i++) {
                    var effectDate = new Date(allRowData[i]["effectDate"]);
                    if (!(effectDate >= firstDayOfLastMonth && effectDate < firstDayOfCurrentMonth)) {
                        shr.showWarning({ message: "Only allow submission of work hours from the previous month" });
                        return false;
                    }
                }
            }

            _self.preVerify(function () {
                $.extend($.verifyRuleTool, _self.getVerifyOptions(submitNodeId))
                $.verifyRuleTool.afterVeriyCallBack = function () {
                    shr.showConfirm($.shrI18n.common.tips.submitConfirm, function () {
                        _self.doSubmit(event, 'submit');
                    });
                };
                $.verifyRuleTool.verifyInto();
                $.verifyRuleTool.ip = "submitShemeBill"
            }, 'submit')
        }

    },
    initForm: function () {
        var _self = this;
        _self.assembleNewModelIdForAddNewOperate();
        _self.setInitData();
        _self.addCopyBtn();
        _self.ChangeSubmitScheme_event();
        _self.setSubmitSchemeState();
        _self.auditPageAdjust();
        shr.loadScript("/shr/addon/compensation/web/js/integrate/base/submitverify/cmpVerifyRuleTool.js")

        //编辑和查看状态下初始化表格
        if (_self.operateState == 'VIEW' || _self.operateState == 'EDIT') {
            _self.getEditGridColModel();
            _self.initF7TypeFieldArr();
        }

        if (_self.operateState == 'ADDNEW' || _self.operateState == 'EDIT') {
            _self.setSubmitSchemeF7Filter();
            _self.setDescriptionLength();
        }
        if (_self.operateState == 'ADDNEW' || _self.operateState == 'VIEW') {
            $("#availableBudget").hide();
        }

        if (_self.operateState == 'VIEW') {
            // 暂时先取消导出功能
            _self.addViewBtn();
            //排除员工自助提报的情景
            if ('1' != $("#datasource").val()) {
                _self.initJumpToPageButton();
            }
        }
        // 字段授权
        _self.checkNoPermFields();
        // 根据提报方案是否关联了预算额度模板，来决定费用承担组织、预算年度，费用类型是否展示
        _self.monitorBudget();
    },
    renderGridHeader: function (islocaldata) {
        var _self = this;
        var colModel = _self.colModel;
        var colNames = _self.colNames;
        var $entry = $('#entry');
        //如果表头没数据，默认展示序号
        if (!(colNames && colNames[0]) || !(colModel && colModel[0])) {
            colNames = ['id'];
            colModel = [{
                "name": "id",
                "label": "id",
                "frozen": false,
                "width": 150,
                "align": "left",
                "hidden": true,
                "key": true,
                "editable": false,
                "sorttype": "",
                "sortable": false,
                "classes": "disabled"
            }];
        }

        var ctrlrole = $entry.attr("ctrlrole");
        //表格已初始化,销毁
        if (ctrlrole) {
            $entry.jqGrid('gridUnload');
        }

        var columnModel = '';
        var hasFrozenColumn = false;
        //拼接columnModel字符串
        if (colModel && colModel[0]) {
            colModel.forEach(function (element, index) {
                if (element['frozen']) {
                    hasFrozenColumn = true;
                }
                columnModel += element.name;
                if (index != colModel.length - 1) {
                    columnModel += ',';
                }
            });
        }

        // var grid_readonly = _self.operateState == 'VIEW';
        var grid_readonly = _self.operateState === 'VIEW' || _self.operateState === 'EDIT' || _self.operateState === 'ADDNEW';
        var grid_celledit = _self.operateState === 'EDIT' || _self.operateState === 'ADDNEW';

        var url = _self.getGridDataRequestURL();
        var dataGrid_option = {
            url: url,
            datatype: islocaldata == '1' ? "local" : "json",
            colNames: colNames,
            jsonReader: {
                repeatitems: false
            },
            sorterItems: "",
            colModel: colModel,
            postData: $entry[0].p.postData,
            customPager: '#gridPager',
            hasPager: grid_readonly,
            cellEdit: grid_celledit,
            height: 'auto',
            rowList: [50, 100, 200, 500],
            autowidth: true,
            viewrecords: true,
            cellsubmit: "clientArray",
            multiselect: true,
            _type_: "EditGrid",
            shrinkToFit: false,
            mtype: "get",
            recordtext: '({0}-{1})/{2}',
            gridview: true,
            pginput: true,
            rownumbers: true,
            footerrow: true,
            userDataOnFooter: true,
            clientFooter: false,
            serverFooter: false,
            sumColModel: [],
            pagerpos: 'center',
            recordpos: 'left',
            pginputpos: 'right',
            keyOptions: {
                addNewRowForLastCell: false,
                loop: true
            }
        };
        //查看模式分页查询,编辑默认查全部
        if (grid_readonly) {
            dataGrid_option.rowNum = 50;
        } else {
            dataGrid_option.rowNum = 100000;
        }
        dataGrid_option.loadComplete = function (ret) {
            $("#entry")[0].__isDirty = false;
            if (grid_readonly) {
                //初始化分页
                if (!$("#gridPager")[0]) {
                    var pagerDiv = '<div id="gridPager"></div>';
                    if ($('.editGrid-toolbar')[0]) {
                        $('.editGrid-toolbar').after(pagerDiv);
                    } else {
                        $('#entry_cont').prepend(pagerDiv);
                    }
                    $("#entry").setCustomPager("#gridPager");
                }
                var datas = $("#entry").jqGrid("getRowData");
                if (datas && datas.length > 8) {   //表格数据超过一定数量,限制高度
                    $("#entry").jqGrid('setGridHeight', 300);
                }
                shr.setIframeHeight();
            }

        };

        dataGrid_option.onPaging = function () {
        }

        dataGrid_option.beforeReloadGrid = function () {
            if (!grid_readonly) {
                waf("#entry").find('tr.selected-row').click();
                var data = waf("#entry").jqGrid('getGridParam', 'data');
                data.length = 0;
                waf("#entry").jqGrid('setGridParam', { data: $("#entry").jqGrid('getAllPageData'), datatype: 'local' });
            }
            shr.setIframeHeight();

        }
        //选择表格前设置姓名过滤条件
        dataGrid_option.beforeSelectRow = function () {
            _self.setNameF7Filter();
        }
        //审批时有滚动条时，把右侧DIV右移了一些挡住了列表的滚动条,现在先给列表的父标签一个右内边距，这样就不会被挡道。
        $('#entry_cont').css('padding-right', '20px')
        waf("#entry").jqGrid(dataGrid_option).jqGrid("setFrozenColumns");

        waf("#entry").jqGrid("resizeGrid", {
            base: waf("#entry"),
            offset: 0
        });
        waf(window).resize(function () {
            waf.ieHack.hackResize(function (e) {
                waf("#entry").jqGrid("resizeGrid", {
                    base: waf("#entry"),
                    offset: 0
                });
            }, waf("#entry"));
        });

        $entry.jqGrid(dataGrid_option).trigger('reloadGrid');

        //查看状态初始化分页
        if (grid_readonly) {
            _self.initPage();
        }

        if (_self.operateState == 'ADDNEW' || _self.operateState == 'EDIT') {
            _self.setGridNameEvent();
        }
        if (!$("#entry_searchBar").length) {
            _self.initCmpEntrySearchBar();
        }
    },
    /**
     * 分录增加复制按钮
     */
    addCopyBtn: function () {
        var _self = this;
        var str = [];
        str.push('<button id="copyRow" type="button" onclick="jsBinder.copyRowAction" name="copyRow" class="shrbtn">');
        str.push('Copy');
        str.push('</button>');
        str.push('<script>');
        str.push('$(function() {');
        str.push('  $("#copyRow").shrButton({');
        str.push('  actionBinding: "copyRowAction",');
        str.push('  subAction: "",');
        str.push('  customData: "",');
        str.push('  permItemId:""');
        str.push('  });');
        str.push('});');
        str.push('</script>');
        $("#deleteRow_entry").after(str.join(""));
    },
    copyRowAction: function (event) {
        var $editGrid = this.getEditGrid(event.currentTarget);
        var ids = $editGrid.jqGrid('getSelectedRows');
        if (!ids || ids.length === 0) {
            shr.showWarning({ message: $.cmpIntegrateI18n.common.selectRowMust /* 请先选择表格中的数据！ */ });
            return;
        }

        for (var i = 0; i < ids.length; i++) {
            var getRowRealData = $("#entry").jqGrid("getRowRealData", ids[i]);
            getRowRealData.id = '';
            $("#entry").jqGrid("addRow", { data: getRowRealData });
        }


    }
});