shr.defineClass("shr.customer.gtiit.AtsOverTimeBillBatchEditForPerEx", shr.ats.atsOverTimeBillBatchEditForPer, {

    initalizeDOM:function(){
        shr.customer.gtiit.AtsOverTimeBillBatchEditForPerEx.superClass.initalizeDOM.call(this);
        var that = this;
        if(jsBinder.operateState == 'VIEW'){
            $('[aria-describedby="entries_todescription"]').css({'white-space':'break-spaces'});
        }
        var entries_cont=waf("#entries");
        entries_cont.jqGrid("option", { 
              beforeSaveCell:function (rowid, cellname, value, iRow, iCol) {
                  
              },
             beforeEditCell: function (rowid, cellname, value, iRow, iCol) {
        console.log("进入编辑前:", rowid, cellname, value, iRow, iCol);
       
    },
    afterEditCell: function (rowid, cellname, value, iRow, iCol) {
        console.log("进入编辑后:", rowid, cellname, value, iRow, iCol);
        // 在这里可以进行一些后续操作，如设置焦点
        // that.updateCalWidth(90)
    },
              afterSaveCell:function (rowid, cellname, value, iRow, iCol) {

                  if(value["adminOrgUnit.id"]){
                        $("#entries").jqGrid('setCell',rowid,"adminOrgUnit.id",value["adminOrgUnit.id"]);
                     }
                _self.afterSaveCellTrigger(rowid, cellname, value, iRow, iCol);              
                    
              }
              ,afterEditCell:function (rowid, cellname, value, iRow, iCol) 
              {
                that.getOTContrlParams(rowid);
                if(cellname=="otType" && that.OTContrlParams[rowid].isOtrolByDateType){
                    $("#"+iRow+"_otType").shrPromptBox("disable");
                }
                //因为需求只是提了第一个时间时改变业务组织
                $("#1_otDate").change(function(){
                 that.changeOverHrOrgUnit();
                });
                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 == "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
                          });
                      }


                  }

                _self.saveEditCellValue(rowid,cellname, value,iRow,iCol) ;
              }
        });
        
    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 });
            }
        });
    },
    afterSaveCellTrigger: function(rowid, cellname, value, iRow, iCol)
    {   
        var that = this ;
        var entries_cont=waf("#entries");
        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);
        }
        
        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);
        }
        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 restStartTimeOfDate;
            var restEndTimeOfDate;
            if (restStartTime!="" && restEndTime!=""){
                restStartTimeOfDate = new Date(restStartTime);
                restEndTimeOfDate = new Date(restEndTime);
                var times =restEndTimeOfDate.getTime()-restStartTimeOfDate.getTime();
                if (times<0){
                    times=0;
                }
                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;
                    }
                    times=times/1000/60;
                    totalRestTime+=times;
                }
            }
            var  t1 = totalRestTime.toFixed(atsMlUtile.getSysDecimalPlace());
            $("#entries").jqGrid('setCell',rowid,"restTime",t1) ;
            var startTime =new Date(startTime+":00");
            var endTime =new Date(endTime+":00");
            var se = endTime.getTime()-startTime.getTime() -totalRestTime; // 毫秒
            var tfl = se/(3600*1000) ;
            $("#entries").jqGrid('setCell',rowid,"applyOTTime",tfl) ;
            that.calculateOTtimes(rowid);
            that.getOTContrlParams(rowid);
            that.countOvertimeHourAction();
        }
    },
    calculateOTtimes : function(rowid){
        var that = this ;
        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","");
        }

        startTime = that.addTimeToDate(startTime);
        endTime = that.addTimeToDate(endTime);
        
        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)).toFixed(fixedNum) ;
            $("#entries").jqGrid('setCell',rowid,"applyOTTime",tfl);
            this.countOvertimeHourAction();
        }
    },
    getOverTimeType:function(rowid,otDate,personId){
        var _self = this;
        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);
                        if(otCompensIds){
                            var otCompensIdsStr = _self.getOTCompensByOTType(personId,response.otTypeValue).replace(/(,)/g, "','");
                            _self.filter[rowid]="BaseInfo.id in ('"+otCompensIdsStr+"')";
                        }
                        
                        var compens = response.compensInfo ;
                        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;
        }
        var otCompensIds = that.getOTCompensByOTType(personId,otTypeId);

        var url = shr.getContextPath()+'/dynamic.do';
        that.remoteCall({
            type:"post",
            method:"getDefaultOTCompens",
            url:url,
            param:{personId:personId,otTypeId:otTypeId},
            async: false,
            success:function(res){
                var info =  res;
                if (info.defaultId == "" || info.defaultId ==undefined ){
                    shr.showWarning({message:jsBizMultLan.atsManager_atsOverTimeBillBatchEditForPer_i18n_24});
                }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 ;
        if(obj.length == 0){
            shr.showWarning({message: jsBizMultLan.atsManager_atsOverTimeBillBatchEditForPer_i18n_7});
            return false;
        }
        
        if(!_self.checkRowIsOver()){
            return false;
        }
        
        _rowMap = {} ;
        jQuery(obj).each(function(n){
                errorString = _self.checkEveryRow(n + 1 , this);
                if(errorString){
                    _self.preShowError( n + 1 ,this.person.name + " " + errorString);
                    errorFlag = 1 ;
                }
            
         });    
         if(!_self.verifyCheck()){
            return false;
         }

        errorString = _self.validateOTEntry();
        if(errorString && errorString != ""){
            shr.showWarning({message: errorString});
            closeLoader();
            return false;
        }
         if(errorFlag == 0){
             //工作流审批界面，加班补提控制。
            var boo = true;
            boo = _self.validateIsFillOtVerify();
            
            return boo;
         }else{
            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);
    },
    submitAction: function(event) {
        var _self = this,
            workArea = _self.getWorkarea(),
            $form = $('form', workArea);
        if(!_self.validate()){
            return ;
        }
        if(!_self.checkOtDate()){
            return false;
        }
            
        if ($form.valid() && _self.verify()) {
            shr.showConfirm(jsBizMultLan.atsManager_atsOverTimeBillBatchEditForPer_i18n_14, function() {
                _self.doSubmit(event, 'submit');
            });
        }       
    },
    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);
        }
    }, 
}); 