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

    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('query:' + query);
        System.debug('reporterState:' + reporterState);
        System.debug('reportDate:' + reportDate);
        List<String> qwords = new List<String>();
        List<String> qwordstmp = query.split(' ');
        String repReportDate = reportDate.replace('-', '/');
        String[] splReportDate = repReportDate.split('/');
        Date reportDateParam = Date.newInstance(Integer.valueOf(splReportDate[0]), Integer.valueOf(splReportDate[1]), Integer.valueOf(splReportDate[2]));
        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;
        }

        system.debug('cond=' + nameCondition);
        
        // 検索
        //this.results = [select id, Name from Account where Delete_Flag__c = false and Name like :nameCondition and RecordTypeId in : rtList and Contract_Fiscal_Period__c = :Contract_Fiscal_Period order by Name limit 30];
        //this.results = [select Id, Name from Account where Is_Active_Formula__c = '有效' and Name like :nameCondition and RecordType.DeveloperName = 'AgencyContract' and Parent.Is_Active_Formula__c = '有效' and Contract_Decide_Start_Date__c <=:Date.parse(reportDate) and Contract_Decide_End_Date__c >=:Date.parse(reportDate) order by Name limit 51];
        String queryString = 'select Id, Name from Account where' + nameCondition + ' Is_Active_Formula__c = \'有效\' and RecordType.DeveloperName = \'Agency\' order by Name limit 51';
        system.debug('queryString=' + queryString);
        this.results = Database.query(queryString);
    }
}