public with sharing class otherLookUp {
    
    @AuraEnabled(cacheable=true)
    public static List<Record> lookUp(String searchTerm, String objName, String filter,String visitPlaceId) {
        system.debug('lookUp');
        system.debug('objName:'+objName);
        system.debug('searchTerm:'+searchTerm);
        system.debug('filter:'+filter);
        system.debug('visitPlaceId:'+visitPlaceId);
        User loginUser = [Select Id, State_Hospital__c, Job_Category__c from User where Id =: UserInfo.getUserId()];
        String reporterState = loginUser.State_Hospital__c;

        List<Record> recordList = new List<Record>();
        String qureyObjName = 'Account';
        if(objName == 'SearchVisitorPlace_Campaign') {
            qureyObjName = 'Campaign';
        } 
        if(objName == 'Opportunity') {
            qureyObjName = 'Opportunity';
        }
        
        if(objName == 'MaintenanceContract') {
            qureyObjName = 'Maintenance_Contract__c';
        } 
        if(objName == 'InfrastructureProject') {
            qureyObjName = 'Infrastructure_Project__c';
        }

        String searchQuery = 'select Id,name from '+qureyObjName+' where Id <> null ';
        //zzm 2023-11-24 日报询价加科室和状态 start
        if(objName == 'Opportunity') {
            searchQuery = 'Select Id, Opportunity_No__c, name, Department_Name__c,Field1__c,Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from  '+qureyObjName+' where Id <> null '; 
        }
        //zzm 2023-11-24 日报询价加科室和状态 end
        
        
        searchQuery += nameCondition(searchTerm,qureyObjName);
        // if(String.isNotBlank(searchTerm)){
        //     if(qureyObjName=='Account'){
        //         searchQuery += 'and Name_for_Daily_Report_text__c like \'%'+ searchTerm + '%\'';

        //     } else{
        //         searchQuery += 'and Name LIKE \'%' + searchTerm + '%\'';
        //     }
        // }
        //访问场所
        if(objName=='SearchVisitorPlace') {
            searchQuery += ' and  Hospital__r.RecordType.DeveloperName = \'HP\' and Is_Active__c <> \'無効\' order by Name ';
        }
        // String queryString = 'select Id, Name from Account where' + nameCondition + ' Is_Active_Formula__c = \'有效\' and RecordType.DeveloperName = \'Agency\' order by Name limit 51';
        if(objName=='SearchVisitorPlace_Sales') {
            searchQuery += ' and RecordType.DeveloperName = \'Agency\' and Is_Active_Formula__c = \'有效\' order by Name ';
        }
        // [select Id, Name from Account where Is_Active__c != '無効' and Name like :nameCondition and RecordType.DeveloperName = 'Training'  order by Name limit 30]
        if(objName=='SearchVisitorPlace_Training') {
            searchQuery += ' and RecordType.DeveloperName = \'Training\' and Is_Active__c <> \'無効\' order by Name ';
        }
        // if(objName=='SearchVisitorPlace_Campaign' || objName == 'InfrastructureProject') {
        //     searchQuery += '  id !=null ';
        // }
        if(objName == 'InfrastructureProject') {
            Account a = null;
            try {
                a = [select Id, Hospital__c from Account where Id=:visitPlaceId];
            }
            catch ( System.QueryException qe) {
                return recordList;
            }
            
            
            searchQuery += '  and OCSM_Hospital__c=\'' + a.Hospital__c + '\' ';
        }

        //新建联系人，只能选择该医院下的所有的三级科室--没做出来
        // if(objName == 'ContactDepartment') {
        //     List<RecordType>  recordTypes= [select Id from RecordType where  SobjectType = 'Account' and DeveloperName in ('Department_GYN','Department_OTH','Department_BF','Department_GI','Department_GS','Department_URO','Department_ENT','Department')];
        //     List<String> recordTypeIds = new List<String>();
        //     for(RecordType rt : recordTypes) {
        //         recordTypeIds.add(rt.Id);
        //     }
        //     Account a = null;
        //     a = [select Id, Hospital__c from Account where Id=:visitPlaceId];
        //     searchQuery += '  and OCSM_Hospital__c=\'' + a.Hospital__c + '\'  and RecordTypeId in :recordTypeIds';
        // }
        Date toDate = Date.today();
        Date lastDate = toDate.addYears(-1);
        // String  today = String.valueOf(Date.newInstance(toDate.year(), toDate.month(), toDate.day())).substring(0,10);
        // String  lastDate = String.valueOf(Date.newInstance(toDate.year()-1, toDate.month(), toDate.day())).substring(0,10);
        // Date lastDate = Date.newInstance(toDate.year()-1, toDate.month(), toDate.day());
           
        //询价单独处理

        if(objName=='Opportunity') { 
            if(String.isNotBlank(visitPlaceId)){
                searchQuery += ControllerUtil.getOppSearchSQOLforLwc(visitPlaceId,toDate,lastDate);

                // searchQuery = ControllerUtil.getOppSearchSQOL(visitPlaceId,'  Id <> null  ' +nameCondition(searchTerm,qureyObjName));
            }
        }
        searchQuery += ' limit 31'; 
        
            
        system.debug('searchQuery:'+searchQuery);
        List<Sobject> queryResult = new List<sObject>();
        //维修合同单独处理
        if(objName == 'MaintenanceContract') {
            queryResult = searchMc(searchTerm,visitPlaceId);
        } else  if(objName == 'Opportunity') {
            queryResult = ControllerUtil.getOpportunitys(searchQuery);
        }else{
            queryResult = Database.query(searchQuery);
        }
        
        Map<Id, Account> accMap = new Map<Id, Account>();
        if(queryResult.size()>0){
            for(Sobject sobj : queryResult){
                Record r = new Record();
                r.Id = sobj.id;
                r.Name = (String)sobj.get('name');
                //zzm 2023-11-24 日报询价加科室和状态 start
                if(objName=='Opportunity') {
                    // r.Department_Name = (String)sobj.get('Department_Name__c');
                    // r.Competitor = (String)sobj.get('Competitor__c');
                     r.Name += '(' +(String)sobj.get('Department_Name__c') +')' +(String)sobj.get('Competitor__c');

                }
                //zzm 2023-11-24 日报询价加科室和状态 end
                recordList.add(r);
                accMap.put(sobj.id,null);
            }
        }
        if(objName=='SearchVisitorPlace'){
            if(recordList.size()<=50){
                // さらに省単位のデータを検索
                String nameCondition = nameCondition(searchTerm,'Account');
                // Map<Id, Account> stateDepartmentMap = selectDepartByHospitalState(' and Name_for_Daily_Report_text__c like \'%'+ searchTerm + '%\'  ', 31 - recordList.size());
                Map<Id, Account> stateDepartmentMap = ControllerUtil.selectDepartByHospitalState(' Id<>null ' +nameCondition + ' and ',reporterState, 51 - recordList.size());
                if (stateDepartmentMap.size() > 0) {
                    for (Id accId : stateDepartmentMap.keySet()) {
                        if (!accMap.containsKey(accId)) {
                            Record r = new Record();
                            r.Id = accId;
                            r.Name = stateDepartmentMap.get(accId).Name;
                            recordList.add(r);
                        }
                    }
                }
            }
        }
        system.debug(recordList);
        return recordList;
    }
    public static String nameCondition(String searchTerm,String qureyObjName) {
        String nameCondition = '';
        List<String> qwords = new List<String>();
        List<String> qwordstmp = searchTerm.split(' ');
        for (String qword : qwordstmp) {
            if (String.isBlank(qword) == false) {
                qwords.add('%' + String.escapeSingleQuotes(qword.replaceAll('%', '')) + '%');
                if(qureyObjName=='Account'){
                    nameCondition += ' and  Name_for_Daily_Report_text__c like \'' + qwords[qwords.size() - 1] + '\'  ';

                } else{
                    nameCondition += ' and Name like \'' + qwords[qwords.size() - 1] + '\'  ';
                }
            }
        }
        return nameCondition;
    }
   
    public class Record {
        @AuraEnabled public String Id;
        @AuraEnabled public String Name;
    }
    /*public static Map<Id, Account> selectDepartByHospitalState(String nameCondition, Integer limitCnt) {
        User loginUser = [Select Id, State_Hospital__c, Job_Category__c from User where Id =: UserInfo.getUserId()];
        String reporterState = loginUser.State_Hospital__c;
        String queryString = 'select Id, Name, Department_Class__c, Department_Class__r.Name, Hospital__c, Hospital__r.Name from Account where Id<>null ' + nameCondition + 'and Hospital__r.RecordType.DeveloperName = \'HP\' and Is_Active__c <> \'無効\'';
        if (loginUser.Job_Category__c == 'GI市场'
                || loginUser.Job_Category__c == 'SP市场'
                || loginUser.Job_Category__c == '服务本部'
                || loginUser.Job_Category__c == '培训'
        ) {
            // 全国範囲、なにもしない
        } else {
            // 省単位の条件追加
            system.debug('selectDepartByHospitalState reporterState=' + reporterState);
            queryString += ' and Parent.Parent.State_Master__r.Name = :reporterState';
        }
        queryString += ' order by Name limit '+limitCnt;
        system.debug('selectDepartByHospitalState queryString=' + queryString);
        return new Map<Id, Account>((List<Account>) Database.query(queryString));
    }*/

    //检索询价
    /*public static String getOppSearchSQOL(String visitorPlaceId,Date today,Date lastDate) {
        Account a = new Account();
        List<Account> accountList = [select Id, Hospital__c, Agent_Ref__c, Parent.Parent.RecordType.DeveloperName, Parent.RecordType.DeveloperName, RecordType.DeveloperName from Account where Id=:visitorPlaceId];
        if(accountList.size()>0) {
            a = accountList[0];
        }
        
        
        // 検索
        String queryString = ' ';
        // String temptoday = Date.today().format().replace('/', '-');
        // String tempLastDate = Date.today().addDays(-365).format().replace('/', '-');
        // Date today = Datetime.now().date();
        // Date lastDate = Datetime.now().date().addyears(-1);
        
        // 病院
        if (a.Parent.Parent.RecordType.DeveloperName == 'HP') {



        // queryString = 'Select Id, Opportunity_No__c, Name, toLabel(StageName), Department_Name__c,Field1__c,Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from Opportunity where' + nameCondition 
            // + ' Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > '+tempLastDate+' and Shipping_Finished_Day__c <= '+temptoday+' and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c limit 31';


            queryString +=  '  and Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > :lastDate and Shipping_Finished_Day__c <= :today and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c '; 
            // queryString +=  ' and   Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and CALENDAR_YEAR(Created_Day__c) <> 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c '; 
        }
        // 販売店
        else if (a.RecordType.DeveloperName == 'Agency') {
            queryString +=  ' and Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\' and Shipping_Finished_Day__c > :lastDate and Shipping_Finished_Day__c <= :today and CALENDAR_YEAR(Created_Day__c) != 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c';
            // queryString +=  ' and  Account.Hospital__c=\'' + a.Hospital__c + '\' and ( StageName IN (\'引合\',\'注残\') or ( StageName = \'出荷\'  CALENDAR_YEAR(Created_Day__c) <> 2012 )) and RecordTypeId in (\'01210000000QekK\',\'012100000006KMeAAM\') order by Name, Opportunity_No__c, Department_Name__c ';
           
        }
        return queryString;
    }*/



    //检索合同
    
    public static  List<Maintenance_Contract__c> searchMc(String query, String visitorPlaceId) {
        // Xin_SearchOpportunityと同じにする
        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] + '\' ';
            }
        }
        
        Account a = null;
        try {
            a = [select Hospital__c from Account where Id=:visitorPlaceId];
        }
        catch ( System.QueryException qe) {
            return new List<Maintenance_Contract__c>();
        }
        
        system.debug('cond=' + nameCondition);
        
        String queryString = 'select Id, Name,Management_Code__c,Status__c from Maintenance_Contract__c where Id<>null ' + nameCondition + '  and Hospital__c=\'' + a.Hospital__c + '\' AND Status__c in (\'契約\',\'契約満了\')  order by Status__c ASC limit 31';
        System.debug(queryString);
        return (List<Maintenance_Contract__c>) Database.query(queryString);
    }
 

}