@isTest
public with sharing class NFM109RestTest {
    
    private static Id pricebookId = ControllerUtil.getStandardPricebook().Id;
    static Account createHospital( String hospitalName) {
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001Trigger = true;
        // 病院を作る
        Account hospital = new Account();
        hospital.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'HP'].id;
        hospital.Name = hospitalName;
        insert hospital;
        StaticParameter.EscapeAccountTrigger = true;
        return hospital;
    }

    static List<Account> selectStrategicDep( Account hospital) {
        // 戦略科室を得る
        List<Account> strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_GI'];
        return strategicDep;
    }

    static Account createDep( Account hospital, Account strategicDep) {
        // 診療科を作る
        Account dep = new Account();
        dep.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'Department_GI'].id;
        dep.Name = 'test dep';
        dep.ParentId = strategicDep.Id;
        dep.Department_Class__c = strategicDep.Id;
        dep.Hospital__c = hospital.Id;
        // dep.State_Text__c = '上海市';
        insert dep;
        return dep;
    }

    static Asset createAsset( Account hospital, Account strategicDep, Account dep) {
        // 製品を作る
        Product2 productA = new Product2( Name = 'テスト商品');
        insert productA;

        // 価格表エントリを作成する
        PricebookEntry entry = new PricebookEntry( Pricebook2Id = pricebookId, Product2Id = productA.Id);
        entry.UnitPrice = 0;
        entry.IsActive = true;
        entry.UseStandardPrice = false;
        entry.CurrencyIsoCode = 'CNY';
        entry.Product2Id = productA.Id;
        insert entry;

        // 納入機器を作成する
        Asset asset = new Asset();
        asset.Name = 'テスト機器';
        asset.AccountId = dep.Id;
        asset.Department_Class__c = strategicDep.Id;
        asset.Hospital__c = hospital.Id;
        asset.SerialNumber = 'testserial';
        asset.Quantity = 3;
        // asset.Extend_Gurantee_DateTo_Text__c =Date.today().addDays(30);
        // asset.IS_Extend_Gurantee_Txt__c =true;
        // asset.Order_No__c = 'BJ_2020';

        insert asset;

        return asset;
    }


    @IsTest
    static void myTest(){
        
        ControllerUtil.EscapeNFM001Trigger = true;

        //  病院、戦略科室、診療科の情報を作成します
        Account hospital = createHospital( 'test hospital');
        Account[] strategicDep = selectStrategicDep( hospital);
        Account dep = createDep( hospital, strategicDep[0]);

        // 納入機器を作る
        Asset asset = createAsset( hospital, strategicDep[0], dep);

        // 修理を作成する01
        Repair__c re = new Repair__c();
        re.SAPRepairNo__c = '000010168255';
        re.Account__c = dep.Id;
        re.Department_Class__c = strategicDep[0].Id;
        re.Hospital__c = hospital.Id;
        re.Delivered_Product__c = asset.Id;
        re.SERVICE_CONTRACT_JUDEGE_DAY__C = Date.today().addDays( -1000); // 维修合同判断日がサービス契約のだいぶ前
        re.Failure_Occurrence_Date__c  = Date.today();
        re.InspectionCategory_Zero__c = '0';
        re.IISE_Inspection_Branch_Zero__c = '1';
        insert re;

        PAE_DecisionRecord__c record = new PAE_DecisionRecord__c(
            PAE_DetermineResults__c = 'nonPAE',                    // PAE判定结果
            PAE_ConfirmationDate__c = Date.valueOf('2020-05-06'),  // OCSM QARA确认日
            PAE_Authenticator__c = '00510000005sEEM',              // OCSM QARA确认者
            PAE_reappear_confirm__c = '未确认'                       // 再现结果确认
        );
        record.PAE_Repair__c = re.Id;
        record.RecordTypeId = Schema.SObjectType.PAE_DecisionRecord__c.getRecordTypeInfosByDeveloperName().get('ASRCDecision').getRecordTypeId();
        insert record;

        PAE_DecisionRecordDetail__c detail1 = new PAE_DecisionRecordDetail__c(
            PAED_RCAC__c = 'Intake',                              // Intake/Final
            PAED_ManagementCode__c = 'test001',                     // Code
            PAED_Status__c = '有效',                                  // 状态
            PAED_ConfirmationDate__c = Date.valueOf('2020-05-06'),  // 确认日
            PAED_Affirmant__c = '00510000005sEEM',                  // 确认者
            PAE_DecisionRecordD__c = 'a3q1s0000008Sxg',             // PAE判定记录
            isInterfaceCreate__c = false,                           // 是否通过接口新建
            PAE_Judge__c = 'nonPAE',                                // PAE判定
            PAED_Reappear_Result__c = '不再現',                    // 再现結果
            InspectionCategory109__c = '0'
        );
        detail1.PAE_DecisionRecordD__c = record.Id;
        detail1.PAED_Repair__c = re.Id;
        insert detail1;

        // PAEDetail.PAE_Judge__c = intake.PaeFlag == 'true' ? 'PAE' : 'nonPAE'; 
        // PAEDetail.PAED_Reappear_Result__c = intake.NotReproduceFlag == 'true' ? '不再現' : '再現';

        PAE_DecisionRecordDetail__c detail2 = new PAE_DecisionRecordDetail__c(
            PAED_RCAC__c = 'Intake',                              // Intake/Final
            PAED_ManagementCode__c = 'GIA11',                     // Code
            PAED_Status__c = '有效',                                  // 状态
            PAED_ConfirmationDate__c = Date.valueOf('2020-05-06'),  // 确认日
            PAED_Affirmant__c = '00510000005sEEM',                  // 确认者
            PAE_DecisionRecordD__c = 'a3q1s0000008Sxg',             // PAE判定记录
            isInterfaceCreate__c = false,                           // 是否通过接口新建
            PAE_Judge__c = 'nonPAE',                                // PAE判定
            PAED_Reappear_Result__c = '不再現'                    // 再现結果
        );
        detail2.PAE_DecisionRecordD__c = record.Id;
        detail2.PAED_Repair__c = re.Id;
        insert detail2;

        PAE_DecisionRecord__c record2 = new PAE_DecisionRecord__c(
            PAE_DetermineResults__c = 'nonPAE',                    // PAE判定结果
            PAE_ConfirmationDate__c = Date.valueOf('2020-05-06'),  // OCSM QARA确认日
            PAE_Authenticator__c = '00510000005sEEM',              // OCSM QARA确认者
            PAE_reappear_confirm__c = '未确认'                       // 再现结果确认
        );
        record2.PAE_Repair__c = re.Id;
        record2.RecordTypeId = Schema.SObjectType.PAE_DecisionRecord__c.getRecordTypeInfosByDeveloperName().get('ASACDecision').getRecordTypeId();
        insert record2;

        List<PAE_DecisionRecord__c> PAEDecisionRecords = [select id,name from PAE_DecisionRecord__c where PAE_Repair__c = :re.Id];
        System.debug('PAEDecisionRecords.size()'+PAEDecisionRecords.size());

        Test.startTest();

        RestRequest req = new RestRequest();
        RestResponse res = new RestResponse();

        String JsonMsg = '{"InspectionRequest":{"InspectionResult":{"ThirdParty":"True",';
        JsonMsg += '"SAPRepairNotificationNo":"000010168255",';
        JsonMsg += '"Quotation":[{"RepairRank":"B","Parts":[{"Qty":"3","ItemCode":"GE782500","BomCode":"BM064248"}],';
        JsonMsg += '"CafeteriaFlag":"False","ActivityCode":["1002","3302"]}],';
        JsonMsg += '"ProductCode":"GIF-H190","Measure":{"CumulativeUses":"111","CumulativeTimes":"222"},';
        JsonMsg += '"IntakeInfo":[{"PaeFlag":"False","NotReproduceIntakeUniversalDesc":"投诉尚未确认","NotReproduceIntakeUniversal":"GIA11Z",';
        JsonMsg += '"NotReproduceFlag":"True","IntakeUniversalDesc":"无吸力","IntakeUniversal":"000"},';
        JsonMsg += '{"PaeFlag":"True","NotReproduceIntakeUniversalDesc":"","NotReproduceIntakeUniversal":"","NotReproduceFlag":"False",';
        JsonMsg += '"IntakeUniversalDesc":"No products in the RSA product list","IntakeUniversal":"GIA11"}],';
        JsonMsg += '"InspectionUserInEnglish":"Shuai Li","InspectionUser":"李帅","InspectionResultFlag":"False",';
        JsonMsg += '"InspectionDate":"20200716","InspectionComment":"0716_test Inspection","InspectionCategory":"0",';
        JsonMsg += '"InspectionBranchNo":"2","FailureCause":"0716_test failure comment",';
        JsonMsg += '"Failure":[{"Phenomenon":"5G","PaeFlag":"True","LocationGroupDesc":"插入部","LocationGroup":"7","LocationDesc":"C本体",';
        JsonMsg += '"Location":"A01","FinalUniversalDesc":"其他故障模式","FinalUniversal":"GIL1201Y","EtqPart":"","EtqCause":"-",';
        JsonMsg += '"EtqAsAnalyzed":"","Description":"A015GA6AA","Cause":"611"},{"Phenomenon":"4A","PaeFlag":"False",';
        JsonMsg += '"LocationGroupDesc":"内镜连接座部","LocationGroup":"1","LocationDesc":"本体","Location":"H01",';
        JsonMsg += '"FinalUniversalDesc":"外部金属部件的电气连接变弱-插入管和弯曲部分之间发生电气连续性错误（故障导致主体接地测试）",';
        JsonMsg += '"FinalUniversal":"GII2001A","EtqPart":"P0004","EtqCause":"C023","EtqAsAnalyzed":"AAEL0072","Description":"H014AB2AD",';
        JsonMsg += '"Cause":"980"}],"EtQManagementNo":"0716_test_etq","DomainCaption":"com.olympus.china","CafeteriaPlanFlag":"False"}}}';
        
        req.requestURI = 'services/apexrest/NFM109';
        req.httpMethod = 'POST';
        req.addHeader('content-type', 'application/json');
        req.requestBody = Blob.valueof(JsonMsg);
        RestContext.request = req;
        RestContext.response = res;

        NFM109Rest.execute();

        Test.stopTest();
        System.debug('response'+res.responseBody);
        re = [select id,name,SAP_Service_Repair_No__c,
                        IISE_Inspection_Branch_Zero__c,IISE_Inspection_Branch_Three__c,
                        IISE_confirmed_person__c,IISE_confirmed_person_en__c,
                        InspectionCategory_Zero__c,InspectionCategory_Three__c
                        from repair__c ];

        System.debug('re updated '+re);
        Map<Id,PAE_DecisionRecord__c> recordsMap = new Map<Id,PAE_DecisionRecord__c>([select id,name,PAE_reappear_confirm__c from PAE_DecisionRecord__c where PAE_Repair__c = :re.Id]);
        for (PAE_DecisionRecord__c ele : recordsMap.values()) {
            System.debug('record'+ele);
        }

        List<PAE_DecisionRecordDetail__c> details = [select id,PAED_ManagementCode__c,PAED_RCAC__c,PAED_Status__c,
                                                        PAE_Judge__c,PAE_DecisionRecordD__c,PAED_Repair__c,PAED_Repair__r.name,
                                                        LocationGroup__c,Location__c,Phenomenon__c,Description__c,Cause__c,EtqPart__c,
                                                        EtqAsAnalyzed__c,EtqCause__c,FinalUniversalDesc__c,PAED_Reappear_Result__c,InspectionCategory109__c 
                                                        from PAE_DecisionRecordDetail__c where PAE_DecisionRecordD__c in :recordsMap.keySet()];
        for (PAE_DecisionRecordDetail__c detail : details) {
            System.debug('detail'+detail);
        }

        List<BatchIF_Log__c> logs = [select id,name,type__c,ErrorLog__c,Last_Update_Date2__c from BatchIF_Log__c where type__c = 'NFM109'];
        System.debug('logs'+logs);
        
    }

}