/**
 * 客户同步
 */
public without sharing class AccountTrigger {
	// 已处理数据、AccountのTriggerの場合、使わない、WFがいろいろあるので。
	//public static Map<Id, Account> accountMap = new Map<Id, Account>();
	
	// 同步到 Account2__c (after insert, after update, before delete) 
	public static void syncAccount2(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		List<Account2__c> acc2List = new List<Account2__c>();
		List<Account2__c> afterInsertAcc2List = new List<Account2__c>();
		if (Trigger.isInsert || Trigger.isUpdate) {
			system.debug('=====afterUpsertToAccount2 start');
			for (Account acc : newList) {
				if (Trigger.isInsert || (Trigger.isUpdate
						&& (acc.ParentId != oldMap.get(acc.Id).ParentId
								|| acc.Name != oldMap.get(acc.Id).Name
						)
				)) {
					Account2__c acc2 = new Account2__c(Account_OrgId__c = ('' + acc.Id).substring(0, 15), Account_Org__c = acc.Id,
						Name = acc.Name, RecordType_DeveloperName__c = acc.RecordType_DeveloperName__c
					);
					acc2List.add(acc2);
					if (Trigger.isInsert) {
						afterInsertAcc2List.add(acc2);
					}
					// 1階層目、2階層目の場合、
					if (acc.ParentId == null
							|| (acc.ParentId != null && acc.Parent_Parent__c == null)
					) {
						acc2.Account__c = acc.Id;           // 主従項目
					}
					// 3階層目の場合
					else {
						acc2.Account__c = acc.ParentId;     // 主従項目
					}
					// TODO acc2のIdをAccountに書き戻す！必要がないかも！！確認中
				}
			}
			if (acc2List.size() > 0) {
				upsert acc2List Account_OrgId__c;
			}
			if (afterInsertAcc2List.size() > 0) {
				List<Account> afterInsertAcc2UpdateAccountList = new List<Account>();
				Set<Id> afterInsertAcc2UpdateAccountIdSet = new Set<Id>();
				for (Account2__c acc2 : afterInsertAcc2List) {
//                    // ありえないはず
//                    if (afterInsertAcc2UpdateAccountIdSet.contains(acc2.Account_OrgId__c)) {
//                        continue;
//                    } else {
						Account acc = new Account(Id = acc2.Account_OrgId__c, Account2__c = acc2.Id);
//                    }
					afterInsertAcc2UpdateAccountList.add(acc);
				}
				update afterInsertAcc2UpdateAccountList;
			}
		} else if (Trigger.isDelete) {
			system.debug('=====beforeDeleteToAccount2 start');
			List<Id> accIds = new List<Id>();
			for (Account acc : oldList) {
				accIds.add(acc.Id);
			}
			if (accIds.size() > 0) {
				List<Account2__c> delList = [select Id, Account_Org__c from Account2__c where Account_Org__c in : accIds];
				if (delList.size() > 0) {
					delete delList;
				}
			}
		}
	}
	
	// 同步到 MB_Account__c
	public static void syncMBAccount(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		// MB_客户插入用
		List<MB_Account__c> ins_mb_accounts = new List<MB_Account__c>();
		// MB_客户删除用
		List<Account> del_accounts = new List<Account>();
		List<MB_Account__c> del_mb_accounts = new List<MB_Account__c>();
		
		if (Trigger.isInsert) {
			for (Account acc : newList) {
				MB_Account__c mbacc = new MB_Account__c(
					  Account__c = acc.Id
					, CurrencyIsoCode = acc.CurrencyIsoCode
// CIC 125725 start
//                    , OwnerId = acc.OwnerId
					, Opp_OCM_text__c = acc.HP_146POCM_Category_From_Dept__c
					, State_Text__c = acc.Province_formula__c
					, Opportunity_Category_text__c = acc.Department_Class_Name__c
// CIC 125725 end
				);
				ins_mb_accounts.add(mbacc);
			}
		}
// CIC 130175 start
		else if (Trigger.isUpdate) {
			// NFM001 のところ、before insertと updateにて、OCM分类 と 省Text を更新しているはず
			// 診療科の場合、ここは各レコードのischanged 見るだけ にします。
			List<Account> accDpts = new List<Account>();
			List<Account> accAlls = new List<Account>();
			for (Account nr : newList) {
				system.debug('aaaaaa1:'+nr.RecordTypeId);
				system.debug('aaaaaa2:'+oldMap.get(nr.Id).RecordTypeId);
				system.debug('aaaaaa3:'+nr.OCM_Category__c);
				system.debug('aaaaaa4:'+oldMap.get(nr.Id).OCM_Category__c);
				system.debug('aaaaaa5:'+nr.State_Text__c);
				system.debug('aaaaaa6:'+oldMap.get(nr.Id).State_Text__c);
				if (nr.RecordTypeId !=  oldMap.get(nr.Id).RecordTypeId
						|| nr.OCM_Category__c !=  oldMap.get(nr.Id).OCM_Category__c
						|| nr.State_Text__c !=  oldMap.get(nr.Id).State_Text__c
				) {
					system.debug('xxxxxxxxxxxxxxx');
					if (String.isBlank(nr.Parent_Parent__c) == false) {
						accDpts.add(nr);
						accAlls.add(nr);
					} else {
						accAlls.add(nr);
					}
				}
			}
			Map<Id, Account> accDptMap = new Map<Id, Account>();
			if (accDpts.size() > 0) {
				system.debug('1111111111111');
				String[] needSendTypes = new String[] {'診療科 その他', '診療科 呼吸科', '診療科 婦人科', '診療科 普外科', '診療科 泌尿科', '診療科 消化科', '診療科 耳鼻喉科'};
				//  LD 20200807 优化account record type ID 读取方法 Start

				// 原逻辑
				// List<RecordType> rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :needSendTypes];
				
				// for (RecordType rect : rects) {
				// 	needSendRectMap.put(rect.Id, rect.Name);
				// }

				// 新逻辑
				String [] RecordTypeId = new String[] {System.Label.Department_OTH , System.Label.Department_BF , System.Label.Department_GYN , System.Label.Department_GS , System.Label.Department_URO , System.Label.Department_GI , System.Label.Department_ENT };
				system.debug('2222222222');
				Map<String, String> needSendRectMap = new Map<String, String>();
				needSendRectMap.put(RecordTypeId[0], needSendTypes[0]);
				needSendRectMap.put(RecordTypeId[1], needSendTypes[1]);
				needSendRectMap.put(RecordTypeId[2], needSendTypes[2]);
				needSendRectMap.put(RecordTypeId[3], needSendTypes[3]);
				needSendRectMap.put(RecordTypeId[4], needSendTypes[4]);
				needSendRectMap.put(RecordTypeId[5], needSendTypes[5]);
				needSendRectMap.put(RecordTypeId[6], needSendTypes[6]);

				//  LD 20200807 优化account record type ID 读取方法 End
				for (Account a : accDpts) {
					if (needSendRectMap.get(a.RecordTypeId) == null) {
						continue;
					}
					system.debug('333333333');
					accDptMap.put(a.Id, a);
				}
			}
			// MBこどもを更新
			ControllerUtil.updMBChildFromDpt(accDptMap);
			
			if (accAlls.size() > 0) {
				ControllerUtil.updMBAccountList(accAlls);
				system.debug('4444444444444');
			}
		}
// CIC 130175 end
		else if (Trigger.isDelete) {
			for (Account acc : oldList) {
				del_accounts.add(acc);
			}
		}
		if (del_accounts.size() > 0) {
			ControllerUtil.delMBAccountList(del_accounts);
		}
		if (ins_mb_accounts.size() > 0) {
			ControllerUtil.insMBAccountList(ins_mb_accounts);
		}
	}

	////CHAN-ADE32V 检查战略科室中的科室名是否重复 by wei
	public static void checkDepartment(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		System.debug('=============> start');

		Map<String, Account> dpartmentMap = new Map<String, Account>();
		Map<String, String> dpartmentMapDB = new Map<String, String>();
		Map<String, String> classMap = new Map<String, String>();
		List<String> accountDep = new List<String>();

		for (Account rd : newList) {
			Account old = oldMap == null ? new Account() : oldMap.get(rd.Id);
			if (rd.Department_Name__c != old.Department_Name__c){
				if (classMap.containsKey(rd.Department_Class__c)){
					Account temp = dpartmentMap.get(rd.Department_Class__c + rd.Department_Name__c);
					if (temp != null) {
						//if (temp.Department_Name__c == rd.Department_Name__c) {
						//    temp.addError('科室录入重复');
						//} else {
							//accountDep.add(rd.Department_Class__c);
						//    dpartmentMap.put(rd.Department_Class__c + rd.Department_Name__c,rd);    
						//}
						temp.addError('科室录入重复');
					} else {
						dpartmentMap.put(rd.Department_Class__c + rd.Department_Name__c,rd);
					}
				} else {
					classMap.put(rd.Department_Class__c,rd.Department_Name__c);
					if(rd.Department_Class__c != null)				//zhj 2022-12-21
						accountDep.add(rd.Department_Class__c);
					dpartmentMap.put(rd.Department_Class__c + rd.Department_Name__c,rd);
				} 
			}
		} 
		System.debug('classMap============〉' +  classMap);
		 System.debug('accountDep============〉' +  accountDep);
		  System.debug('dpartmentMap============〉' +  dpartmentMap);

		if (accountDep.size() > 0) {
			List<Account>  dpartmentChk = [select Id,Department_Class__c,Department_Name__c from Account where Department_Class__c in : accountDep];

			for (Account chk : dpartmentChk) {

				dpartmentMapDB.put(chk.Department_Class__c + chk.Department_Name__c , chk.Id);
		   
			}
			System.debug('dpartmentMapDB============〉' +  dpartmentMapDB);
			for (String tmpStr : dpartmentMap.keySet()) {
				if (dpartmentMapDB.containsKey(tmpStr)){
					if (Trigger.isInsert) {
						Account tmpInsert = dpartmentMap.get(tmpStr);
						tmpInsert.addError('科室已经存在');
					} else if (Trigger.isUpdate){
						Account tmpUpdate = dpartmentMap.get(tmpStr);
						if (String.valueOf(tmpUpdate.Id) != String.valueOf(dpartmentMapDB.get(tmpStr))) {
							tmpUpdate.addError('科室已经存在');
						} else {
							continue;
						}
					}
				} else {
					continue;
				}
			}
		}	
		System.debug('=============> end');   
	}
	

	public static void changeOwnerId(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		System.debug('===========> start');
		List<Account> accList = new List<Account>();
		
		if (Trigger.isUpdate) {
			Boolean flag = false;
			for (Account a : newList) {
				if(Trigger.isUpdate && a.OwnerId != oldMap.get(a.Id).OwnerId){
					flag = true;                                            //取得所有战略科室所有人改变的战略科室id
				}
			}
			if(flag == false){
				return;
			}
			String[] departmentTypes = new String[] {'戦略科室分類 その他' , '戦略科室分類 呼吸科', '戦略科室分類 婦人科', '戦略科室分類 普外科', '戦略科室分類 泌尿科', '戦略科室分類 消化科', '戦略科室分類 耳鼻喉科','戦略科室分類ET'};
			//  LD 20200807 优化account record type ID 读取方法 Start

			// 原逻辑
			// List<RecordType> rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :departmentTypes];
			
			// for (RecordType rect : rects) {
			// 	rectMap.put(rect.Id, rect.Name);
			// }

			// 新逻辑
			String[] StrategicDepartmentId = new String[] {System.Label.Department_Class_OTH , System.Label.Department_Class_BF , System.Label.Department_Class_GYN , System.Label.Department_Class_GS , System.Label.Department_Class_URO , System.Label.Department_Class_GI , System.Label.Department_Class_ENT , System.Label.Department_Class_ET};
			Map<String, String> rectMap = new Map<String, String>();
			rectMap.put(StrategicDepartmentId[0], departmentTypes[0]);
			rectMap.put(StrategicDepartmentId[1], departmentTypes[1]);
			rectMap.put(StrategicDepartmentId[2], departmentTypes[2]);
			rectMap.put(StrategicDepartmentId[3], departmentTypes[3]);
			rectMap.put(StrategicDepartmentId[4], departmentTypes[4]);
			rectMap.put(StrategicDepartmentId[5], departmentTypes[5]);
			rectMap.put(StrategicDepartmentId[6], departmentTypes[6]);
			rectMap.put(StrategicDepartmentId[7], departmentTypes[7]);

			//  LD 20200807 优化account record type ID 读取方法 End

			List<String> dcIds = new List<String>();   
			//List<String> contactIds = new List<String>();                
			for (Account a : newList) {
				if (rectMap.get(a.RecordTypeId) == null) {
					continue;
				}
				if(Trigger.isUpdate && a.OwnerId != oldMap.get(a.Id).OwnerId){
					dcIds.add(a.Id);                                            //取得所有战略科室所有人改变的战略科室id
				}

			}

			
			if(dcIds.size() > 0){
				List<String> upIds = new List<String>();
				List<Account> accDepList = [select Id, OwnerId,ParentId from Account where ParentId in :dcIds];  //取出所有的战略科室所有人改变的科室信息
				
				Map<String, Account> accoppMap = new Map<String, Account>();
				for (Account a : accDepList) {
					if(!accoppMap.containsKey(a.ParentId)){
					upIds.add(a.ParentId); 
					}
					accoppMap.put(a.ParentId, a);
				}

				Map<id, Account> accMap = new Map<id, Account>();
				if(upIds.size() > 0){
					//所有人改变的战略科室
					List<Account> acckList = [select id,OwnerId from Account where id in :upIds];
					for(Account acc : acckList){
						accMap.put(acc.id, acc);
					}
				}

				List<Account> accUpdateList = new List<Account>();
				for (Account a : accDepList) {
					Account accz = new Account();
					accz = accMap.get(a.ParentId);
					a.OwnerId = accz.OwnerId;
					accUpdateList.add(a);
				}

				//取战略科室所有人改变的客户人员信息
				List<String> conIds = new List<String>();
				List<Contact> ConList = [select id, Name, OwnerId, Strategic_dept_Class__c from Contact where Strategic_dept_Class__c in :dcIds];
				Map<String,Contact> contaMap = new Map<String,Contact>();
				for(Contact c :ConList){
					if(!contaMap.containsKey(c.Strategic_dept_Class__c)){
						conIds.add(c.Strategic_dept_Class__c);
					}
					contaMap.put(c.Strategic_dept_Class__c, c);
				}

				Map<id, Account> conMap = new Map<id, Account>();
				if(conIds.size() > 0){
					//所有人改变的战略科室
					List<Account> acckconList = [select id,OwnerId from Account where id in :conIds];
					for(Account acc : acckconList){
						conMap.put(acc.id, acc);
					}
				}

				List<Contact> conUpdateList = new List<Contact>();
				for (Contact c : ConList) {
					Account accc = new Account();
					accc = conMap.get(c.Strategic_dept_Class__c);

					c.OwnerId = accc.OwnerId;
					conUpdateList.add(c);
				}
				update accUpdateList;
				update conUpdateList;

			}

		}
		System.debug('===========> end');
	}

	public static void setDepartmentOwner(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		Boolean flag = false;
		for (Account a : newList) {
			if (a.OwnerId != oldMap.get(a.Id).OwnerId){
				flag = true;
			}
		}
		if (flag == false){
			return;
		}

		String[] departmentTypes = new String[] {'戦略科室分類 その他', '戦略科室分類 呼吸科', '戦略科室分類 婦人科', '戦略科室分類 普外科', '戦略科室分類 泌尿科', '戦略科室分類 消化科', '戦略科室分類 耳鼻喉科','戦略科室分類ET'};
		//  LD 20200807 优化account record type ID 读取方法 Start

		// 原逻辑
		// List<RecordType> rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :departmentTypes];

		// for (RecordType rect : rects) {
		// 	rectMap.put(rect.Id, rect.Name);
		// }

		// 新逻辑
		String[] StrategicDepartmentId = new String[] {System.Label.Department_Class_OTH , System.Label.Department_Class_BF , System.Label.Department_Class_GYN , System.Label.Department_Class_GS , System.Label.Department_Class_URO , System.Label.Department_Class_GI , System.Label.Department_Class_ENT , System.Label.Department_Class_ET};
		Map<String, String> rectMap = new Map<String, String>();
		rectMap.put(StrategicDepartmentId[0], departmentTypes[0]);
		rectMap.put(StrategicDepartmentId[1], departmentTypes[1]);
		rectMap.put(StrategicDepartmentId[2], departmentTypes[2]);
		rectMap.put(StrategicDepartmentId[3], departmentTypes[3]);
		rectMap.put(StrategicDepartmentId[4], departmentTypes[4]);
		rectMap.put(StrategicDepartmentId[5], departmentTypes[5]);
		rectMap.put(StrategicDepartmentId[6], departmentTypes[6]);
		rectMap.put(StrategicDepartmentId[7], departmentTypes[7]);
		//  LD 20200807 优化account record type ID 读取方法 End

		List<String> dcIds = new List<String>();
		for (Account a : newList) {
			if (rectMap.get(a.RecordTypeId) == null) {
				continue;
			}
			if(a.OwnerId != oldMap.get(a.Id).OwnerId){
				dcIds.add(a.Id);
			}

		}

		Map<String, Account> updMap = new Map<String, Account>();
		if(dcIds.size() > 0){
			//停用：不再从战略科室获取担当人信息
            //for (String dcId : dcIds) {
            //    String hpid = newMap.get(dcId).ParentId;
            //    if (updMap.containsKey(hpid) == true) {
            //        Account acc = updMap.get(hpid);
            //        String rt = rectMap.get(newMap.get(dcId).RecordTypeId);
            //        String owner = newMap.get(dcId).OwnerId;
            //        if (rt == '戦略科室分類 消化科') {
            //            acc.GI_Main__c = owner;
            //        } else if (rt == '戦略科室分類 呼吸科') {
            //            acc.BF_owner__c = owner;
            //        } else if (rt == '戦略科室分類 普外科') {
            //            acc.SP_Main__c = owner;
            //        } else if (rt == '戦略科室分類 耳鼻喉科') {
            //            acc.ENT_owner_ID__c = owner;
            //        } else if (rt == '戦略科室分類 泌尿科') {
            //            acc.URO_owner_ID__c = owner;
            //        } else if (rt == '戦略科室分類 婦人科') {
            //            acc.GYN_owner__c = owner;
            //        } else if (rt == '戦略科室分類ET') {
            //            acc.ET_owner__c = owner;
            //        }
            //    } else {
            //        Account acc = new Account(Id = hpid);
            //        String rt = rectMap.get(newMap.get(dcId).RecordTypeId);
            //        String owner = newMap.get(dcId).OwnerId;
            //        if (rt == '戦略科室分類 消化科') {
            //            acc.GI_Main__c = owner;
            //        } else if (rt == '戦略科室分類 呼吸科') {
            //            acc.BF_owner__c = owner;
            //        } else if (rt == '戦略科室分類 普外科') {
            //            acc.SP_Main__c = owner;
            //        } else if (rt == '戦略科室分類 耳鼻喉科') {
            //            acc.ENT_owner_ID__c = owner;
            //        } else if (rt == '戦略科室分類 泌尿科') {
            //            acc.URO_owner_ID__c = owner;
            //        } else if (rt == '戦略科室分類 婦人科') {
            //            acc.GYN_owner__c = owner;
            //        } else if (rt == '戦略科室分類ET') {
            //            acc.ET_owner__c = owner;
            //        }
            //        updMap.put(hpid, acc);
            //    }
            //}
		}

		if (updMap.values() != null && updMap.values().size() > 0) {
			update updMap.values();
		}
	}

	// FSE-GI主担当 / FSE-SP主担当 变更时更新 修理
	public static void fseChangeToUpdRepair(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		List<String> accIdList = new List<String> ();
		List<Repair__c> repList = new List<Repair__c> ();

		for (Account acc : newList) {
			if (acc.RecordTypeId == '01210000000QemG' && (oldMap.get(acc.Id).FSE_GI_Main_Leader__c != acc.FSE_GI_Main_Leader__c || oldMap.get(acc.Id).FSE_SP_Main_Leader__c != acc.FSE_SP_Main_Leader__c)) {
				accIdList.add(acc.Id);
			}
		}

		if (accIdList.size() > 0) {
			repList = [select Id, Hospital__c, Account__r.Parent.RecordTypeId, FSE_Work_Location__c from Repair__c where Hospital__c in : accIdList];
			if (repList.size() > 0) {
				List<Repair__c> updRepair = new List<Repair__c> ();
				Map <Id, Account> workLocationList = new Map <Id, Account> ([select Id, Name, FSE_GI_Main_Leader__r.Work_Location__c, FSE_SP_Main_Leader__r.Work_Location__c from Account Where Id in : accIdList]);
				for (Repair__c re : repList) {
					if (((re.Account__r.Parent.RecordTypeId == '01210000000QemL' || 
						re.Account__r.Parent.RecordTypeId == '01210000000QezZ' || 
						re.Account__r.Parent.RecordTypeId == '01210000000QemQ') && 
					  oldMap.get(re.Hospital__c).FSE_GI_Main_Leader__c != newMap.get(re.Hospital__c).FSE_GI_Main_Leader__c &&
					  workLocationList.get(re.Hospital__c).FSE_GI_Main_Leader__r.Work_Location__c != re.FSE_Work_Location__c) ||
					  (( re.Account__r.Parent.RecordTypeId == '01210000000Qeze' || 
						re.Account__r.Parent.RecordTypeId == '01210000000Qezj' || 
						re.Account__r.Parent.RecordTypeId == '01210000000Qezt' ||
						re.Account__r.Parent.RecordTypeId == '01210000000Qezo' || 
						re.Account__r.Parent.RecordTypeId == '01210000000Qezy') &&
					  oldMap.get(re.Hospital__c).FSE_SP_Main_Leader__c != newMap.get(re.Hospital__c).FSE_SP_Main_Leader__c &&
					  workLocationList.get(re.Hospital__c).FSE_SP_Main_Leader__r.Work_Location__c != re.FSE_Work_Location__c)) {
						updRepair.add(new Repair__c(Id = re.Id));
					}
				}

				if (updRepair.size() > 0) {
					update updRepair;
				}
			}
		}
	}
	//SWAG-CGG7UK【委托】 【P-OBSAP经销商协议】经销商协议所有人的修改权限 fy start
	public static void UpdateSalesAssistant(List<Account> newList, Map<Id, Account> newMap, List<Account> oldList, Map<Id, Account> oldMap) {
		// for(Account account : newList){
		// }
		System.debug('newList[0]'+newList[0]);
		System.debug('newList[0].OCM_man_province_HP__c'+newList[0].OCM_man_province_HP__c);
	}
	//SWAG-CGG7UK【委托】 【P-OBSAP经销商协议】经销商协议所有人的修改权限 fy end
}