public with sharing class Xin_SearchVisitorPlace_Campaign {
    public List<Campaign> results {get; private set;}
    public Boolean getIsOverLimit() {
        if (results != null && results.size() > 30) {
            return true;
        }
        return false;
    }

    public Xin_SearchVisitorPlace_Campaign() {
        this.results = new List<Campaign>();
    }

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

    //public void search(String query, String reporterState, String reportDate) {
    //    String nameCondition = '%' + String.escapeSingleQuotes(query.replaceAll('%', '')) + '%';
    //    system.debug('cond=' + nameCondition);

        // 検索
    //   this.results = [select Id, Name from Campaign where Name like :nameCondition order by Name limit 31];
    //}

    public void search(String query, String reporterState, String reportDate) {
        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 += ' and Name like \'' + qwords[qwords.size() - 1] + '\' ';
            }
        }

        system.debug('cond=' + nameCondition);

        String queryString = 'select Id, Name from Campaign where Id != null ' + nameCondition + 'order by Name limit 31';

        system.debug('queryString=' + queryString);

        Map<Id, Campaign> accMap = new Map<Id, Campaign>((List<Campaign>) Database.query(queryString));

        //String nameCondition = '%' + String.escapeSingleQuotes(query.replaceAll('%', '')) + '%';
        
        this.results = accMap.values();                         // values()の場合、順序わからないです
        this.results.sort();   
    }
}