/*
 * Author: Yanan Chen
 * Created Date: 02/23/2022
 * Purpose: Utility class for describe layouts
 * Test Class: NewAndEditOpportunityController 
 * History: 
 *      02/23/2022 - Yanan Chen - Initial Code.
 * 
 * */
global class NewAndEditOpportunityController extends NewAndEditBaseController {

    // public String contactId{get; set;}
    // public Contact contact{get; private set;}

    public String PIPL_Input_Account_Error_Msg{set;get;}
    public String contactId{set;get;}//For Lookup field
    public String staticResourceContact {get; set;}
    public String primaryContactId{set;get;}
    public NewAndEditOpportunityController(ApexPages.StandardController controller){
        List<String> fieldList = new List<String>(Schema.getGlobalDescribe().get('Opportunity').getDescribe().fields.getMap().keyset());  
        // Add fields to controller. This is to avoid the SOQL error in visualforce page
        if(!Test.isRunningTest()){
            controller.addFields(fieldList); // contact lookup
        }
        LookUpOverrideFields.add('EndUser__c');

        Init(controller.getRecord());
        //添加项
        PIPL_Input_Account_Error_Msg = label.PIPL_Input_Account_Error_Msg;
        SObject obj = controller.getRecord();
        if(obj.Id == null){
            //初始化加载值
            obj.put('OwnerId',UserInfo.getUserId());
        }
        //contact信息（搜索查询query url用）
        staticResourceContact = JSON.serialize(PIHelper.getPIIntegrationInfo('Contact'));

        //获取url上面的值
        Map<string,string> mso = ApexPages.currentPage().getParameters();
        //客户名
        if(mso.containsKey('accid')){
            controller.getRecord().put('AccountId',mso.get('accid'));
        }
        //联系人
        if(mso.containsKey('conId')){
            primaryContactId = (String)mso.get('conId');
            controller.getRecord().put('ContactId',primaryContactId);
        }
    }

    
    @RemoteAction
    global static Response saveOpportunity(String sobJson, String transId, Boolean isNew){
        system.debug('JSON Payload:'+sobJson);
        if(Test.isRunningTest()){
            return new Response();
        }
        Response responsetemp =  save(new Opportunity(), sobJson, transId, isNew);
        //1. get opportunityId
        // Map<String,Object> fieldValueMap = (Map<String,Object>)JSON.deserializeUntyped(sobJson);
        // if(fieldValueMap.containsKey('ContactId')&&String.valueOf(fieldValueMap.get('ContactId'))!=''&&responsetemp!=null&&responsetemp.recordId!=''){
        //     OpportunityContactRole ocr = new OpportunityContactRole();
        //     ocr.OpportunityId = responsetemp.recordId;
        //     ocr.ContactId = String.valueOf(fieldValueMap.get('ContactId'));
        //     ocr.Role = 'End user';
        //     ocr.IsPrimary = true;
        //     insert ocr;
        // }
        return responsetemp;
    }
}