public with sharing class lexXinSearchVisitorPlaceController {
    public static List<Account> results = new List<Account>();
	@AuraEnabled
	public static List<Account> getResults(){
		return results;
	}
	@AuraEnabled
	public static Boolean getIsOverLimit() {
		if (results != null && results.size() > 50) {
			return true;
		}
		return false;
	}


	/**
	 * Xin_SearchVisitorPlaceRest などから呼び出す
	 */
	@AuraEnabled
    public static void search(String query, String reporterState) {
		if (query == null || query == '') {
			return;
		}
		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_for_Daily_Report_text__c like \'' + qwords[qwords.size() - 1] + '\' and';
			}
		}
		
		if(qwords.size() < 2 && query.length() < 3) {
			return;
		}

	    // 検索
//	    this.results = [select id, Name from Account where Name like :nameCondition and Parent.Parent.RecordType.DeveloperName = 'HP' and Is_Active__c <> '無効' and Parent.Parent.Is_Active__c <> '無効' order by Name limit 30];
        String queryString = 'select Id, Name, Department_Class__c, Department_Class__r.Name, Hospital__c, Hospital__r.Name from Account where' + nameCondition + ' Hospital__r.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));
	    if (accMap.size() <= 50) {
	        // さらに省単位のデータを検索
	        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));
	                }
	            }
	        }
	    }
	    results = accMap.values();                         // values()の場合、順序わからないです
	    results.sort();                                    // order by Name
	    //this.results = Database.Query('select id, Name from Account where Name like ' + nameCondition + ' AND Id NOT IN (select AccountId From AccountShare where UserOrGroupId = \'00510000000gaBh\' and RowCause = \'ImplicitParent\' ) order by Name limit 30');
	}
}