/* 备品智能化 add by dzk
   事件copy日报组件,将without sharing 改为 with sharing
*/
public with sharing class otherLookUpEvent {
    
    @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 ';
        if(objName == 'Opportunity') {
            // 2023-12-04 update by du Start 新建事件时,涉及询价查询时,附带询价状态 
            searchQuery = 'Select Id,StageName__c, Opportunity_No__c, name, Department_Name__c,Field1__c,Close_Forecasted_Date__c, Competitor__c, Wholesale_Price__c from  '+qureyObjName+' where Id <> null AND StageName  IN (\'引合\') '; 
            // 2023-12-04 update by du End 新建事件时,涉及询价查询时,附带询价状态 
        }
        searchQuery += nameCondition(searchTerm,qureyObjName);

        //访问场所
        if(objName=='SearchVisitorPlace') {
            searchQuery += ' and  Hospital__r.RecordType.DeveloperName = \'HP\' and Is_Active__c <> \'無効\' order by Name ';
        }
        if(objName=='SearchVisitorPlace_Sales') {
            searchQuery += ' and RecordType.DeveloperName = \'Agency\' and Is_Active_Formula__c = \'有效\' order by Name ';
        }
        if(objName=='SearchVisitorPlace_Training') {
            searchQuery += ' and RecordType.DeveloperName = \'Training\' and Is_Active__c <> \'無効\' order by Name ';
        }
        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 + '\' ';
        }

        Date toDate = Date.today();
        Date lastDate = toDate.addYears(-1);
        if(objName=='Opportunity') { 
            if(String.isNotBlank(visitPlaceId)){
                searchQuery += ControllerUtilEvent.getOppSearchSQOLforLwc(visitPlaceId,toDate,lastDate);
            }
        }
        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 = ControllerUtilEvent.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');
                if(objName=='Opportunity') {
                    // 2023-12-04 update by du Start 新建事件时,涉及询价查询时,附带询价状态 
                    r.Name += '(' + (String)sobj.get('StageName__c') +')' +  '(' +(String)sobj.get('Department_Name__c') +')' +(String)sobj.get('Competitor__c')  ;
                    // 2023-12-04 update by du 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 = 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  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);
    }
 
}