public with sharing class CM_SearchDepartmentServiceController {
	public List<Account> results {get; private set;}
	public Boolean getIsOverLimit() {
		if (results != null && results.size() > 50) {
			return true;
		}
		return false;
	}
	public CM_SearchDepartmentServiceController () {
		this.results = new List<Account>();
	}

	public void search() {
		// 検索条件を用意
		String query = System.currentPageReference().getParameters().get('q');
		String reporterState = System.currentPageReference().getParameters().get('r');
		if (query == null || query == '') {
			return;
		}
		system.debug('reporterState=' + reporterState);
		this.search(query, reporterState);
	}

	/**
	 * Xin_SearchVisitorPlaceRest などから呼び出す
	 */
	public void search(String query, String reporterState) {
		List<String> qwords = new List<String>();
		List<String> qwordstmp = query.split(' ');
		String nameCondition = '';
		for (String qword : qwordstmp) {
			if (String.isBlank(qword) == false) {
				qwords.add('%' + String.escapeSingleQuotes(qword.replaceAll('%', '')) + '%');
				nameCondition += ' Name like \'' + qwords[qwords.size() - 1] + '\' and';
			}
		}

		if (qwords.size() < 2 && query.length() < 3) {
			return;
		}

		// 検索
		String queryString = 'select Id, Name, Department_Class__c, Department_Class__r.Name, Hospital__c, Hospital__r.Name from Account where' + nameCondition + ' Parent.Parent.RecordType.DeveloperName = \'HP\' and Is_Active__c <> \'無効\' order by Name limit 51';
		system.debug('queryString=' + queryString);
		Map<Id, Account> accMap = new Map<Id, Account>((List<Account>) Database.query(queryString));
		system.debug('accMap' + accMap);
		if (accMap.size() <= 50) {
			// さらに省単位のデータを検索
			nameCondition += ' Parent.Parent.RecordType.DeveloperName = \'HP\' and ';
			Map<Id, Account> stateDepartmentMap = ControllerUtil.selectDepartByHospitalState(nameCondition, reporterState, 51 - accMap.size());
			if (stateDepartmentMap.size() > 0) {
				for (Id accId : stateDepartmentMap.keySet()) {
					if (!accMap.containsKey(accId)) {
						accMap.put(accId, stateDepartmentMap.get(accId));
					}
				}
			}
		}
		this.results = accMap.values();                         // values()の場合、順序わからないです
		this.results.sort();                                    // order by Name
	}
}