shr.defineClass("shr.customer.gtiit.AtsOverTimeBillBatchEditEx", shr.ats.AtsOverTimeBillBatchEdit, {

    initalizeDOM:function(){
        shr.customer.gtiit.AtsOverTimeBillBatchEditEx.superClass.initalizeDOM.call(this);
        var that = this;
        var entries_cont = waf("#entries");
        entries_cont.jqGrid("option", {
             
            onChange: function (rowid, cellname, value, iRow, iCol) {
                console.log(rowid, cellname, value, iRow, iCol, 123123);
            },
              // 其他配置...
            beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
                console.log("进入编辑前:", rowid, cellname, value, iRow, iCol);
               
            },
   
            beforeSaveCell: function (
                rowid,
                cellname,
                value,
                iRow,
                iCol
            ) {
               
            },
            afterSaveCell: function (rowid, cellname, value, iRow, iCol) {
          
                if (value["adminOrgUnit.id"]) {
                    $("#entries").jqGrid(
                        "setCell",
                        rowid,
                        "adminOrgUnit.id",
                        value["adminOrgUnit.id"]
                    );
                }

                that.removePreShowError(rowid);
                if (cellname == "otDate") {
                    var val = value;
                    if (val.length <= 10) {
                        val = val + " 00:00:00";
                    }
                    val &&
                        $("#entries").jqGrid(
                            "setCell",
                            rowid,
                            "startTime",
                            val
                        );
                    val &&
                        $("#entries").jqGrid(
                            "setCell",
                            rowid,
                            "endTime",
                            val
                        );
                    that.changeOverTimeType(rowid);
                    that.calRestTimeLen(rowid);
                    that.getOTContrlParams(rowid);
                }

                if (cellname == "otType") {
                    that.changeOTCompens(rowid);
                    that.countOvertimeHourAction();
                }
                // 添加 开始时间  结束时间   休息时长(分钟) 响应时间
                if (
                    cellname == "startTime" ||
                    cellname == "endTime" ||
                    cellname == "restTime"
                ) {
                    if (cellname != "restTime") {
                        that.calRestTimeLen(rowid);
                    }
                    that.calculateOTtimes(rowid);
                }
                if (cellname == "person") {
                    that.calRestTimeLen(rowid);
                    that.getOTContrlParams(rowid);
                }
                if (cellname == "applyOTTime") {
                    // 加班小时数  发生改变就给予提示
                    that.changOtTimeTipInfo(rowid);
                    that.countOvertimeHourAction();
                }
                if (cellname == "otCompens") {
                    that.countOvertimeHourAction();
                }
                if (
                    cellname == "restStartTime" ||
                    cellname == "restStartTime2" ||
                    cellname == "restEndTime" ||
                    cellname == "restEndTime2"
                ) {
                    //计算休息时间，加班时间
                    var startTime = $("#entries").jqGrid(
                        "getCell",
                        rowid,
                        "startTime"
                    );
                    var endTime = $("#entries").jqGrid(
                        "getCell",
                        rowid,
                        "endTime"
                    );
                    var restStartTime = $("#entries").jqGrid(
                        "getCell",
                        rowid,
                        "restStartTime"
                    );
                    var restEndTime = $("#entries").jqGrid(
                        "getCell",
                        rowid,
                        "restEndTime"
                    );
                    var restStartTime2 = $("#entries").jqGrid(
                        "getCell",
                        rowid,
                        "restStartTime2"
                    );
                    var restEndTime2 = $("#entries").jqGrid(
                        "getCell",
                        rowid,
                        "restEndTime2"
                    );
                    if (startTime == "" || endTime == "") {
                        return;
                    }
                    
                    var totalRestTime = 0;
                    var totalRestTimeLong = 0;
                    var restStartTimeOfDate;
                    var restEndTimeOfDate;
                    if(shr.getBowserInfo().browser === 'IE' || shr.getBowserInfo().browser === 'Safari'){
                        restStartTime = restStartTime.replace(/-/g,'/');
                        restEndTime = restEndTime.replace(/-/g,'/');
                        restStartTime2 = restStartTime2.replace(/-/g,'/');
                        restEndTime2 = restEndTime2.replace(/-/g,'/');
                    }
                    if (restStartTime != "" && restEndTime != "") {
                        restStartTimeOfDate = new Date(restStartTime);
                        restEndTimeOfDate = new Date(restEndTime);
                        var times =
                            restEndTimeOfDate.getTime() -
                            restStartTimeOfDate.getTime();
                        if (times < 0) {
                            times = 0;
                        }
                        totalRestTimeLong += times;
                        times = times / 1000 / 60;
                        totalRestTime += times;
                    }
                    if (restStartTime2 != "" && restEndTime2 != "") {
                        var restStartTime2OfDate = new Date(restStartTime2);
                        var restEndTime2OfDate = new Date(restEndTime2);
                        if (
                            (restStartTime != "" &&
                                restEndTime2OfDate.getTime() >
                                    restStartTimeOfDate.getTime() &&
                                restStartTimeOfDate.getTime() >=
                                    restStartTime2OfDate.getTime()) ||
                            (restEndTime != "" &&
                                restEndTimeOfDate.getTime() <=
                                    restEndTime2OfDate.getTime() &&
                                restStartTime2OfDate.getTime() <
                                    restEndTimeOfDate.getTime()) ||
                            (restStartTime != "" &&
                                restEndTime != "" &&
                                restEndTimeOfDate.getTime() >=
                                    restEndTime2OfDate.getTime() &&
                                restStartTime2OfDate.getTime() >=
                                    restStartTimeOfDate.getTime())
                        ) {
                            //时间有交叉
                            $("#entries").jqGrid(
                                "setCell",
                                rowid,
                                "restEndTime2",
                                restStartTime2
                            );
                        } else {
                            var times =
                                restEndTime2OfDate.getTime() -
                                restStartTime2OfDate.getTime();
                            if (times < 0) {
                                times = 0;
                            }
                            totalRestTimeLong += times;
                            times = times / 1000 / 60;
                            totalRestTime += times;
                        }
                    }
                    var t1 = totalRestTime.toFixed(
                        atsMlUtile.getSysDecimalPlace()
                    );
                    $("#entries").jqGrid("setCell", rowid, "restTime", t1);
                    var startTime = NewDate(startTime + ":00");
                    var endTime = NewDate(endTime + ":00");
                    var se =
                        endTime.getTime() -
                        startTime.getTime() -
                        totalRestTimeLong; // 毫秒
                    var tfl = se / (3600 * 1000);
                    $("#entries").jqGrid(
                        "setCell",
                        rowid,
                        "applyOTTime",
                        tfl
                    );
                    that.getOTContrlParams(rowid);
                    that.countOvertimeHourAction();
                }
            },
            afterEditCell: function (rowid, cellname, value, iRow, iCol) {
                if (
                    cellname == "otType" &&
                    that.OTContrlParams[rowid] &&
                    that.OTContrlParams[rowid].isOtrolByDateType
                ) {
                    $("#" + iRow + "_otType").shrPromptBox("disable");
                }
                if (cellname == "otCompens") {
                    if (that.filter[rowid] == undefined) {
                        // R20221006-0542 修复选择加班费后 再点击“补偿方式”F7就变成了调休的问题
                        // that.changeOTCompens(rowid);
                    }
                    if (that.filter[rowid]) {
                        //                      $("#"+rowid+"_otCompens").shrPromptBox("setFilter",that.filter[rowid]);
                        $(
                            "#" +
                                $("#entries").jqGrid(
                                    "getCell",
                                    rowid,
                                    "rn"
                                ) +
                                "_otCompens"
                        ).shrPromptBox("setFilter", that.filter[rowid]);
                    }
                }
                if (cellname == "person") {
                    var hrOrgUnitId = $("#hrOrgUnit_el").val();
                    $("#" + rowid + "_person")
                        .shrPromptBox()
                        .attr("data-params", hrOrgUnitId);
                    $("#" + iRow + "_person").shrPromptBox("option", {
                        onchange: function (e, value) {
                            $("#entries").jqGrid(
                                "setCell",
                                rowid,
                                "person.number",
                                value.current
                                    ? value.current["person.number"]
                                    : ""
                            );
                        }
                    });

                }
                if(cellname == "attAdminOrgUnit"){
                    var personId = $("#entries").jqGrid("getCell", rowid, "person").id;
                    var attendanceDate = $("#entries").jqGrid("getCell", rowid, "otDate");

                    if(!(personId && attendanceDate)){
                        shr.showInfo({message: jsBizMultLan.atsManager_atsOverTimeBillEdit_YM_999});
                        return false;
                    }else{
                        //$("#"+rowid+"_attPosition").shrPromptBox().attr("data-params", adminOrg);
                        $("#"+iRow+"_attAdminOrgUnit").shrPromptBox("setOtherParams", {
                            personId: personId,
                            attendanceDate: attendanceDate
                        });
                    }


                }


            }
        });
       this.updateCalWidth();
    },
    updateCalWidth:function(inWidth){
        // 获取jqGrid的引用
        var $grid = $("#entries");
        // 获取列模型
        var colModel = $grid.jqGrid('getGridParam', 'colModel');
        
        // 找到 'startTime' 列的索引
        var columnIndex = -1;
        $.each(colModel, function (i, col) {
            if (col.name === 'startTime' || col.name === 'endTime' 
                || col.name === 'restStartTime' || col.name === 'restEndTime' 
                || col.name === 'restStartTime2' || col.name === 'restEndTime2'
                || col.name === 'realStartTime' || col.name === 'realEndTime') {
                columnIndex = i;
                // 设置新的列宽
                var newWidth = inWidth?inWidth:75; // 新的宽度值
            
                // 调整列标题的宽度
                $('.ui-jqgrid-labels > th:eq(' + columnIndex + ')').css('width', newWidth + 'px');
            
                // 调整列内容的宽度
                $grid.find('tbody tr').each(function () {
                    var $td = $(this).find('td:eq(' + columnIndex + ')');
                    $td.css('width', newWidth + 'px');
                });
            
                // 调整jqGrid的列宽（确保jqGrid内部状态更新）
                $grid.jqGrid('setColProp', col.name, { width: newWidth });
            }
        });
    },
    calculateOTtimes: function (rowid) {
        var startTime = $("#entries").jqGrid("getCell", rowid, "startTime");
        var endTime = $("#entries").jqGrid("getCell", rowid, "endTime");
        var restTime = $("#entries").jqGrid("getCell", rowid, "restTime");

        if (startTime == "[object Object]") {
            $("#" + rowid)
                .find("td")
                .eq("5")
                .text("");
            $("#" + rowid)
                .find("td")
                .eq("5")
                .attr("title", "");
        }
        if (endTime == "[object Object]") {
            $("#" + rowid)
                .find("td")
                .eq("6")
                .text("");
            $("#" + rowid)
                .find("td")
                .eq("6")
                .attr("title", "");
        }

        if (startTime != "" && endTime != "") {
            var restVal = 0;
            if (restTime != "" && /^[0-9]*$/.test(restTime)) {
                restVal = restTime; // 分钟数
            }
            var startTime = NewDate(startTime + ":00");
            var endTime = NewDate(endTime + ":00");
            var se =
                endTime.getTime() -
                startTime.getTime() -
                restVal * 1000 * 60; // 毫秒
            var tfl = se / (3600 * 1000);
            $("#entries").jqGrid(
                "setCell",
                rowid,
                "applyOTTime",
                tfl.toFixed(fixedNum)
            );
            this.countOvertimeHourAction();
        }
    },
    getOverTimeType: function (rowid, otDate, personId) {
        var _self = this;
        var tDate = otDate;
        var url =
            shr.getContextPath() +
            "/dynamic.do?method=getOverTimeTypeAndOtCompens";
        url +=
            "&otDate=" +
            encodeURIComponent(otDate) +
            "&personId=" +
            encodeURIComponent(personId)+"&uipk="+shr.getUrlRequestParam('uipk');
        $.ajax({
            url: url,
            async: false,
            success: function (response) {
                if (
                    response.otTypeValue != null &&
                    response.otTypeValue != undefined &&
                    response.otTypeValue != ""
                ) {
                    var responseObejct = {
                        id: response.otTypeValue,
                        name: response.otTypeText
                    };
                    if (_self.isOtTypeEffective(response.otTypeValue)) {
                        // $('#entries').restoreCell(rowid,4); // 先恢复单元格状态再重新赋值，可以避免
                        $("#entries").jqGrid(
                            "setCell",
                            rowid,
                            "otType",
                            responseObejct
                        );
                        //设置该加班类型的补偿方式过滤
                        var otCompensIds = _self.getOTCompensByOTType(
                            personId,
                            response.otTypeValue,
                            tDate
                        );
                        if (otCompensIds) {
                            var otCompensIdsStr = _self
                                .getOTCompensByOTType(
                                    personId,
                                    response.otTypeValue,
                                    tDate
                                )
                                .replace(/(,)/g, "','");
                            _self.filter[rowid] =
                                "BaseInfo.id in ('" +
                                otCompensIdsStr +
                                "')";
                        }

                        var compens = response.compensInfo;
                        if (compens != null) {
                            var defaultJson = {
                                id: compens.id,
                                name: compens.name
                            };
                            $("#entries").jqGrid(
                                "setCell",
                                rowid,
                                "otCompens",
                                defaultJson
                            );
                        }
                    } else {
                        $("#entries").jqGrid(
                            "setCell",
                            rowid,
                            "otType",
                            null
                        );
                    }
                }else{
                    $("#entries").jqGrid('setCell',rowid,"otType",null);
                }
            },
            error: function (response) {}
        });
        _self.changeWorkType(rowid);
        _self.countOvertimeHourAction();
    },
    changeOTCompens: function (rowid) {
        var that = this;
        var otCompensId;
        if (!$("#entries").jqGrid("getCell", rowid, "otType")) {
            return;
        } else {
            otTypeId = $("#entries").jqGrid("getCell", rowid, "otType").id;
        }

        if (!$("#entries").jqGrid("getCell", rowid, "person")) {
            return;
        } else {
            var personId = $("#entries").jqGrid("getCell", rowid, "person").id;
        }

        if (!$("#entries").jqGrid("getCell", rowid, "otDate")) {
            return;
        } else {
            var otDate = $("#entries").jqGrid("getCell", rowid, "otDate");
        }
        var otCompensIds = that.getOTCompensByOTTypes(personId, otTypeId);
        var url =
            shr.getContextPath() +
            "/dynamic.do";
        that.remoteCall({
            type: "post",
            method: "getDefaultOTCompens",
            url: url,
            param: {
                personId: personId,
                otTypeId: otTypeId,
                otDate: otDate
            },
            async: false,
            success: function (res) {
                var info = res;
                if (info.defaultId == "" || info.defaultId == undefined) {
                    shr.showWarning({
                        message:
                            jsBizMultLan.atsManager_atsOverTimeBillBatchEdit_i18n_28
                    });
                } else {
                    var defaultOTCompens = {
                        id: info.defaultId,
                        name: info.defaultName
                    };
                    $("#entries").jqGrid(
                        "setCell",
                        rowid,
                        "otCompens",
                        defaultOTCompens
                    );
                    if (otCompensIds) {
                        var otCompensIdsStr = otCompensIds.replace(
                            /(,)/g,
                            "','"
                        );
                        that.filter[rowid] =
                            "BaseInfo.id in ('" + otCompensIdsStr + "')";
                    }
                }
            }
        });
        that.countOvertimeHourAction();
    },
    verify: function () {
        var _self = this;
        var obj = $("#entries").jqGrid("getRowData");
        var errorString = "";
        var errorFlag = 0;
        var billerrorString = "";
        if (obj.length == 0) {
            shr.showWarning({
                message:
                    jsBizMultLan.atsManager_atsOverTimeBillBatchEdit_i18n_7
            });
            return false;
        }
        if (!_self.checkRowIsOver()) {
            //          closeLoader();
            return false;
        }

        _rowMap = {};

        openLoader(
            1,
            jsBizMultLan.atsManager_atsOverTimeBillBatchEdit_i18n_29
        );

        jQuery(obj).each(function (n) {
            errorString = _self.checkEveryRow(n + 1, this);

            if (errorString) {
                _self.preShowError(
                    n + 1,
                    this.person.name + " " + errorString
                );
                billerrorString =
                    billerrorString +
                    shr.formatMsg(
                        jsBizMultLan.atsManager_atsOverTimeBillBatchEdit_i18n_44,
                        [n + 1]
                    ) +
                    errorString;

                errorFlag = 1;
            }
        });
        if (errorString && errorString != "") {
            var showMes = "";
            showMes += billerrorString.replace(/。/g, "。</br>");
            shr.showWarning({ message: showMes });
            closeLoader();
            return false;
        }

        errorString = _self.validateOTEntry();
        if (errorString && errorString != "") {
            shr.showWarning({ message: errorString });
            closeLoader();
            return false;
        }

        var hasOtType = _self.checkOtType();
        if (!hasOtType) {
            return false;
        }

        if (errorFlag == 0) {
            //工作流审批界面，加班补提控制。
            var boo = true;
            boo = _self.validateIsFillOtVerify();
            closeLoader();
            // if(!_self.checkOtDate()){
            //     return false;
            // }
            return boo;
        } else {
            closeLoader();
            return false;
        }
    },
    changeWorkType: function (rowid) {
        var that = this;
        var otDate;
        if (!$("#entries").jqGrid("getCell", rowid, "otDate")) {
            return;
        } else {
            otDate = $("#entries").jqGrid("getCell", rowid, "otDate");
        }

        _self.remoteCall({
            type:"post",
            async: false,
            method:"workMultiple",
            param:{otDate:otDate},
            success:function(res){
                if(res.otTypeValue){
                    var responseObejct = {id: res.otTypeValue,name: res.otTypeText};
                    $("#entries").jqGrid("setCell",rowid,"otType",responseObejct);
                }
            }
        });

        var otType = $("#entries").jqGrid("getCell",rowid,"otType");
        if(!otType){
            _self.remoteCall({
                type:"post",
                async: false,
                method:"jobType",
                param:{otDate:otDate},
                success:function(res){
                    if(res.otTypeValue){
                        var responseObejct = {id: res.otTypeValue,name: res.otTypeText};
                        $("#entries").jqGrid("setCell",rowid,"otType",responseObejct);
                    }
                }
            });
        }
    },

    /**
     * 删除行
     */
    deleteRowAction: function(event) {
        var $editGrid = this.getEditGrid(event.currentTarget);
        var ids = $editGrid.jqGrid('getSelectedRows');
        if (ids.length > 0) {
            for (var i = ids.length - 1; i >= 0; i--) {
                $editGrid.jqGrid('delRow', ids[i]);
            }
            this.countOvertimeHourAction();
        }else{
            shr.showInfo({
                message: $.shrI18n.common.tips.chooseTableDataFirst,
                hideAfter: 3
            });
        }
    },

    countOvertimeHourAction:function(){
        var allRowData = $("#entries").jqGrid("getAllRowData");
        var length = allRowData.length;
        var weekdayHour = 0;//工作日加班小时数
        var restdayHour = 0;//休息日加班小时数
        var holidayHour = 0;//法定节假日加班小时数
        var totalDuration = 0;//加班总时长
        var compensatoryTotal = 0;//调休加班总时长
        var totalOvertimePay = 0;//加班费加班总时长
        for(var i=0; i<length; i++){
            var otType = allRowData[i].otType.id;
            var applyOTTime = allRowData[i].applyOTTime;
            var otCompens = allRowData[i].otCompens.id;
            if(applyOTTime == ""){
                continue;
            }
            if(otType == "rBy0u1YgQ9C1OxcM85mxyY6C/nU="){
                weekdayHour = Number(weekdayHour)+Number(applyOTTime);
            }else if(otType == "zr+ur5D4RA+2bdVZ2VPqp46C/nU="){
                restdayHour = Number(restdayHour)+Number(applyOTTime);
            }else if(otType == "sRWUOt7sRpOY0TCo6NMqGY6C/nU="){
                holidayHour = Number(holidayHour)+Number(applyOTTime);
            }
            if(otCompens == "AERg0TIcSnaM40EKvJCdRKlrTmA="){
                compensatoryTotal = Number(compensatoryTotal)+Number(applyOTTime);
            }else if(otCompens == "zkbt5bMLQ3ehUivmKbtBOqlrTmA="){
                totalOvertimePay = Number(totalOvertimePay)+Number(applyOTTime);
            }
        }
        totalDuration = Number(weekdayHour)+Number(restdayHour)+Number(holidayHour);
        // $("#weekdayHour").val(weekdayHour);
        // $("#restdayHour").val(restdayHour);
        // $("#holidayHour").val(holidayHour);
        // $("#totalDuration").val(totalDuration);
        // $("#compensatoryTotal").val(compensatoryTotal);
        // $("#totalOvertimePay").val(totalOvertimePay);

        this.getField("weekdayHour").shrNumberField("setValue",weekdayHour);
        this.getField("restdayHour").shrNumberField("setValue",restdayHour);
        this.getField("holidayHour").shrNumberField("setValue",holidayHour);
        this.getField("totalDuration").shrNumberField("setValue",totalDuration);
        this.getField("compensatoryTotal").shrNumberField("setValue",compensatoryTotal);
        this.getField("totalOvertimePay").shrNumberField("setValue",totalOvertimePay);
    },
    checkOtDate:function(){
        var allRowData = $("#entries").jqGrid("getAllRowData");
        for(var i=0; i<allRowData.length; i++){
            var otDate = allRowData[i].otDate;
            otDate  = new Date(otDate);
            const currentDate = new Date();
            const lastMonthDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
            var lastYear = lastMonthDate.getFullYear();
            var lastMonth = lastMonthDate.getMonth();

            if(otDate.getMonth() != lastMonth || otDate.getFullYear() != lastYear){
                shr.showWarning({message: "Only overtime records with the previous month's overtime date can be submitted for the current month"});
                return false;
            }
        }
        return true;
    }


});
waf.defineCustomeClass("cellformatter.shrTextArea", cellformatter.defaultFormatter, {
    unformat: function (cell, rowId) {
        return $.trim($(cell).text());
    },
    format: function (cellval, rwd) {
        if (!$.type.isEmpty(cellval)) {
            return "<pre class='required' style='width:98%;color:rgb(153, 153, 153)'>" + cellval + "</pre>";
        } else {
            return cellformatter.defaultFormatter.prototype.format.call(this, cellval, rwd);
        }
    }, 
});