public without sharing class SearchContactLWCController {
    public String searchKeyWord{set;get;}
    public String staticResource {get; set;}
    public String contactAWSIds {set;get;}
    public String contactsInfo {set;get;}
    public String PIPL_Search_Contact_Label{set;get;}
    public String aId{set;get;}

    public String ObjectType {set;get;}
    public String ObjectTypeLabel {set;get;}
    public String FieldNameList{set;get;}
	public String FieldApiNameList{set;get;}
    // public String FieldWhereSQL{set;get;}
	public String QueryFieldName{set;get;}
	public String QueryFieldApiName{set;get;}
	public String inputHiddenId{set;get;}
    public String inputFieldId{set;get;}
    public String SelectObj{set;get;}
    public String SelectFld{set;get;}
    public String setVal{set;get;}
    public String FilterSql{set;get;}
    public String accountId{set;get;}   //deloitte-亚楠 20240202 
    public static Boolean checkNullString(String inputString){
        if(String.isEmpty(inputString)||String.isBlank(inputString)){
            return true;
        }
        return false;
    }
    //2023 08 30 张赫阳 PIPL页面改造 start
    public String OFSType {set;get;}
    //2023 08 30 张赫阳 PIPL页面改造 end
    public SearchContactLWCController() {
        accountId = ApexPages.currentPage().getParameters().get('accountId');//deloitte-亚楠 20240202 
        searchKeyWord = ApexPages.currentPage().getParameters().get('searchContactKeyWord');
        //2023 08 30 张赫阳 PIPL页面改造 start
        OFSType = ApexPages.currentPage().getParameters().get('Type');
        
        ObjectType = ApexPages.currentPage().getParameters().get('ObjectType');
        QueryFieldApiName = ApexPages.currentPage().getParameters().get('QueryFieldApiName');
        inputHiddenId = ApexPages.currentPage().getParameters().get('inputHiddenId');
        inputFieldId = ApexPages.currentPage().getParameters().get('inputFieldId');
        SelectObj = ApexPages.currentPage().getParameters().get('SelectObj');
        ObjectTypeLabel = Schema.getGlobalDescribe().get(SelectObj).getDescribe().getLabel();
        // SelectFld = ApexPages.currentPage().getParameters().get('SelectFld');
        setVal =  ApexPages.currentPage().getParameters().get('setVal');
        FilterSql =  ApexPages.currentPage().getParameters().get('FilterSql');
        // if(String.isBlank(SelectFld)){
            SelectFld='Name';
        // }

        Object_Search_Layout_Setting__c LayoutMap=Object_Search_Layout_Setting__c.getValues(SelectObj);
        if(LayoutMap==null){
            FieldApiNameList='Name,Id';
            FieldNameList='名称,Id';
        }else{
            FieldApiNameList=LayoutMap.Columns_Displayed__c;
            // FieldWhereSQL = LayoutMap.Where_SQL__c;
            FieldNameList='';
            String[] fl=FieldApiNameList.split(',');

            Map<String,Schema.SObjectField> fieldMap=Schema.getGlobalDescribe().get(SelectObj).getDescribe().fields.getMap();

            for(String fieldName:fl){
                // fieldName=fieldName.toLowerCase();
                if(fieldName=='RoleName_wave__c'){
                    FieldNameList+='角色';
                    continue;
                }
                if(fieldMap.get(fieldName)!=null){
                    FieldNameList+=fieldMap.get(fieldName).getDescribe().getLabel() + ',';
                }else{
                    FieldNameList+=fieldName+',';
                }
            }
            FieldNameList=FieldNameList.removeEnd(',');
        }
        
        //2023 08 30 张赫阳 PIPL页面改造 end
        aId = accountId;
        PIPL_Search_Contact_Label = Label.PIPL_Search_Contact_Label;
        //1. Query Contact by accountId
        List<Contact> conList = new List<Contact>();
        system.debug('Account Id from Front-end:'+accountId);
        if(checkNullString(accountId)&&checkNullString(searchKeyWord)){
            conList = new List<Contact>();
        }else{
            if(checkNullString(accountId)){
                conList = new List<Contact>();
            }else {
                //2022-5-12 yjk 将科室匹配改为医院匹配查询联系人 statt
                Account act = [select id,Hospital__c from Account where id = :accountId];
                conList = new List<Contact>([select Id,AWS_Data_Id__c,Account.Name from Contact  where 	Account.Hospital__c=:act.Hospital__c and AWS_Data_Id__c!='']); 
                //2022-5-12 yjk 将科室匹配改为医院匹配查询联系人 end
            }
            
        }    
        //2. Prepare the Contact Info
        Map<String,Contact> awsIdToContactMap = new Map<String,Contact>();
        List<String> conAWSIds = new List<String>();
        for(Contact con:conList){
            conAWSIds.add(con.AWS_Data_Id__c);
            awsIdToContactMap.put(con.AWS_Data_Id__c,con);
        }
        contactsInfo = JSON.serialize(awsIdToContactMap);
        contactAWSIds = JSON.serialize(conAWSIds);
        // staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));   
        staticResource = 'notUse';

        //deloitte-hzj 20231210 
        System.debug('FieldNameList = ' + FieldNameList);
        FieldNameList = FieldNameList.replace('Account.Name', '客户名称');
    }

    // @RemoteAction
    // public static Response searchContacts(String accountId,String FieldApiNameList,String ObjectType,String QueryFieldApiName,String QuertLimit) {
    //     Response resp = new Response();
    //     resp.status = 'fail';
    //     Map<String,Sobject> awsIdToContactMapTemp = new Map<String,Sobject>();
    //     List<Sobject> conListTemp = new List<Sobject>();
    //     // if(!checkNullString(accountId)){
    //     //     //2022-5-12 yjk 将科室匹配改为医院匹配查询联系人 statt
    //     //     Account act = [select id,Hospital__c from Account where id = :accountId];
    //     //     conListTemp = new List<Contact>([select Id,AWS_Data_Id__c,Account.Name from Contact where Account.Hospital__c=:act.Hospital__c and AWS_Data_Id__c in:awsDataIds]);
    //     //     //2022-5-12 yjk 将科室匹配改为医院匹配查询联系人 end
    //     // }else {
    //     //     conListTemp = new List<Contact>([select Id,AWS_Data_Id__c,Account.Name from Contact where AWS_Data_Id__c in:awsDataIds]);
    //     // }
    //     String sql='SELECT '+ FieldApiNameList + ' FROM ' + ObjectType + ' WHERE ' + QueryFieldApiName + ' like \'%' + accountId + '%\' AND ' + QuertLimit;
    //     conListTemp = Database.query(sql);
    //     System.debug('sql='+sql);
    //     for(Sobject con:conListTemp){
    //         awsIdToContactMapTemp.put(con.Id,con);
    //     }
    //     System.debug('awsIdToContactMapTemp = ' + awsIdToContactMapTemp);
    //     if(awsIdToContactMapTemp.keySet().size()>0 ){
    //         resp.status = 'success';
    //         resp.message = JSON.serialize(awsIdToContactMapTemp);// PI contact info
    //     }
    //     return resp;
    // }



    @RemoteAction
    public static Response searchContacts(String awsContactIds,String accountId,String FieldApiNameList,String ObjectType,String QueryFieldApiName,String SelectObj,String SelectFld,String setVal,String staticFilterSql) {
        System.debug('awsContactIds = ' + awsContactIds);
        Object_Search_Layout_Setting__c LayoutMaptemp=Object_Search_Layout_Setting__c.getValues(SelectObj);
        Response resp = new Response();
        resp.status = 'fail';
        Map<String,Sobject> awsIdToContactMapTemp = new Map<String,Sobject>();
        List<Sobject> conListTemp = new List<Sobject>();
        Object_Filter_Setting__c FilterMap=null;
        resp.i1='null';
        try{
            String Lname=QueryFieldApiName;
            // Lname=Lname.replace('_', '');
            FilterMap=Object_Filter_Setting__c.getValues(QueryFieldApiName);
            resp.i1=Lname;
        }catch(Exception e){
            System.debug('e');
        }
        String sql = 'SELECT '+ FieldApiNameList + ' FROM ' + SelectObj + ' WHERE Name != null ';
        try{

            Boolean setValFlag=true;
            if(FilterMap!=null&&FilterMap.Filter_Sql__c!=null&&FilterMap.Filter_Sql__c.contains(':setVal')&&(String.isBlank(setVal)||setVal==System.label.Agency_ID_c)){
                // setValFlag=false;
                setVal=System.label.Agency_ID_c;
            }
            if( String.isNotBlank(accountId)){

                sql += ' AND (' + SelectFld + ' like \'%' + accountId + '%\' ';
                if (String.isNotBlank(LayoutMaptemp.Where_SQL__c)) {
                    String[] WhereSQLList=LayoutMaptemp.Where_SQL__c.split(',');
                    System.debug('WhereSQLList='+WhereSQLList.size());
                    System.debug('WhereSQLList===== '+WhereSQLList);
                    // sql += ' AND (';
                    for (String WhereSQL : WhereSQLList) {
                        sql += ' OR ' + WhereSQL + ' like \'%' + accountId + '%\'';
                    }
                    // for (String WhereSQL : WhereSQLList) {
                    //     sql += WhereSQL + ' like \'%' + accountId + '%\'';
                    // }
                    // sql += ') ';
                    // sql += ' AND (' + LayoutMaptemp.Where_SQL__c + ') ';
                }
                sql += ') ';
            //有检索条件，没有筛选条件
            }
            if(FilterMap!=null && FilterMap.Filter_Type__c && FilterMap.Active__c && setValFlag){
                sql +=' AND (' + FilterMap.Filter_Sql__c + ') ';
            }
            if(String.isNotBlank(staticFilterSql)&&staticFilterSql!='undefined'){
                sql += ' AND ('+ staticFilterSql +')';
            }
            //有检索条件和筛选条件
            // if( String.isNotBlank(SelectFld)  && FilterMap!=null && FilterMap.Filter_Type__c && FilterMap.Active__c && setValFlag){
            //     sql +=  ' WHERE ' + SelectFld + ' like \'%' + accountId + '%\' AND (' + FilterMap.Filter_Sql__c + ') ';
            // //有检索条件，没有筛选条件
            // }else if( String.isNotBlank(SelectFld)  && (FilterMap==null||!FilterMap.Filter_Type__c||!FilterMap.Active__c ) ){
            //     sql +=  ' WHERE ' + SelectFld + ' like \'%' + accountId + '%\'';
            // }
            // if (String.isNotBlank(LayoutMaptemp.Where_SQL__c)) {
            //     String[] WhereSQLList=LayoutMaptemp.Where_SQL__c.split(',');
            //     System.debug('WhereSQLList='+WhereSQLList.size());
            //     System.debug('WhereSQLList===== '+WhereSQLList);
            //     sql += ' AND (';
            //     for (Integer i = 0; i < WhereSQLList.size(); i++) {
            //         if (i==0) {
            //             sql += WhereSQLList[i] + ' like \'%' + accountId + '%\'';
            //         }else {
            //             sql += ' OR ' + WhereSQLList[i] + ' like \'%' + accountId + '%\'';
            //         }
            //     }
            //     // for (String WhereSQL : WhereSQLList) {
            //     //     sql += WhereSQL + ' like \'%' + accountId + '%\'';
            //     // }
            //     // sql += ') ';
            //     // sql += ' AND (' + LayoutMaptemp.Where_SQL__c + ') ';
            // }
            sql +=' limit 50 ';
            // Schema.DescribeFieldResult fieldResult = QuoteIrai__c.Agency1_entrust__c.getDescribe();
            // Schema.FilteredLookupInfo filterInfo = fieldResult.getFilteredLookupInfo();
            // System.debug(filterInfo.getControllingFields());
            // System.debug(fieldResult);
            System.debug('sql='+sql);
            resp.i1=staticFilterSql;
            resp.i2=sql;
            conListTemp = Database.query(sql);
            for(Sobject con:conListTemp){
                awsIdToContactMapTemp.put(con.Id,con);
            }
            System.debug('awsIdToContactMapTemp = ' + awsIdToContactMapTemp);
            if(awsIdToContactMapTemp.keySet().size()>0 ){
                resp.status = 'success';
                resp.message = JSON.serialize(awsIdToContactMapTemp);// PI contact info
            }
            return resp;
        }catch(Exception e){
            resp.status='fail';
            resp.message=e.getMessage();
            return resp;
        }

    }

    @RemoteAction
    public static Response searchContactsNoPI(String contactName) {
        Response resp = new Response();
        resp.status = 'fail';
        List<Account> conListTemp = new List<Account>([select Id,Name from Account where Name like :contactName]);
        if(conListTemp.size() > 0){
            resp.status = 'success';
            resp.message = JSON.serialize(conListTemp);

        }
        return resp;
    }

    public class Response{
        public String message{set;get;}
        public String status{set;get;}
        public String noPIContactList{set;get;}
        public Object i1{get;set;}
        public Object i2{get;set;}
    }

}