public with sharing class NewLoanerUserController {
	//基础url
	public String baseUrl { get; private set; }

	public List<loaner_user__c> luList{get; private set; }
	//数据List
	public List<loaner_user__c> dataLines {get; private set;}
	//订单Id
	public String laId {get; private set;}
    // Update 20220317 By Yang Kaiyu Start
    public String staticResource {get; set;}
    public String staticResourceContact {get; set;}
	//PI contact
    public List<ContactClass> conList {get;set;}

    public String contactId {get;set;}
    public string conListJson {get{
        if(conList==null)return null;
        return JSON.serialize(conList);
    }}
    public String dataLinesJson{get{
        if(dataLines==null)return null;
        return JSON.serialize(dataLines);
    }}
    class ContactClass{
        public String contactIdValue{set;get;}
        public String contactNameValue{set;get;}
        public String contactPhoneValue{set;get;}
    }    
    // Update 20220317 By Yang Kaiyu End
	/*public NewLoanerUserController() {
		 laId = System.currentPageReference().getParameters().get('headId');
         //ApexPages.currentPage().getParameters().get('headId');

    }*/

    public NewLoanerUserController(ApexPages.StandardController stdController) {
        String luId = stdController.getId();
        if(luId == null || luId == ''){
             laId = System.currentPageReference().getParameters().get('headId');
        }else{
            loaner_user__c lu = [select id,loaner_application__c from loaner_user__c where id = :luId];
            laId = lu.loaner_application__c; 
        }  
        // Update 20220317 By Yang Kaiyu Start  
        staticResource = JSON.serialize(PIHelper.getPIIntegrationInfo('loaner_user__c')); 
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('contact')); 
        conList = new List<ContactClass>();
        // Update 20220317 By Yang Kaiyu End
    }
    


	//初始化方法
	public PageReference init() {
 		// 基础Url
        baseUrl = URL.getSalesforceBaseUrl().toExternalForm();
        String path = URL.getCurrentRequestUrl().getPath();
        if (path.indexOf('/apex') > 0) {
            baseUrl += path.substring(0,path.indexOf('/apex'));
        } else if (path.indexOf('production/') > 0) {
            baseUrl += '/production';
        }
        dataLines = new List<loaner_user__c>();
        // Update 20220317 By Yang Kaiyu Start
        luList = [select id,Contact__r.AWS_Data_Id__c,Contact__c,Contact__r.LastName,Contact__r.Phone,Contact__r.LastName_Encrypted__c,Contact__r.Phone_Encrypted__c,ContactNumber__c,
                        FromThePeriod__c,EndThePeriod__c,Remarks__c,Customer__c,Follow_UP_Opp__c 
                    from loaner_user__c 
                    where  loaner_application__c =:laId];
        // Update 20220317 By Yang Kaiyu End
        if(luList.size() >0){
        	for(loaner_user__c lu : luList){
                // Update 20220317 By Yang Kaiyu Start
                ContactClass con = new ContactClass();
                con.contactIdValue   = lu.Contact__r.AWS_Data_Id__c;
                con.contactNameValue = lu.Contact__r.LastName_Encrypted__c;
                con.contactPhoneValue= lu.Contact__r.Phone_Encrypted__c;
                conList.add(con);
                // Update 20220317 By Yang Kaiyu End
        		dataLines.add(lu);
        	}
        }
        if(dataLines.size()<50){
        	integer num = dataLines.size();
        	for(integer i = 0 ;i<50-num;i++){
        		loaner_user__c luc = new loaner_user__c();
        		dataLines.add(luc);
        	}
        }
		return null;
	}

	public PageReference updateUser() {

        System.debug('进入updateUser');

		List<loaner_user__c> updateList = new List<loaner_user__c>();
		loaner_application__c la =[select id,RecordType.DeveloperName from loaner_application__c where id=:laId];
        List<String> contactIdList = new List<String>();

        String firstLuId = '';
        String accountName = '';
        List<String> idList = new List<String>();
        System.debug('dataLines = ' + dataLines);
		for(loaner_user__c luc : dataLines){
			if(!(String.isBlank(luc.Contact__c) || luc.Customer__c == null)){
				loaner_user__c lu = new loaner_user__c();
				lu.Contact__c = luc.Contact__c;
                contactIdList.add(luc.Contact__c);
                
                if(firstLuId == '') firstLuId = luc.Contact__c;
				
                lu.FromThePeriod__c = luc.FromThePeriod__c;
				lu.EndThePeriod__c = luc.EndThePeriod__c;
				lu.Remarks__c = luc.Remarks__c;
				lu.Customer__c = luc.Customer__c;
                lu.Follow_UP_Opp__c = luc.Follow_UP_Opp__c;
				lu.loaner_application__c = laId;
				updateList.add(lu);
                //
                idList.add(luc.Customer__c);
			}
		}

        List<Contact> contactList = [select id,Phone from Contact where id = :contactIdList];
        for(Contact con : contactList){
            for(loaner_user__c lu1 : updateList){
                if(lu1.Contact__c == con.id){
                    lu1.ContactNumber__c = con.Phone;
                }
            }
        }
        if(firstLuId == '' || firstLuId == null){
            delete luList;
            String url = baseUrl;
            url += '\\' + laId;
            return new Pagereference(url);
        }
        if(la.RecordType.DeveloperName == 'BS'){
            Contact contact = [select id,Name,Phone,Address1__c,Postcode__c from Contact where id = : firstLuId]; 
            la.id = laId;
            la.Loaner_receive_staff__c = contact.Name;
            la.Loaner_receive_staff_phone__c = contact.Phone;
            la.direct_shippment_address__c = contact.Address1__c;
            la.Post_Code__c = contact.Postcode__c;
        }

		Savepoint sp = Database.setSavepoint();
       
        try {
            
            if (updateList.size() > 0) {
                delete luList;
                insert updateList;
            }
            System.debug(accountName);
            if(accountName == ''){
                System.debug('1111');
                List<Account> luList = new List<Account>();
                luList = [select id,Name from Account where id in :idList];
                System.debug('luList'+ luList);
                for(Account lu : luList){
                    if(accountName == ''){
                        accountName = lu.Name;
                    }else{
                        accountName += (',' + lu.Name);
                    }
                }
            }
            System.debug(accountName);
            la.Loaner_Account__c = accountName;
            update la;
        }catch (Exception ex) {
                Database.rollback(sp);
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, ex.getMessage() + ' | Line:' + ex.getLineNumber()));
                return null;
        }
        // 返回样机借出申请画面
        String url = baseUrl;
        url += '\\' + laId;
        return new Pagereference(url);
	}


	public PageReference cancelBtn() {
        // 返回样机借出申请画面
        String url = baseUrl;
        url += '\\' + laId;
        return new Pagereference(url);
    }

}