var sidValue = [];
var orgLongNum="";
var sumType = "1";
var colNames;
var colModel;
shr.defineClass("shr.customer.gtiit.rpt.personRosterList", shr.framework.List, {
    gridId: '#reportGrid',
    reportUipk :   "com.kingdee.eas.personroster.list" ,
    rowNumPerPage : 30, // 设置默认分页30
    colModelData: null,
    isFirstTimeLoad: 0,
	initalizeDOM : function () {
		var that = this;
		that.setColModelData();
		shr.customer.gtiit.rpt.personRosterList.superClass.initalizeDOM.call(this);
		
		// 快速查询添加事件
		$('#searcher').shrSearchBar('option', {
			afterSearchClick: this.queryGridByEvent

		});
		/*
		// 获取当前日期  
		var currentDate = new Date();  
		  
		// 设置过滤条件  
		var filterItems  = {  
		  field: 'deadline', // 过滤条件的字段名  
		  operator: '=', // 运算符，这里使用等于  
		  value: currentDate.toISOString() // 将当前日期转换为 ISO 格式的字符串  
		};  
		  
		// 将过滤条件添加到过滤条件列表中  
		var filterItem  = [filterItems];  
           */
		$("#deadline").shrDateTimePicker("setValue", new Date());
		$("#deadline").trigger("change")
		//快速过滤展开
		if($(".filter-containers").is(":hidden")){
			$("#filter-slideToggle").click();
	
		}
		/*
		setTimeout(function(){
			var currentDate = new Date();data-id
			var year = currentDate.getFullYear();
			var month = (currentDate.getMonth() + 1).toString().padStart(2, '0');
			var day = currentDate.getDate().toString().padStart(2, '0');

			var formattedDate = year + "-" + month + "-" + day;

			// 在这里编写需要延迟加载的代码
			$("#deadline").attr("original-value", formattedDate);
			$("#deadline").attr("title", formattedDate);
		}, 3000); // 延迟 1 秒执行
		*/
		
	} 
	,processF7ChangeEvent : function(){
		var that = this;
		$('#personType').shrPromptBox("option", {
			onchange : function(e, value) {
			   var info = value.current;
			   	if(info!=null){
			   	
				   if (info.length != undefined) {
				   		orgLongNum = "";
				   		for (var index = 0; index < info.length; index++) {
				   			orgLongNum = orgLongNum + info[index].longNumber + "@" ;
				   		}
				   		if (orgLongNum.length > 0) {
				   			orgLongNum = orgLongNum.substring(0,orgLongNum.length -1);
				   		}
				   }else{
					   	if(info.longNumber !=null && info.longNumber!=''){ 
					   		orgLongNum = info.longNumber;
					   	}
				   }
				}
			}
		});
  	 }
  	 /**
	 * 选择导航节点
	 */
	,queryGridByEvent: function(e) {
		var viewPage;
		var self=this;
		if (e.target) {
			viewPage = shr.getCurrentViewPage(e.target);
		} else {
			viewPage = shr.getCurrentViewPage(e);
		}
		// 将页码恢复为第1页
		$(viewPage.gridId).jqGrid('option', 'page', 1);
		viewPage.queryAction();
	},
	
	/**
	 * 获得search查询条件
	 */
	getSearchFilterItems: function() {
		var filter = $('#searcher').shrSearchBar('option', 'filterView');
		if (filter && filter.filterItems) {
			return filter.filterItems;
		}
	}
	,queryAction : function () {
		var self = this;
		//search搜索
		var searchFilterItems = self.getSearchFilterItems();
		if( searchFilterItems == undefined)
			searchFilterItems = "" ;
		//快速过滤
		var fastFilterItems = self.getFastFilterItems();
		if(fastFilterItems == undefined){
			fastFilterItems = "";
		}
		if(fastFilterItems["add"] == ""){
			fastFilterItems["add"] = null;
		}
		
		//R20190625-2369保存方案后，其它条件设置的条件被清空
		//需把视图的filterItem其他条件name="add"改成name="advancedFilter" 
		var advancedFilterItems = self.getAdvancedFilterItems();
		if(advancedFilterItems != undefined){
			fastFilterItems["add"] = advancedFilterItems;
		}
		
		$("#reportGrid").jqGrid('setGridParam', {
			datatype : 'json',
			postData : {
				'NewRearch'   : 'newRearch',
				'fastFilterItems' : $.toJSON(fastFilterItems),
				'searchFilterItems' : searchFilterItems,
				'sumType' : sumType,
				'page' : 1
			},
			page : 0
		});
		self.doRenderDataGrid();
	},
	setColModelData: function () {
		var self = this;
		self.remoteCall({
			method : "getGridColModel",
			success : function (data) {
				colNames = data.colNames;
				colModel = data.colModel;
			}
		})
	},
	  
	/**
	 * 表格数据请求URL
	 */
	getGridDataRequestURL : function () {
		var serviceId = shr.getUrlRequestParam("serviceId");
		return this.dynamicPage_url + "?method=getGridData" + "&uipk=" + this.reportUipk + '&serviceId='+encodeURIComponent(serviceId); 
	},

   doRenderDataGrid : function () {
		var self = this, table = $("#reportGrid");
		var searchFilterItems = self.getSearchFilterItems();
		var fastFilterItems = self.getFastFilterItems();
		if( searchFilterItems == undefined)
			searchFilterItems = "" ;
		if( fastFilterItems == undefined)
			fastFilterItems = "" ;
		if(fastFilterItems["add"] == ""){
			fastFilterItems["add"] = null;
		}
		
		//R20190625-2369保存方案后，其它条件设置的条件被清空
		//需把视图的filterItem其他条件name="add"改成name="advancedFilter" 
		var advancedFilterItems = self.getAdvancedFilterItems();
		if(advancedFilterItems != undefined){
			fastFilterItems["add"] = advancedFilterItems;
		}
		
		postData = {
			'searchFilterItems' : searchFilterItems,
			'fastFilterItems' : $.toJSON(fastFilterItems),
			'page1' : 1
		};

		var url = self.getGridDataRequestURL();        
		var	options = {
			url : url ,
			datatype : "json",
			multiselect : true,
			rownumbers : false,
			colNames : colNames,
			colModel : colModel,
			rowNum : self.rowNumPerPage,
			// pager : '#gridPager1',
			mtype: 'POST',
			postData: postData ,
//			height : 'auto',
			height : '600px',
//			height : self.rowNumPerPage > 21 ? '600px' : 'auto',
			rowList : [30,45,60],
			recordpos : 'left',
			recordtext : '({0}-{1})/{2}',
			gridview : true,
			// pginput : true,
			shrinkToFit :colModel.length>10?false:true,
			viewrecords : true,
			//cellEdit:true,
            // cellsubmit:"clientArray" ,	
			// sortname : "sumsql.fproposerid",
			//caption: "Frozen Header",
			customPager : '#gridPager1',  
			pagerpos:"center",
			pginputpos:"right",
			pginput:true,     
			synchTotal:"true",
			onSelectRow: function(id){ 
				jQuery('#reportGrid').jqGrid('editRow', id, false, function(){});
				sidValue.push(id);
				lastsel2 = id;
				$("#reportGrid").attr("sid", sidValue.join(","));
			}
		};

		options.loadComplete = function (data) {
			if($("#gridPager1").html() == "" && "true" == "true"){
				$("#reportGrid").setCustomPager("#gridPager1");
			}
			
			shr.setIframeHeight();
			$('#gridPager1_left').click(function(){
				$('.ui-pg-selbox').show();
				$('.ui-pg-selbox').css({"left":"-60px"})
				$(this).children('.ui-paging-info').hide();
			});
			$("#microToolbar").parent().hide()
			$("#gridPager1").parent().css({"position":"relative"})  
			$("#gridPager1").addClass("shrPage").css({
				"position":"absolute",
				"top":"-25px",
				"right":"0px",
				"background":"#FFF"
			})
            shr.customer.gtiit.rpt.personRosterList.superClass.gridLoadComplete.call(this,data);
		};
		table.html();
		table.jqGrid(options);
		jQuery("#reportGrid").jqGrid(options).jqGrid("reloadGrid");
		jQuery('#reportGrid').jqGrid('setFrozenColumns');
		self.firstTime = 1;
		
	},
	handleMicroToolbarInfo : function () {

		var self = this;
		var html = "";
		html += "<div class='shrPage page-Title' >";
		html += "<span id='gripage' class='ui-paging-info' style='cursor: default;display: inline-block;font-size: 13px;padding: 2px 5px 0 0;'></span>";
		html += "<span id='prevId'  style='vertical-align: text-top;cursor: pointer;' class='ui-icon ui-icon-seek-prev'></span>";
		html += "<span id='nextId'  style='vertical-align: text-top;cursor: pointer;' class='ui-icon ui-icon-seek-next'></span></div>";
		
		$('#microToolbar').html("");
		$('#microToolbar').append(html);

		$("#gripage").on("click", self.selectRowNumPerPage);
		$("#prevId").on("click", self.prePage);
		$("#nextId").on("click", self.nextPage);

		//页码 (1-4)/4
		self.updatePageEnable();
		$("#gripage").text($("#gridPager1_left >div[dir='ltr']").text());
		$("#gridPager1").hide();
		 var ids=jQuery("#reportGrid").jqGrid('getDataIDs');
         var rowdata=jQuery("#reportGrid").jqGrid('getRowData',ids[0]);  
		
		shr.setIframeHeight();
		$("#reportGrid_frozen").parent().height('583px');
	},
	updatePageEnable:function () {
		var temp = $("#gridPager1_left >div[dir='ltr']").text();
		if (temp.substring(1, temp.indexOf('-')) == '1') {
			$("#prevId").addClass("ui-state-disabled");
		} else {
			$("#prevId").removeClass("ui-state-disabled");
		}

		if (parseInt(temp.substring(temp.indexOf('-') + 1, temp.indexOf(')'))) >= parseInt(temp.substring(temp.indexOf('/') + 1).replace(new RegExp(",","gm"),""))) {
			$("#nextId").addClass("ui-state-disabled");
		} else {
			$("#nextId").removeClass("ui-state-disabled");
		}
	},
    
	getCurPage:function(){
		//(1-4)/4
		var self = this,
		rowNum = self.rowNumPerPage;
		var temp = $("#gridPager1_left >div[dir='ltr']").text();
		var curPageNum = (parseInt(temp.substring(1, temp.indexOf('-')))-1)/rowNum+1;
		return curPageNum;
	},

	prePage : function () {
		$("#prev_gridPager1").trigger("click");
		shr.setIframeHeight();
		$("#gripage").text($("#gridPager1_left >div[dir='ltr']").text());
	},

	nextPage : function () {
		$("#next_gridPager1").trigger("click");
		shr.setIframeHeight();
		$("#gripage").text($("#gridPager1_left >div[dir='ltr']").text());
	},
		
	selectRowNumPerPage:function(){
			
	}
	
	,
	exportToExcelAction : function () {
		openLoader
  		var _self = this ;
  		var url = _self.exportCommonParam();
  		var fastFilterItems = _self.getFastFilterItems();
		if( fastFilterItems == undefined)
			fastFilterItems = "" ;
		if(fastFilterItems["add"] == ""){
			fastFilterItems["add"] = null;
		}
				
  		 var serviceId = shr.getUrlRequestParam("serviceId");
  		url += '&serviceId='+encodeURIComponent(serviceId) + "&isAll=true";
		//document.location.href = url;
		var callback=function(psw){
            var params = _self.getExportAllParams();
            params.exportPrivteProtected = $.allEncrypt(psw);
			openLoader(1,jsBizMultLan.atsManager_attendanceResultSumList_i18n_28);
			shr.ajax({
				type:"post",
				url:url,
				data: $.extend(_self.assemExportData(),{exportPrivteProtected: psw} ),
				success:function(res){
					closeLoader();
					if(null != res && null != res.url){   //这里有可能返回空，所以这里要做飞空判断的，但是不知道这里的业务逻辑，所以这里要问常青和飞羽
                        shr.redirect(res.url,"");
                    }
					//document.location.href = url;
				},
				error : function(res){
					shr.showError({message: jsBizMultLan.atsManager_attendanceResultSumList_i18n_6});
					closeLoader();
				}
			});
		}
        if(_self.isNeedExportFilePassword('#exportToExcel')) {
			fieldSensitiveService.setExportPsw(callback);
		}else{
			callback();
		}
	},
		assemExportData:function(exportData){
		var _self = this ;
		var fastFilterItems = _self.getFastFilterItems();
		var advancedFilterItems = _self.getAdvancedFilterItems();
		if( fastFilterItems == undefined)
			fastFilterItems = "" ;
		if(fastFilterItems["add"] == ""){
			fastFilterItems["add"] = null;
		}
		
		if(advancedFilterItems != undefined){
			fastFilterItems["add"] = advancedFilterItems;
		}
		
		var postData = {fastFilterItems : $.toJSON(fastFilterItems)};
		
		exportData && (postData = $.extend(postData, exportData));
		return postData;
	},
	
	exportCommonParam : function(){
		var self = this;
		var url = shr.getContextPath() + shr.dynamicURL + "?method=exportToExcel";
		var uipk = "com.kingdee.eas.hr.ats.app.AttendanceResultSumList";
		var filterItems = self.getQuickFilterItems();
		var sorder =   $('#reportGrid').jqGrid('getGridParam', 'sortorder') || "";
		var sordName = $('#reportGrid').jqGrid('getGridParam', 'sortname') || "";

		//标题
		   url += "&title="+jsBizMultLan.atsManager_attendanceResultSumList_i18n_8;
		   url = url + '&uipk=' + uipk + "&sidx=" + sordName+"&page=0"+"&sumType="+sumType + "&sord=" + sorder + "&transverse=1";
		//如果存在高级搜索的条件，则拼上条件。
		if(filterItems){
			url += "&searchFilterItems=" + encodeURIComponent(filterItems);
		}
		return url;
	},
	exportCurrentAction : function(){
		var Exchange_json=[];
		var _self = this;
		var exportData = {
			exportSelect:"yes",
			serviceId:shr.getUrlRequestParam("serviceId")
		};
		var selectedIds = $("#reportGrid").jqGrid("getSelectedRows");
		if (selectedIds == undefined || selectedIds.length <= 0 || (selectedIds && selectedIds.length ==
				1 && selectedIds[0] == "")) {
			shr.showError({
				message: "请先选中表格中的数据！",
				hideAfter: 5
			});
			return false;
		}
		/*
		_self.remoteCall({
			type: "post",
			async: false,
			method: "exportCurrent",
			param: {
				billIds: selectedIds.toString()
			},
		});
		*/
		if (selectedIds.length > 0) {
			for (var i = 0, length = selectedIds.length; i < length; i++) {
//				personIds.push($("#reportGrid").jqGrid("getCell", selectedIds[i], "id"));
				var item = selectedIds[i];
				var data = $("#reportGrid").jqGrid("getRowData", item);
				
				var personId=data["personId"] ;
				var adminOrgUnit=data["adminOrgUnitId"] ;
				Exchange_json.push({'personId':personId,'adminOrgUnit':adminOrgUnit});
			}
		}
		if(Exchange_json.length > 0){
			exportData.PersonJson =  $.toJSON(Exchange_json);
		}else{
			shr.showWarning({
				message: jsBizMultLan.atsManager_attendanceResultSumList_i18n_13
			});
			return false;
		}
		var callback=function(psw){
            var params = _self.getExportCurrentParams();
            params.exportPrivteProtected = $.allEncrypt(psw);
			openLoader(1,jsBizMultLan.atsManager_attendanceResultSumList_i18n_28);
			shr.ajax({
				type:"post",
				url:_self.exportCommonParam(),
				//method : "toexportCurrent",
				data: $.extend( _self.assemExportData(exportData),params ),
				success:function(res){
					closeLoader();
					//document.location.href = url;
					shr.redirect(res.url,"");
				},
				error : function(res){
					shr.showError({message: jsBizMultLan.atsManager_attendanceResultSumList_i18n_6});
					closeLoader();
				}
			});
		}
        if(_self.isNeedExportFilePassword('#exportCurrent'))  {
			fieldSensitiveService.setExportPsw(callback);
		}else{
			callback();
		}

	},
    //导出选中参数，供领域获取
    getExportCurrentParams: function() {
        var _self = this;
        var isenableexcelpwd = $('#exportCurrent').attr('data-isenableexcelpwd');
        var fieldName = this.getExportFieldName();
        if(isenableexcelpwd == 'false') {
            if(window.isShrSensitiveRuleOpen) isenableexcelpwd = _self.isSensitiveGrid();
        }

        var ids = $("#reportGrid").jqGrid("getSelectedRows");
        var params = {
            supportQueryUuid: false,
            selectedData: ids,
            fieldName_key: fieldName,
            encryptKeys: 'exportPrivteProtected',
            isEnableExcelPwd: typeof(isenableexcelpwd) === 'undefined' ? 'false' : JSON.parse(isenableexcelpwd)
        }
        return params;
    },
	
	exportAllExcelAction:function(){
        var _self = this;
		var self = this, table = $("#reportGrid");
		var searchFilterItems = self.getSearchFilterItems();
		var fastFilterItems = self.getFastFilterItems();
		if( searchFilterItems == undefined)
			searchFilterItems = "" ;
		if( fastFilterItems == undefined)
			fastFilterItems = "" ;
		if(fastFilterItems["add"] == ""){
			fastFilterItems["add"] = null;
		}
		
		//R20190625-2369保存方案后，其它条件设置的条件被清空
		//需把视图的filterItem其他条件name="add"改成name="advancedFilter" 
		var advancedFilterItems = self.getAdvancedFilterItems();
		
		if(advancedFilterItems != undefined){
			fastFilterItems["add"] = advancedFilterItems;
		}
		/*
		var urlinner = shr.getContextPath() + shr.dynamicURL + "?fastFilterItems="+$.toJSON(fastFilterItems)+"&method=toExcel&handler=com.kingdee.shr.customer.gtiit.rpt.PersonRosterListHandler"+"&uipk="+shr.getUrlRequestParam('uipk');
		//var urlinner = shr.getContextPath()  + shr.dynamicURL + "?method=toExcel&handler=com.kingdee.shr.customer.gtiit.rpt.PersonRosterListHandler";
		//alert(urlinner);
		openLoader(1,"正在导出,请稍等...");
		var param2 = "";
		var test = shr.reloadUrlByPost(urlinner, param2, 'toExcel');
		
		closeLoader();
		*/
		/*
		_self.remoteCall({
			type: "post",
			async: false,
			method: "toExcel",
			param: {
				'fastFilterItems' : $.toJSON(fastFilterItems)
			},
		});
		*/
		openLoader(1,"正在导出,请稍等...");
		var urlinner = shr.getContextPath() + shr.dynamicURL;  

			var data = {  

				fastFilterItems: $.toJSON(fastFilterItems),  

				method: 'toExcel',  

				handler: 'com.kingdee.shr.customer.gtiit.rpt.PersonRosterListHandler',  

				uipk: shr.getUrlRequestParam('uipk')  

			};  

			  

			//$.post(urlinner, data)  
					var test = shr.reloadUrlByPost(urlinner, data, 'toExcel');
					closeLoader();
             /*
			.done(function(data) {  

				// 处理返回的数据  

			})  

			.fail(function(jqXHR, textStatus, errorThrown) {  

				console.error('Error:', textStatus, errorThrown);  

			});
			*/
					
				}
				
			});	
