global class SubAuthorizedBatch implements Database.Batchable<sObject> {
	String testID;

	Boolean IsNeedExecute = false; // 2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  是否符合执行条件

	public SubAuthorizedBatch(string testID) {
		this.testID = testID;

	}
	public SubAuthorizedBatch() {

	}
	// 2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
	public SubAuthorizedBatch(Boolean NeedExecute) {
	    this.IsNeedExecute = NeedExecute;
	}
	// 2021-03-03  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end

	global Database.QueryLocator start(Database.BatchableContext BC) {
		Date today = Date.today();
		Date tomorrow = today.addDays(1);
		Date twoDayLater = today.addDays(2);
		//Date twoDayAgo = today.addDays(-2);
		//Date yesterday = today.addDays(-1);
		if (!String.isBlank(this.testID)) {
			return Database.getQueryLocator(
			           [select Id, Status__c, IsAuthorize__c, Authorizer__c,
			            AuthorizedStartDate__c, AuthorizedEndDate__c, Authorizee__c
			            from SubAuthorized__c
			            where id = :testID]
			       );
		}
		return Database.getQueryLocator(
		           [select Id, Status__c, IsAuthorize__c, Authorizer__c,
		            AuthorizedStartDate__c, AuthorizedEndDate__c, Authorizee__c
		            from SubAuthorized__c
		            where
		            (Status__c = '已批准'
		                         and IsAuthorize__c = false
		                                 and AuthorizedStartDate__c <= : tomorrow
		                                 and AuthorizedEndDate__c >= : twoDayLater)
		            or
		            (Status__c = '已批准'
		                         and IsAuthorize__c = true
		                                 and AuthorizedEndDate__c <= : tomorrow)
		            or
		            (Status__c = '已取消'
		                         and IsAuthorize__c = true
		            )
		           ]
		       );
	}
	global void execute(Database.BatchableContext BC, List<SubAuthorized__c> SubAuthorizedList) {
		system.debug('---------1-------------SubAuthorizedList:' + SubAuthorizedList);
		Map<id, SubAuthorized__c> SubAuthorizedMap = new Map<id, SubAuthorized__c> ();
		Set<User> UpdateUserSet = new Set<User>();

		List<User> UpdateUserList = new List<User>();

		// 获取所有提交人的id
		for ( SubAuthorized__c SubAuthor : SubAuthorizedList) {
			SubAuthorizedMap.put(SubAuthor.Authorizer__c, SubAuthor);
		}
		system.debug('---------2-------------SubAuthorizedMap:' + SubAuthorizedMap);
		//	检索出提交人为经理部长总监的用户数据（包括作为备份的）
		list<User> allUserList =
		    [select id, ZongjianApprovalManager_copy__c,
		     TongkuoZongjian_copy__c, BuchangApprovalManager_copy__c,
		     BuchangApprovalManagerSales_copy__c, JingliApprovalManager_copy__c,
		     SalesManager_copy__c, ZongjianApprovalManager__c,
		     TongkuoZongjian__c, BuchangApprovalManager__c,
		     BuchangApprovalManagerSales__c, JingliApprovalManager__c,
		     SalesManager__c, ManagerId , ManagerId_copy__c
		     // SWAG-BEM9EP start
		     ,JingliEquipmentManager__c, JingliEquipmentManager_copy__c
		     ,Buzhang_Equipment_Manager__c, Buzhang_Equipment_Manager_copy__c
		     // SWAG-BEM9EP end
		     from user
		     where
		     ZongjianApprovalManager_copy__c in: SubAuthorizedMap.keyset()
		     or TongkuoZongjian_copy__c in: SubAuthorizedMap.keyset()
		     or BuchangApprovalManager_copy__c in: SubAuthorizedMap.keyset()
		     or BuchangApprovalManagerSales_copy__c in: SubAuthorizedMap.keyset()
		     or JingliApprovalManager_copy__c in: SubAuthorizedMap.keyset()
		     or SalesManager_copy__c in: SubAuthorizedMap.keyset()
		     or ZongjianApprovalManager__c in: SubAuthorizedMap.keyset()
		     or TongkuoZongjian__c in: SubAuthorizedMap.keyset()
		     or BuchangApprovalManager__c in: SubAuthorizedMap.keyset()
		     or BuchangApprovalManagerSales__c in: SubAuthorizedMap.keyset()
		     or JingliApprovalManager__c in: SubAuthorizedMap.keyset()
		     or SalesManager__c in: SubAuthorizedMap.keyset()
		     or ManagerId in : SubAuthorizedMap.keyset()
		     or ManagerId_copy__c in : SubAuthorizedMap.keyset()
		     //SWAG-BEM9EP start
		     or JingliEquipmentManager__c in : SubAuthorizedMap.keyset()
		     or JingliEquipmentManager_copy__c in : SubAuthorizedMap.keyset()
		     or Buzhang_Equipment_Manager__c in : SubAuthorizedMap.keyset()
 			 or Buzhang_Equipment_Manager_copy__c in : SubAuthorizedMap.keyset()
 			 // SWAG-BEM9EP end
		     ];

		// 设置更新用户数据
		for (User tempUser : allUserList) {
			boolean IsUpdate = false;
			// 从备份赋值到总监部长经理回来，备份置空
			if (tempUser.ZongjianApprovalManager_copy__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.ZongjianApprovalManager_copy__c)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.ZongjianApprovalManager_copy__c))
			   ) {
				tempUser.ZongjianApprovalManager__c = tempUser.ZongjianApprovalManager_copy__c;
				tempUser.ZongjianApprovalManager_copy__c = null;
				IsUpdate = true;

			}
			if (tempUser.TongkuoZongjian_copy__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.TongkuoZongjian_copy__c)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.TongkuoZongjian_copy__c))
			   ) {
				tempUser.TongkuoZongjian__c = tempUser.TongkuoZongjian_copy__c;
				tempUser.TongkuoZongjian_copy__c = null;
				IsUpdate = true;
			}
			if (tempUser.BuchangApprovalManager_copy__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.BuchangApprovalManager_copy__c)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.BuchangApprovalManager_copy__c))
			   ) {
				tempUser.BuchangApprovalManager__c = tempUser.BuchangApprovalManager_copy__c;
				tempUser.BuchangApprovalManager_copy__c = null;
				IsUpdate = true;
			}
			if (tempUser.BuchangApprovalManagerSales_copy__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.BuchangApprovalManagerSales_copy__c)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.BuchangApprovalManagerSales_copy__c))
			   ) {
				tempUser.BuchangApprovalManagerSales__c = tempUser.BuchangApprovalManagerSales_copy__c;
				tempUser.BuchangApprovalManagerSales_copy__c = null;
				IsUpdate = true;
			}
			if (tempUser.JingliApprovalManager_copy__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.JingliApprovalManager_copy__c)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.JingliApprovalManager_copy__c))
			   ) {
				tempUser.JingliApprovalManager__c = tempUser.JingliApprovalManager_copy__c;
				tempUser.JingliApprovalManager_copy__c = null;
				IsUpdate = true;
			}
			if (tempUser.SalesManager_copy__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.SalesManager_copy__c)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.SalesManager_copy__c))
			   ) {
				tempUser.SalesManager__c = tempUser.SalesManager_copy__c;
				tempUser.SalesManager_copy__c = null;
				IsUpdate = true;
			}

			if (tempUser.ManagerId_copy__c	 != null &&
			        SubAuthorizedMap.containsKey(tempUser.ManagerId_copy__c	)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.ManagerId_copy__c	))
			   ) {
				tempUser.ManagerId = tempUser.ManagerId_copy__c;
				tempUser.ManagerId_copy__c	 = null;
				IsUpdate = true;
			}
			//SWAG-BEM9EP start
			if (tempUser.JingliEquipmentManager_copy__c	 != null &&
			        SubAuthorizedMap.containsKey(tempUser.JingliEquipmentManager_copy__c	)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.JingliEquipmentManager_copy__c	))
			   ) {
				tempUser.JingliEquipmentManager__c = tempUser.JingliEquipmentManager_copy__c;
				tempUser.JingliEquipmentManager_copy__c	 = null;
				IsUpdate = true;
			}

			if (tempUser.Buzhang_Equipment_Manager_copy__c	 != null &&
			        SubAuthorizedMap.containsKey(tempUser.Buzhang_Equipment_Manager_copy__c	)
			        && !checkSubAuthorized(SubAuthorizedMap.get(tempUser.Buzhang_Equipment_Manager_copy__c))
			   ) {
				tempUser.Buzhang_Equipment_Manager__c = tempUser.Buzhang_Equipment_Manager_copy__c;
				tempUser.Buzhang_Equipment_Manager_copy__c	 = null;
				IsUpdate = true;
			}
			//SWAG-BEM9EP end


			// 从总监部长经理赋值到备份，总监部长经理设置为转授权人
			if (tempUser.ZongjianApprovalManager__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.ZongjianApprovalManager__c)
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.ZongjianApprovalManager__c))
			   ) {
				tempUser.ZongjianApprovalManager_copy__c = tempUser.ZongjianApprovalManager__c;
				tempUser.ZongjianApprovalManager__c
				    = SubAuthorizedMap.get(tempUser.ZongjianApprovalManager__c).Authorizee__c ;
				IsUpdate = true;
			}
			if (tempUser.TongkuoZongjian__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.TongkuoZongjian__c)
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.TongkuoZongjian__c))
			   ) {
				tempUser.TongkuoZongjian_copy__c = tempUser.TongkuoZongjian__c;
				tempUser.TongkuoZongjian__c
				    = SubAuthorizedMap.get(tempUser.TongkuoZongjian__c).Authorizee__c ;
				IsUpdate = true;
			}
			if (tempUser.BuchangApprovalManager__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.BuchangApprovalManager__c)
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.BuchangApprovalManager__c))
			   ) {
				tempUser.BuchangApprovalManager_copy__c = tempUser.BuchangApprovalManager__c;
				tempUser.BuchangApprovalManager__c
				    = SubAuthorizedMap.get(tempUser.BuchangApprovalManager__c).Authorizee__c ;
				IsUpdate = true;
			}
			if (tempUser.BuchangApprovalManagerSales__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.BuchangApprovalManagerSales__c)
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.BuchangApprovalManagerSales__c))
			   ) {
				tempUser.BuchangApprovalManagerSales_copy__c = tempUser.BuchangApprovalManagerSales__c;
				tempUser.BuchangApprovalManagerSales__c
				    = SubAuthorizedMap.get(tempUser.BuchangApprovalManagerSales__c).Authorizee__c ;
				IsUpdate = true;
			}
			if (tempUser.JingliApprovalManager__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.JingliApprovalManager__c)
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.JingliApprovalManager__c))
			   ) {
				tempUser.JingliApprovalManager_copy__c = tempUser.JingliApprovalManager__c;
				tempUser.JingliApprovalManager__c
				    = SubAuthorizedMap.get(tempUser.JingliApprovalManager__c).Authorizee__c ;
				IsUpdate = true;
			}
			if (tempUser.SalesManager__c != null &&
			        SubAuthorizedMap.containsKey(tempUser.SalesManager__c)
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.SalesManager__c))
			   ) {
				tempUser.SalesManager_copy__c = tempUser.SalesManager__c;
				tempUser.SalesManager__c
				    = SubAuthorizedMap.get(tempUser.SalesManager__c).Authorizee__c ;
				IsUpdate = true;

			}
			if (tempUser.ManagerId  != null &&
			        SubAuthorizedMap.containsKey(tempUser.ManagerId )
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.ManagerId ))
			   ) {
				tempUser.ManagerId_copy__c = tempUser.ManagerId ;
				tempUser.ManagerId
				    = SubAuthorizedMap.get(tempUser.ManagerId ).Authorizee__c ;
				IsUpdate = true;

			}

			//SWAG-BEM9EP start
			if (tempUser.JingliEquipmentManager__c  != null &&
			        SubAuthorizedMap.containsKey(tempUser.JingliEquipmentManager__c )
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.JingliEquipmentManager__c ))
			   ) {
				tempUser.JingliEquipmentManager_copy__c = tempUser.JingliEquipmentManager__c ;
				tempUser.JingliEquipmentManager__c
				    = SubAuthorizedMap.get(tempUser.JingliEquipmentManager__c ).Authorizee__c ;
				IsUpdate = true;

			}

			if (tempUser.Buzhang_Equipment_Manager__c  != null &&
			        SubAuthorizedMap.containsKey(tempUser.Buzhang_Equipment_Manager__c )
			        && checkSubAuthorized(SubAuthorizedMap.get(tempUser.Buzhang_Equipment_Manager__c ))
			   ) {
				tempUser.Buzhang_Equipment_Manager_copy__c = tempUser.Buzhang_Equipment_Manager__c ;
				tempUser.Buzhang_Equipment_Manager__c
				    = SubAuthorizedMap.get(tempUser.Buzhang_Equipment_Manager__c ).Authorizee__c ;
				IsUpdate = true;

			}
			//SWAG-BEM9EP end

			if (IsUpdate) {
				UpdateUserList.add(tempUser);
			}
		}


		// 先更新经理部长总监改了的用户
		if (UpdateUserList.size() > 0) {
			update UpdateUserList;
		}
		// 设置转授权功能是否授权数据
		updateSubAuthorizedList(SubAuthorizedList);


	}

	global void finish(Database.BatchableContext BC) {

		// 2021-09-17  mzy  WLIG-BYHD79  SFDC环境batch合并调查  start
		if(!System.Test.isRunningTest() &&IsNeedExecute==true){
          //batch里调用下一个batch时，希望跟原有的Schedule里面传的条数保持一致
           Id execBTId = Database.executebatch(new UpdateOPDStatusAndReasonBatch(),100);
        }
        // 2021-09-17  mzy  WLIG-BYHD79  SFDC环境batch合并调查  end

	}

	// 设置转授权功能是否授权数据
	private static void updateSubAuthorizedList(list<SubAuthorized__c> SubAuthorizedList) {
		List<SubAuthorized__c> updateSubAuthorizedList = new List<SubAuthorized__c>();
		for ( SubAuthorized__c SubAuthor : SubAuthorizedList) {
			if (checkSubAuthorized(SubAuthor) && !SubAuthor.IsAuthorize__c) {
				SubAuthor.IsAuthorize__c = true;
				updateSubAuthorizedList.add(SubAuthor);
			} else if (SubAuthor.IsAuthorize__c) {
				SubAuthor.IsAuthorize__c = false;
				updateSubAuthorizedList.add(SubAuthor);
			}
		}
		system.debug('---------4-------------updateSubAuthorizedList:' + updateSubAuthorizedList);
		// 后更新是否授权	，如果用户更新失败，那么就不会更新是否授权
		if (updateSubAuthorizedList.size() > 0) {
			update updateSubAuthorizedList;
		}

	}
	// 判断这个转授权是需要转审批还是需要取消转审批
	public static boolean checkSubAuthorized(SubAuthorized__c SubAuthorized) {
		if (SubAuthorized == null) {
			return false;
		}
		Date today = Date.today();
		Date tomorrow = today.addDays(1);
		Date twoDayLater = today.addDays(2);
		if (SubAuthorized.Status__c != null &&
		        SubAuthorized.Status__c.equals('已批准') && SubAuthorized.IsAuthorize__c == false
		        && SubAuthorized.AuthorizedStartDate__c <=  tomorrow
		        && SubAuthorized.AuthorizedEndDate__c >=  twoDayLater
		   ) {
			return true;
		}
		return false;
	}
}