global class BreachRecordBatch implements Database.Batchable<sObject>,Database.Stateful {
	
	private List<String> idList = null;
	
	public List<String> outlaId = new List<String>();
	public List<String> autolaId = new List<String>();
	global BreachRecordBatch() {
		
	}

	global BreachRecordBatch(List<String> temp) {
		idList = temp;
	}
	
	global Database.QueryLocator start(Database.BatchableContext BC) {
		if(idList != null && idList.size() > 0){
			return Database.getQueryLocator([select id,Receipt_Date__c,Loaner_Express__c,Equipment_Type__c,Automatic_Received_Date__c,loaner_application__c,loaner_application__r.Rental_End_Date__c,
				                             loaner_application__r.OwnerId,loaner_application__r.Owner.ProfileId,loaner_application__r.Is_Automatic_Received__c,loaner_application__r.Is_time_out__c 
				                             from loaner_application_detail__c  
				                             where (loaner_application__r.Rental_End_Date__c <= :Date.today() or Automatic_Received_Date__c <= :Date.today()) 
				                             //and loaner_application__r.CreatorUserType__c = 'PowerPartner' 
				                             and RAESD_Status__c in ('已出库','申请者已收货','申请者已装机确认') and id in :idList ]);
		}else{
			return Database.getQueryLocator([select id,Receipt_Date__c,Loaner_Express__c,Equipment_Type__c,Automatic_Received_Date__c,loaner_application__c,loaner_application__r.Rental_End_Date__c,
				                             loaner_application__r.OwnerId,loaner_application__r.Owner.ProfileId,loaner_application__r.Is_Automatic_Received__c,loaner_application__r.Is_time_out__c 
				                             from loaner_application_detail__c  
				                             where ((loaner_application__r.Rental_End_Date__c <= :Date.today() and RAESD_Status__c in ('已出库','申请者已收货','申请者已装机确认')) 
				                                   or (Automatic_Received_Date__c <= :Date.today() and RAESD_Status__c = '已出库'))]);
		}
	}

   	global void execute(Database.BatchableContext BC, List<sObject> scope) {

   		List<String> passUserId = new List<String>{
        	'00e0K000001z2Y8',
        	'00e0K000001l1Dx',
        	'00e0K000001l1E2',
        	'00e0K000001l1E7',
        	'00e28000000YMiL',
        	'00e28000000YMif',
        	'00e28000000eN61',
        	'00e28000000eN64',
        	'00e28000001wf2h'
    	};

   		Map<String,loaner_application__c> timeoutMap= new Map<String,loaner_application__c>();
		Map<String,loaner_application__c> autoMap= new Map<String,loaner_application__c>();
		
		Set<loaner_application__c> timeoutSet= new Set<loaner_application__c>();
		Set<loaner_application__c> autoSet= new Set<loaner_application__c>();

		Set<String> timeoutID = new Set<String>();
		Set<String> autoID = new Set<String>();

		Set<String> userIdSet = new Set<String>();
		List<User> userList = new List<User>();
		Map<String,User> userMap = new Map<String,User>();
		List<loaner_application_detail__c> ladList = new List<loaner_application_detail__c>();
     	Set<String> leIdSet = new Set<String>();

		Set<String> laIdSet = new Set<String>();   		
		Map<String,String> usertypeMap = New Map<String,String>();

		system.debug(scope.size());
		//获取符合条件的明细的借用单和借用物流单.
		for(sObject temp : scope){
			
			loaner_application_detail__c lad = (loaner_application_detail__c) temp;
			if(lad.loaner_application__r.Owner.ProfileId != null){
				if(passUserId.contains(String.valueOf(lad.loaner_application__r.Owner.ProfileId).subString(0,15))){

				}else{
					userIdSet.add(lad.loaner_application__r.OwnerId);
					usertypeMap.put(lad.loaner_application__r.OwnerId, lad.Equipment_Type__c);
		         	leIdSet.add(lad.Loaner_Express__c);
		        }
		    }
		}

		//userList = [select id,Automatic_Received_Number__c,Return_Timeout_Number__c from User where id in : userIdSet];
      	//明细
      	List<Loaner_Express__c> leList = new List<Loaner_Express__c>();
		for(Loaner_Express__c le : [select id from Loaner_Express__c where id= :leIdSet]){
        	le.NotReceivingNum__c = 0;
        	leList.add(le);
      	}
		/*for(User temp : userList){
			
			userMap.put(temp.id, temp);
			
		}*/

		Map<String,loaner_application__c> updatLa = new Map<String,loaner_application__c>();
		Map<String,loaner_application__c> updatLa1 = new Map<String,loaner_application__c>();
	
		
		//判断明细是否超期
		for(sObject temp : scope){
			loaner_application_detail__c lad = (loaner_application_detail__c) temp;
			//如果自动收货日期是今天或者今天之前，并且借用单是否自动收货是false并且没有收货日期。
			
			if(lad.Automatic_Received_Date__c <= Date.today() 
				&& lad.loaner_application__r.Is_Automatic_Received__c != true 
				&& lad.Receipt_Date__c == null ){
				//借用单
				loaner_application__c la = new loaner_application__c();
				la.id = lad.loaner_application__c;
				la.OwnerId = lad.loaner_application__r.OwnerId;
				la.Is_Automatic_Received__c = true;
				if(lad.loaner_application__r.Owner.ProfileId != null){
					if(passUserId.contains(String.valueOf(lad.loaner_application__r.Owner.ProfileId).subString(0,15))){

					}else{
						autoMap.put(la.id, la);
					}	
				}
				lad.RAESD_Status__c = '申请者已收货';
				lad.Receipt_Status__c= 'OK';
				lad.Receipt_Date__c = Date.today();
				ladList.add(lad);
				laIdSet.add(lad.loaner_application__c);
				if(!updatLa.keySet().contains(la.id)){
					updatLa.put(la.Id, la);
				}

				//updatLa.add(la);
			}
			//如果借出结束日是今天或者今天之前，并且是否超期是false
			if(lad.loaner_application__r.Rental_End_Date__c <= Date.today() 
				&& lad.loaner_application__r.Is_time_out__c != true ){
				loaner_application__c la = new loaner_application__c();
				la.id = lad.loaner_application__c;
				la.OwnerId = lad.loaner_application__r.OwnerId;
				la.Is_time_out__c = true;
				if(!updatLa1.keySet().contains(la.id)){
					updatLa1.put(la.Id, la);
				}

				//updatLa1.add(la);
				if(lad.loaner_application__r.Owner.ProfileId != null){
					if(passUserId.contains(String.valueOf(lad.loaner_application__r.Owner.ProfileId).subString(0,15))){

					}else{
						timeoutMap.put(la.id, la);
					}
				}
			}
		}
		system.debug(timeoutSet);
		system.debug(autoSet);
		autoSet.addAll(autoMap.values());
		timeoutSet.addAll(timeoutMap.values());


		//自动收货
		/*for(sObject temp : scope){
			loaner_application_detail__c lad = (loaner_application_detail__c) temp;

			if(lad.Automatic_Received_Date__c <= Date.today() && lad.Receipt_Date__c == null){
				lad.RAESD_Status__c = '申请者已收货';
				lad.Receipt_Status__c= 'OK';
				lad.Receipt_Date__c = Date.today();
				ladList.add(lad);
				laIdSet.add(lad.loaner_application__c);
			}
		}*/

		//List<User> autoUser = new List<User>();
		List<User> timeoutUser = new List<User>();
		List<loaner_application__c> autoList = new List<loaner_application__c>();
		List<loaner_application__c> timeoutList = new List<loaner_application__c>();

		List<User_Violations__c> ulList = [select id,Violations_User__c,Violations_reason__c from User_Violations__c where Is_effective__c = true and Violations_User__c in : userIdSet];
		Map<String,Integer> uvMap = new Map<String,Integer>();
		Map<String,Integer> uvMap2 = new Map<String,Integer>();

		//统计现在系统中已有的违规次数
		for(User_Violations__c uv : ulList){
			/*if(uv.Violations_reason__c == '系统自动收货'){
				if(uvMap.containsKey(uv.Violations_User__c)){
					uvMap.put(uv.Violations_User__c, uvMap.get(uv.Violations_User__c)+1);	
				}else{
					uvMap.put(uv.Violations_User__c, 1);
				}
			}
			if(uv.Violations_reason__c == '超期未归还'){
				if(uvMap2.containsKey(uv.Violations_User__c)){
					uvMap2.put(uv.Violations_User__c, uvMap2.get(uv.Violations_User__c)+1);	
				}else{
					uvMap2.put(uv.Violations_User__c, 1);
				}
			}*/

			if(uvMap.containsKey(uv.Violations_User__c)){
				uvMap.put(uv.Violations_User__c, uvMap.get(uv.Violations_User__c)+1);
			}else{
				uvMap.put(uv.Violations_User__c, 1);
			}
		}


		Map<String,List<User_Violations__c>>  newMap = new Map<String,List<User_Violations__c>>();
		List<loaner_application__c> laList = new List<loaner_application__c>();
		system.debug(autoSet);
		if(autoSet.size()>0){
			laList =  [select id,Approver__c,loaner_Manager__c,ApproveManager__c from loaner_application__c where id in :autoMap.keySet()];
			for(loaner_application__c la : autoSet){
				//User user = userMap.get(la.OwnerId);
				/*if(user == null){
					break;
				}*/
				//userMap.get(la.OwnerId).Automatic_Received_Number__c = (userMap.get(la.OwnerId).Automatic_Received_Number__c == null? 0 : userMap.get(la.OwnerId).Automatic_Received_Number__c ) + 1;
				
				if(autolaId.contains(la.Id)){

				}else{
					loaner_application__c la1 = new loaner_application__c();
					for(loaner_application__c la2 : laList){
						if(la2.Id == la.Id){
							la1 = la2;
						}
					}
					User_Violations__c uv = new User_Violations__c();
					uv.Violations_User__c = la.OwnerId;
					uv.Violations_Loaner__c = la.id;
					uv.Violations_reason__c = '系统自动收货';
					uv.ApplyPerson__c = la1.Approver__c;
					uv.loaner_Manager__c = la1.loaner_Manager__c;
					uv.ApproveManager__c = la1.ApproveManager__c;
					if(newMap.containsKey(uv.Violations_User__c)){
						newMap.get(uv.Violations_User__c).add(uv);
					}else{
						List<User_Violations__c> uvlist = new List<User_Violations__c>();
						uvlist.add(uv);
						newMap.put(uv.Violations_User__c,uvlist);
					}
					autolaId.add(la.Id);
					//autoUser.add(user);
				}
			}
		}

		Map<String,List<User_Violations__c>>  newMap2 = new Map<String,List<User_Violations__c>>();
		system.debug(timeoutSet);
		if(timeoutSet.size()>0){
			laList =  [select id,Approver__c,loaner_Manager__c,ApproveManager__c from loaner_application__c where id in :timeoutMap.keySet()];
			for(loaner_application__c la : timeoutSet){
				//User user = userMap.get(la.OwnerId);
/*   				if(user == null){
					break;
				}*/
				// user.Return_Timeout_Number__c = (user.Return_Timeout_Number__c == null ? 0 :  user.Return_Timeout_Number__c ) +1;
				//timeoutUser.add(user);
				//userMap.put(la.OwnerId,user);

				if(outlaId.contains(la.Id)){

				}else{

					loaner_application__c la1 = new loaner_application__c();
					for(loaner_application__c la2 : laList){
						if(la2.Id == la.Id){
							la1 = la2;
						}
					}

					User_Violations__c uv = new User_Violations__c();
					uv.Violations_User__c = la.OwnerId;
					uv.Violations_Loaner__c = la.id;
					uv.Violations_reason__c = '超期未归还';
					uv.ApplyPerson__c = la1.Approver__c;
					uv.loaner_Manager__c = la1.loaner_Manager__c;
					uv.ApproveManager__c = la1.ApproveManager__c;

					/*if(newMap2.containsKey(uv.Violations_User__c)){
						newMap2.get(uv.Violations_User__c).add(uv);
					}else{
						List<User_Violations__c> uvlist = new List<User_Violations__c>();
						uvlist.add(uv);
						newMap2.put(uv.Violations_User__c,uvlist);
					}*/
					if(newMap.containsKey(uv.Violations_User__c)){
						newMap.get(uv.Violations_User__c).add(uv);
					}else{
						List<User_Violations__c> uvlist = new List<User_Violations__c>();
						uvlist.add(uv);
						newMap.put(uv.Violations_User__c,uvlist);
					}
					outlaId.add(la.Id);
				}
			}
		}

		system.debug(newMap.values());
		system.debug(newMap2.values());

		List<User_Violations__c> updateList = new List<User_Violations__c>();
		for(String str : newMap.keySet()){
			if(usertypeMap.get(str) == 'NDT' ||usertypeMap.get(str) == 'ANI'){
				if(uvMap.containsKey(str)){
					if(newMap.containsKey(str)){
						if((uvMap.get(str) + newMap.get(str).size()) >= 1 && uvMap.get(str) < 1){
							newMap.get(str)[0].Is_locking__c = true;
							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
						}
					}
				}else{
					if(newMap.containsKey(str)){
						if(newMap.get(str).size() >= 1 ){
							newMap.get(str)[0].Is_locking__c = true;	
							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
						}
					}
				}
			}else{
				if(uvMap.containsKey(str)){
					if(newMap.containsKey(str)){
						if((uvMap.get(str) + newMap.get(str).size()) >= 2 && uvMap.get(str) < 2){
							newMap.get(str)[0].Is_locking__c = true;
							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
						}
					}
				}else{
					if(newMap.containsKey(str)){
						if(newMap.get(str).size() >= 2 ){
							newMap.get(str)[0].Is_locking__c = true;	
							newMap.get(str)[0].Locking_Start_Date__c = Date.today();
						}
					}
				}
			}
			updateList.addAll(newMap.get(str));
		}

		/*for(String str : newMap2.keySet()){
			if(uvMap2.containsKey(str)){
				if(newMap2.containsKey(str)){
					if((uvMap2.get(str) + newMap2.get(str).size()) == 2 && uvMap2.get(str) != 2){
						newMap2.get(str)[0].Is_locking__c = true;
						newMap2.get(str)[0].Locking_Start_Date__c = Date.today();
					}
				}
			}else{
				if(newMap2.containsKey(str)){
					if(newMap2.get(str).size() >= 2 ){
						newMap2.get(str)[0].Is_locking__c = true;	
						newMap2.get(str)[0].Locking_Start_Date__c = Date.today();
					}
				}
			}
			updateList.addAll(newMap2.get(str));
		}*/

		system.debug('updateList:' + updateList);
		insert updateList;
   		
		//update userMap.values();

		if(ladList.size()>0){
			update ladList;
		}
      	if(leList.size()>0){
         	update leList;
      	}
      	if(updatLa.size()>0){
      		update updatLa.values();
      	}
      	if(updatLa1.size()>0){
      		update updatLa1.values();
      	}

		if(laIdSet.size()>0){
			laList = [select id,Count_SendOut__c,Count_ApplicantReceived__c from loaner_application__c where id = :laIdSet and Status__c = '全部发货'];
			for(loaner_application__c la : laList){
				if(la.Count_SendOut__c == la.Count_ApplicantReceived__c){
					la.Status__c = '申请者已收货';
				}
			}
			update laList;
		}




	
	}
	
	global void finish(Database.BatchableContext BC) {
		List<User_Violations__c> uvList = [select id,Violations_User__c,Is_locking__c,Violations_reason__c from User_Violations__c where Is_effective__c = true order by Violations_User__c];
		Map<String,Integer> userMap = new Map<String,Integer>();
		Map<String,Integer> userMap2 = new Map<String,Integer>();
		
		Map<String,String> user_vMap = new Map<String,String>();
		
		for(User_Violations__c uv : uvList){
			if(uv.Violations_reason__c == '超期未归还'){
				if(userMap.containsKey(uv.Violations_User__c)){
					userMap.put(uv.Violations_User__c, userMap.get(uv.Violations_User__c)+1);
				}else{
					userMap.put(uv.Violations_User__c, 1);
				}
			}else if(uv.Violations_reason__c == '系统自动收货'){
				if(userMap2.containsKey(uv.Violations_User__c)){
					userMap2.put(uv.Violations_User__c, userMap2.get(uv.Violations_User__c)+1);
				}else{
					userMap2.put(uv.Violations_User__c, 1);
				}
			}
			if(uv.Is_locking__c == true){
				user_vMap.put(uv.Violations_User__c,uv.Id);
			}
		}
		system.debug(user_vMap);
		Map<String,User> userList = new Map<String,User>();
		
		for(String userId : userMap.keySet()){
			User user = new User();
			user.Id = userId;
			user.Return_Timeout_Number__c = userMap.get(userId);
			if(user_vMap.containsKey(userId)){
				user.ViolationsID__c = user_vMap.get(userId);
			}
			userList.put(user.Id, user);
		}

		for(String userId : userMap2.keySet()){
			User user = new User();
			if(userList.containsKey(userId)){
				user = userList.get(userId);
				user.Automatic_Received_Number__c = userMap2.get(userId);
			}else{
				user.Id = userId;
				user.Automatic_Received_Number__c = userMap2.get(userId);
			}

			if(user_vMap.containsKey(userId)){
				user.ViolationsID__c = user_vMap.get(userId);
			}
			userList.put(user.Id, user);
		}


		system.debug(userList);
		List<User> updateList = userList.values();
		update updateList;

	}


	
}