public class SearchVisitorController {
    public Contact rc {get;set;}
    public Contact sc {get;set;}
    public List<SltContactWrapper> scwl {get;set;}
    public List<Contact> cl {get;set;}
    public List<AddContactWrapper> acwl {get;set;}
    public String index {get; set;}
    public String awsContactIds{set;get;}//Add By Li Jun 20220214 for PIPL
    public String id1 {get;set;}
    public String hId1 {get;set;}
    public String idVa1 {get;set;}
    public String id2 {get;set;}
    public String hId2 {get;set;}
    public String idVa2 {get;set;}
    public String id3 {get;set;}
    public String hId3 {get;set;}
    public String idVa3 {get;set;}
    public String id4 {get;set;}
    public String hId4 {get;set;}
    public String idVa4 {get;set;}
    public String id5 {get;set;}
    public String hId5 {get;set;}
    public String idVa5 {get;set;}
    public String vp {get;set;}
    
    public User u {get;set;}
    public Account a {get;set;}


    //Add By Li Jun 20220217 Start
    public String staticResource {get; set;}
    public String contactAWSIds {set;get;}
    public String contactsInfo {set;get;}
    public String awsDataIdArray {set;get;}
    //Add By Li Jun 20220217 End
    
    public SearchVisitorController(){
        this.id1 = Apexpages.currentPage().getParameters().get('id1');
        this.hId1 = Apexpages.currentPage().getParameters().get('hId1');
        this.idVa1 = Apexpages.currentPage().getParameters().get('idVa1');
        this.id2 = Apexpages.currentPage().getParameters().get('id2');
        this.hId2 = Apexpages.currentPage().getParameters().get('hId2');
        this.idVa2 = Apexpages.currentPage().getParameters().get('idVa2');
        this.id3 = Apexpages.currentPage().getParameters().get('id3');
        this.hId3 = Apexpages.currentPage().getParameters().get('hId3');
        this.idVa3 = Apexpages.currentPage().getParameters().get('idVa3');
        this.id4 = Apexpages.currentPage().getParameters().get('id4');
        this.hId4 = Apexpages.currentPage().getParameters().get('hId4');
        this.idVa4 = Apexpages.currentPage().getParameters().get('idVa4');
        this.id5 = Apexpages.currentPage().getParameters().get('id5');
        this.hId5 = Apexpages.currentPage().getParameters().get('hId5');
        this.idVa5 = Apexpages.currentPage().getParameters().get('idVa5');
        this.vp = Apexpages.currentPage().getParameters().get('vp');
        
        u = [select id, Employee_No__c, Province__c from User where id =:UserInfo.getUserId()];
        a = [select id from Account where Id =:vp];

        clearRC();
        sc = new Contact();
        scwl = new List<SltContactWrapper>();
        
        /*Set<ID> idList = new Set<ID>();
        if(idVa1 != ''){
            idList.add(idVa1);
        }
        if(idVa2 != ''){
            idList.add(idVa2);
        }
        if(idVa3 != ''){
            idList.add(idVa3);
        }
        if(idVa4 != ''){
            idList.add(idVa4);
        }
        if(idVa5 != ''){
            idList.add(idVa5);
        }
        
        AddContactWrapper acw = new AddContactWrapper();
        acwl = new List<AddContactWrapper>();
        Integer i = 0;
        if(idList.size() == 0){
            acw.con = new Contact();
            acw.index = String.valueOf(i);
            acwl.add(acw);
            acwl.add(acw);
            acwl.add(acw);
            acwl.add(acw);
            acwl.add(acw);
            i++;
        }
        else{
            List<Contact> cl = [select id, name, Account.Name, Type__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, phone, Supplement__c, Select_Flg__c From Contact Where id IN :idList];
            
            for(Contact c : cl){
                acw = new AddContactWrapper();
                acw.con = c;
                acw.index = String.valueOf(i);
                acwl.add(acw);
                i++;
            }
            
            for(Integer j=i; j<5; j++){
                acw = new AddContactWrapper();
                acw.con = new Contact();
                acw.index = String.valueOf(j);
                acwl.add(acw);
            }
        }*/
        
        acwl = new List<AddContactWrapper>();
        list<String> idList = new list<String>();
        system.debug('===========================idList.size():'+idList.size());
        idList.add(idVa1);
        idList.add(idVa2);
        idList.add(idVa3);
        idList.add(idVa4);
        idList.add(idVa5);
        acwlRefresh(idList);

        /*
        List<Contact> cList1 = [select id, name, Account.Name, FirstName, Search_LastName__c, LastName, Type__c, phone, Supplement__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, Select_Flg__c, Please_Delete__c, Please_Delete_applier__c  From Contact Where id =:idVa1];
        if(idVa1 != '' && cList1.size() > 0){
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(0), cList1.get(0));
            acwl.add(acw);
        }
        else{
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(0), new Contact());
            acwl.add(acw);
        }
        
        List<Contact> cList2 = [select id, name, Account.Name, FirstName, Search_LastName__c, LastName, Type__c, phone, Supplement__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, Select_Flg__c, Please_Delete__c, Please_Delete_applier__c  From Contact Where id =:idVa2];
        if(idVa2 != '' && cList2.size() > 0){
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(1), cList2.get(0));
            acwl.add(acw);
        }
        else{
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(1), new Contact());
            acwl.add(acw);
        }
        
        List<Contact> cList3 = [select id, name, Account.Name, FirstName, Search_LastName__c, LastName, Type__c, phone, Supplement__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, Select_Flg__c, Please_Delete__c, Please_Delete_applier__c  From Contact Where id =:idVa3];
        if(idVa3 != '' && cList3.size() > 0){
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(2), cList3.get(0));
            acwl.add(acw);
        }
        else{
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(2), new Contact());
            acwl.add(acw);
        }
        
        List<Contact> cList4 = [select id, name, Account.Name, FirstName, Search_LastName__c, LastName, Type__c, phone, Supplement__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, Select_Flg__c, Please_Delete__c, Please_Delete_applier__c  From Contact Where id =:idVa4];
        if(idVa4 != '' && cList4.size() > 0){
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(3), cList4.get(0));
            acwl.add(acw);
        }
        else{
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(3), new Contact());
            acwl.add(acw);
        }
        
        List<Contact> cList5 = [select id, name, Account.Name, FirstName, Search_LastName__c, LastName, Type__c, phone, Supplement__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, Select_Flg__c, Please_Delete__c, Please_Delete_applier__c  From Contact Where id =:idVa5];
        if(idVa5 != '' && cList5.size() > 0){
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(4), cList5.get(0));
            acwl.add(acw);
        }
        else{
            AddContactWrapper acw = new AddContactWrapper(String.valueOf(4), new Contact());
            acwl.add(acw);
        }*/
        
        serContact();

        //Add By Li Jun for PIPL 20220217 Start
        //1. Query Contact by accountId
        List<Contact> conList = new List<Contact>();
        system.debug('Account Id from Front-end:'+a.Id);
        String accountId = a.Id;
        PIHelper.PIIntegration contactPIIntegration = PIHelper.getPIIntegrationInfo('Contact');
        if(String.isNotBlank(accountId) && String.isNotEmpty(accountId)){
            conList = new List<Contact>([select Id,AWS_Data_Id__c from Contact where AccountId=:accountId and AWS_Data_Id__c!='' limit :contactPIIntegration.maxQueryNumber]);
        }        
        //2. Prepare the Contact Info
        List<String> conAWSIds = new List<String>();
        system.debug('Contact Size:'+conList.size());
        for(Contact con:conList){
            conAWSIds.add(con.AWS_Data_Id__c);
        }
        contactAWSIds = JSON.serialize(conAWSIds);
        staticResource = JSON.serialize(contactPIIntegration); 
        //Add By Li Jun for PIPL 20220217 End 
     }
    //Add by Li Jun for PIPL 202202117 Start
    public PageReference clearLineInfoList()  {
        scwl = new List<SltContactWrapper>();
        return null;
    }
    //Add by Li Jun for PIPL 202202117 End
    public PageReference serContact(){
        System.debug('===== serContact start ====='+awsContactIds);
        //Add By Li Jun for PIPL 20220218 Start
        Set<String> awsContactSet = new Set<String>();
        if(String.isNotBlank(awsContactIds)&&String.isNotEmpty(awsContactIds)){
            List<String> awsDataIds = (List<String>) JSON.deserialize(awsContactIds, List<String>.class);
            awsContactSet = new Set<String>(awsDataIds);
        }        
        System.debug('===== serContact start ====='+awsContactSet);
         //Add By Li Jun for PIPL 20220218 End
        String searchHospital = 'Select Hospital__c, Department_Class__c,Is_Active__c From Account Where Id = \'' + vp + '\' ';
        Account a = Database.query(searchHospital);
        if(a.Is_Active__c == '無効'){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'summary - This hospital is inactive.', 'detail - error'));
            return null;
        }
        
        String searchSql = 'Select id, name,Ignore_Same_Name__c,AWS_Data_Id__c, Account.Name, Type__c, Doctor_Division1__c, MyDr_Flg__c, phone, Supplement__c, MyDr__c, Select_Flg__c,Delete_Reason__c, Please_Delete__c, Please_Delete_applier__c, FirstName, LastName, Search_LastName__c, Account_Visitor_Search__c  From Contact ';
        String whereStr = 'Where Account.ParentId =\'' + a.Department_Class__c + '\' and Account.Is_Active__c != \'無効\' ' + ' and Isactive__c != \'无效(退休)\' and Isactive__c != \'无效(重复)\'';
        String whereSql = '';
        //Commented by Li Jun 20220214 for PIPL
        if(awsContactSet.size()>0){
            whereSql += 'and AWS_Data_Id__c in: awsContactSet ';
        }
        // if(sc.Search_LastName__c != null && sc.Search_LastName__c != ''){
        //     whereSql += 'and LastName like ' + '\'%' + sc.Search_LastName__c + '%\' ';
        // }
        
        // if(sc.Search_FirstName__c != null && sc.Search_FirstName__c != ''){
        //     whereSql += 'and FirstName like ' + '\'%' + sc.Search_FirstName__c + '%\' ';
        // }
        
        if(sc.Type__c != null && sc.Type__c != ''){
            whereSql += 'and Type__c = \'' + sc.Type__c + '\' ';
        }
        
        if(sc.Doctor_Division1__c != null && sc.Doctor_Division1__c != ''){
            whereSql += 'and Doctor_Division1__c = \'' + sc.Doctor_Division1__c + '\' ';
        }
        
        if(sc.MyDr_Flg__c){
            whereSql += 'and MyDr__c like \'%' + u.Employee_No__c + '%\' ';
        }
        
        
        searchSql = searchSql + whereStr + whereSql;
        
        searchSql += ' order by Account.Name asc, LastName, FirstName ';
        
        System.debug('searchSql:'+searchSql);
        cl = Database.query(searchSql);
        System.debug('Query Result from SF:'+JSON.serialize(cl));
        Integer i = 0;
        
        scwl = new List<SltContactWrapper>();
        for(Contact c : cl){
            if(c.MyDr__c != null && (',' + c.MyDr__c).contains(',' + u.Employee_No__c)){
                c.MyDr_Flg__c = true;
            }
            else{
                c.MyDr_Flg__c = false;
            }
            SltContactWrapper cw = new SltContactWrapper(String.valueOf(i), c);
            scwl.add(cw);
            i++;
        }
        
        for ( i = 0; i < acwl.size(); i++) {
            AddContactWrapper acw = acwl.get(i);
            if (acw.con != null && acw.con.MyDr__c != null  && (',' + acw.con.MyDr__c).contains(',' + u.Employee_No__c) ) {
                acw.con.MyDr_Flg__c = true;
            }else{
                acw.con.MyDr_Flg__c = false;
            }
        }
        
        return null;
    }
    
    public PageReference updContactP(){
        system.debug('========upd please delete start**============='+index);
        Contact conTemp = scwl.get(Integer.valueof(index)).con;
        Contact conTemp2 = [select Please_Delete__c, Please_Delete_applier__c  From Contact where Id = :conTemp.Id];
        if(conTemp.Please_Delete__c == true && conTemp.Delete_Reason__c==null){
            conTemp.Delete_Reason__c.addError('请输入删除理由');
            return null;
        }else if(conTemp2.Please_Delete_applier__c != null && conTemp2.Please_Delete_applier__c != UserInfo.getUserId()){
            return null;
        }else if(conTemp.Please_Delete__c == true && conTemp2.Please_Delete_applier__c == null){
            conTemp.Please_Delete_applier__c = UserInfo.getUserId();
        }else if(conTemp.Please_Delete__c == false && conTemp2.Please_Delete_applier__c == UserInfo.getUserId()){
            conTemp.Please_Delete_applier__c = null;
        }else{

        } 
        Savepoint sp = Database.setSavepoint();
        try{
            update conTemp;
            }catch(Exception io){
                Database.rollback(sp);
            }
        return null;
    }
    
    public PageReference MyDrChange(Contact c){
        list<Contact> conList = [select MyDr__c, MyDr_Flg__c  From Contact where Id = :c.Id];
        Contact conTemp = new Contact();
        if(conList.size()<1){
            conTemp = c;
        }else{
            conTemp = conList[0];
        }
        list<String> mdList = new list<String>();
        if(!string.isBlank(conTemp.MyDr__c)){
            mdList = conTemp.MyDr__c.split(',',0);
        }
        
        //u = [select id, Employee_No__c from User where id =:UserInfo.getUserId()];
        integer index = -1;
        for(integer i=0;i < mdList.size();i++){
            if(mdList[i].equals(u.Employee_No__c)){
                //if the myDr is included, save the sequence number
                index = i;
                break;
            } else{
                //do nothing
            }
        }
        //if mydr is true, the Employee_No__c should be in the mdList
        if(c.MyDr_Flg__c==true){
            if(index == -1) mdList.add(u.Employee_No__c);
        // in the contrast , the Employee_No__c should not be in the mdList 
        } else{
            if(index != -1) mdList.remove(index);
        }
        String s;
        if(mdList.size()<1){
            s='';
        }else{
            s = mdList[0];
            if(mdList.size()>1){
                for(integer i=1;i<mdList.size();i++){
                    s = s +',' + mdList[i];
                }
            }
        }
        c.MyDr__c = s;
        return null;
    }
    public PageReference updContactM(){
        MyDrChange(scwl.get(Integer.valueof(index)).con);
        update scwl.get(Integer.valueof(index)).con;
        return null;
    }
    
    public PageReference clearRC(){
        rc = new Contact();    
        rc.Account_Visitor_Search__c = a.id;
        return null;
    }
    
    public PageReference editVistor(){
        if(acwl.get(Integer.valueof(index)).conId!=''){
            Id rcID = acwl.get(Integer.valueof(index)).conId;
            for(integer i =0; i<scwl.size();i++){
                if(scwl.get(i).conId==rcID){
                    rc=scwl.get(i).con;
                    system.debug('--------------rc.Search_LastName__c ='+rc.Search_LastName__c);
                    system.debug('--------------rc.Search_FirstName__c ='+rc.Search_FirstName__c);
                    system.debug('--------------rc.Account_Visitor_Search__c'+rc.Account_Visitor_Search__c);
                    rc.Search_LastName__c = rc.LastName;
                    rc.Search_FirstName__c = rc.FirstName;
                    rc.Account_Visitor_Search__c = rc.AccountId;
                    break;
                }
            }
            system.debug('this.rc='+this.rc);
            system.debug('this.rc.LastName'+this.rc.LastName);
            system.debug('rc='+rc);
        }else{
            clearRC();
        }
        return null;
    }
    
    public PageReference regContact(){
        Account a = [Select Hospital__c, Is_Active__c  From Account Where Id = :vp];
        if(a.Is_Active__c == '無効'){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'summary - This hospital is inactive.', 'detail - error'));
            return null;
        }
        if(rc.Search_LastName__c == null || rc.Search_LastName__c == ''){
            rc.Search_LastName__c.addError(System.Label.Error_Message3);
            return null;
        }
        
        MyDrChange(rc);
        
        rc.LastName = rc.Search_LastName__c;
        rc.AccountId = rc.Account_Visitor_Search__c;
        rc.Isactive__c = '有效';
        system.debug('--------------rc.LastName ='+rc.LastName);
        
        Savepoint sp = Database.setSavepoint();
        try{
            upsert rc;
            }catch(Exception io){
                Database.rollback(sp);
                return null;
            }
        
        /*
        rc=[Select id, name, Account.Name, Type__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, phone, Supplement__c, Select_Flg__c, Please_Delete__c, Please_Delete_applier__c, FirstName, LastName, Search_LastName__c, Account_Visitor_Search__c  From Contact where ID = :rc.Id];
        for (Integer i = 0; i < acwl.size(); i++) {
            AddContactWrapper acw = acwl.get(i);
            system.debug('==============acwl['+i+'].conId =='+acw.conId);
            if (acw.con != null && acw.conId == string.valueOf(rc.id) ) {
                AddContactWrapper acwNew = new AddContactWrapper('' + i, rc);
                acwl.set(i, acwNew);
            }
            system.debug('--------------acw.con.Search_LastName__c ='+acw.con.Search_LastName__c);
            system.debug('--------------acw.con.LastName ='+acw.con.LastName);
            system.debug('acwl('+i+').id= [' + acw.conId +']');
            system.debug('rc.id= [' + rc.Id +']');
        }
        system.debug('acwl.size()= [' + acwl.size()+']');
        */
        List<String> idList = new List<String>();
        for(Integer i = 0; i < acwl.size(); i++){
            AddContactWrapper acw = acwl.get(i);
            idList.add(acw.conId);
        }
        acwlRefresh(idList);
        clearRC();
        serContact();
        
        return null;
    }
    
    public PageReference acwlRefresh(List<String> idList){
        List<Contact> cList = [Select id, name, Account.Name, Type__c, Doctor_Division1__c, MyDr_Flg__c, MyDr__c, phone, Supplement__c, Select_Flg__c, Please_Delete__c, Please_Delete_applier__c, FirstName, LastName, Search_LastName__c, Account_Visitor_Search__c  From Contact where id in :idList];
        system.debug('===========================cList.size():'+cList.size());
        map<String, Contact> idConMap = new map<String, Contact>();
        integer i = 0;
        List<AddContactWrapper> acwlTemp = new List<AddContactWrapper>();
        for(String d : idList){
            system.debug('===========================idList:'+i+'='+d);
            i++;
            for(Contact c : cList){
                system.debug('===========================c.Id:'+i+'='+c.Id);
                if(d.equals(c.Id)){
                    idConMap.put(d,c);
                    break;
                }
            }
        }
        system.debug('===========================idConMap:'+idConMap.get(''));
        for (i = 0; i < 5; i++) {
            AddContactWrapper acwNew;
            if(idList[i] == ''||idList[i] == null ){
                acwNew = new AddContactWrapper('' + i, new Contact());
            }else{
                acwNew = new AddContactWrapper('' + i, idConMap.get(idList[i]));
            }
            
            system.debug('===========================acwNew:'+acwNew.index);
            acwlTemp.add(acwNew);
        }
        acwl = acwlTemp.clone();
        return null;
    }
    
    class SltContactWrapper{
        public String index {get;set;}
        public Contact con {get;set;}
        public String conId {get;set;}
        
        public SltContactWrapper(String index, Contact con) {
            this.con = con;
            this.conId = con.Id;
            this.index = index;
        }
    }
    
    class AddContactWrapper{
        public String index {get;set;}
        public Contact con {get;set;}
        public String conId {get;set;}
        
        public AddContactWrapper(String index, Contact con) {
            this.con = con;
            this.conId = con.Id;
            this.index = index;
        }
    }
}