@isTest
private class NFM603ControllerTest {
    static testMethod void testMethod1() {
        
    }

    @testSetup
    static void makeTestRepair() {
        Oly_TriggerHandler.bypass('ContactTriggerHandler');

        ControllerUtil.EscapeNFM001Trigger = true;
        StaticParameter.EscapeNFM001Trigger = true;
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001AgencyContractTrigger2 = true;
        StaticParameter.EscapeOppandStaTrigger = true;
        
        List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '病院'];
        if (rectCo.size() == 0) {
            throw new ControllerUtil.myException('not found 病院 recodetype');
        }
        List<RecordType> rectSct = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '戦略科室分類 消化科'];
        if (rectSct.size() == 0) {
            throw new ControllerUtil.myException('not found 戦略科室分類 呼吸科 recodetype');
        }
        List<RecordType> rectDpt = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '診療科 消化科'];
        if (rectDpt.size() == 0) {
            throw new ControllerUtil.myException('not found 診療科 消化科 recodetype');
        }
        // 省
        Address_Level__c al = new Address_Level__c();
        al.Name = '東京';
        al.Level1_Code__c = 'CN-99';
        al.Level1_Sys_No__c = '999999';
        insert al;
        // 市
        Address_Level2__c al2 = new Address_Level2__c();
        al2.Level1_Code__c = 'CN-99';
        al2.Level1_Sys_No__c = '999999';
        al2.Level1_Name__c = '東京';
        al2.Name = '渋谷区';
        al2.Level2_Code__c = 'CN-9999';
        al2.Level2_Sys_No__c = '9999999';
        al2.Address_Level__c = al.id;
        insert al2;
        // テストデータ
        Account company = new Account();
        company.RecordTypeId = rectCo[0].Id;
        company.Name         = 'NFM105TestCompany';
        upsert company;
        // Account section = [Select State_Master__c,Salesdepartment_HP__c,Management_Code__c, Management_Code_Auto__c, Name, Id from Account where ParentId = :company.Id and RecordTypeId = :rectSct[0].Id];
        Account section = [Select State_Master__c,Salesdepartment_HP__c,Management_Code__c, Name, Id from Account where ParentId = :company.Id and RecordTypeId = :rectSct[0].Id];

        Account depart = new Account();
        depart.RecordTypeId        = rectDpt[0].Id;
        depart.AgentCode_Ext__c = '10086';
        depart.Name                = '*';
        depart.Department_Name__c  = 'NFM105TestDepart';
        depart.ParentId            = section.Id;
        depart.Department_Class__c = section.Id;
        depart.Hospital__c         = company.Id;
        depart.State_Master__c = al.id;
        upsert depart;

        Product2 prd1 = new Product2();
        prd1.ProductCode_Ext__c     = 'NFM105Prd1';
        prd1.ProductCode            = 'NFM105Prd1';
        prd1.Repair_Product_Code__c = 'NFM105Prd1_RP';
        prd1.Name                   = 'NFM105Prd1';
        prd1.Manual_Entry__c        = false;
        insert prd1;

        Asset ast = new Asset();
        ast.Name                   = 'NFM105Ast1';
        ast.AccountId              = depart.Id;
        ast.Department_Class__c    = section.Id;
        ast.Hospital__c            = company.Id;
        ast.Product2Id             = prd1.Id;
        ast.SerialNumber           = 'NFM105SerialNumber';
        ast.Guarantee_period_for_products__c = Date.today();
        ast.InstallDate                      = Date.today();
        insert ast;
        // ast = [select Id, Name, Product_Serial_No__c, AccountId, Department_Class__c, Department_Class__r.Management_Code_Auto__c, Hospital__c, Product2Id, Product2.ProductCode, Product2.Repair_Product_Code__c, SerialNumber
        //        from Asset
        //        where Id = :ast.Id];
        ast = [select Id, Name, Product_Serial_No__c, AccountId, Department_Class__c, Hospital__c, Product2Id, Product2.ProductCode, Product2.Repair_Product_Code__c, SerialNumber
               from Asset
               where Id = :ast.Id];
        RepairSubOrder__c subOrder = new RepairSubOrder__c();
        subOrder.AttachmentDownload__c = true;
        subOrder.AttachmentLink__c = 'https://albsylfw.s3.cn-northwest-1.amazonaws.com.cn/20211220/14/11/30/lessthan12/5e8cb69e-f935-48f5-825e-b8344d60f6d4.zip';
        subOrder.AttachmentName__c = '测试附件下载';
        subOrder.Status__c = '待处理';// 20230201 ljh 
        insert subOrder;
        Repair__c rpr = new Repair__c();
        rpr.PAE_Determine__c = 'PAE' ;   //-- 
        rpr.ifDeadHurt__c = '有';        //-- R1
        rpr.PAE_DetermineAC__c = null;   //--
        rpr.SAPRepairNo__c   = 'NFM105Rpr1';
        rpr.Account__c             = depart.Id;
        rpr.Department_Class__c    = section.Id;
        rpr.Hospital__c            = company.Id;
        rpr.DeliveryLogisticsMode__c = '其他';
        rpr.RepairSubOrder__c = subOrder.Id;
        rpr.Delivered_Product__c   = ast.Id;
        rpr.Status__c              = '1.受理完毕';
        rpr.SAP_Transfer_time__c = null;
        rpr.Incharge_Staff__c = Userinfo.getUserId();
        rpr.Repair_Detail__c = 'test';
        rpr.GeneratedPDFField__c = null;
        rpr.AsyncData__c    = true;
        rpr.AwaitToSendAWS__c = false;
        rpr.Complaint_Number__c = null;
        rpr.ReportAdverseEvents__c = '有';
        rpr.ProblemOccurred__c = '到货验收';
        rpr.ifDeadHurt__c = '有';
        rpr.ASReportedCode__c = 'TEST01,TEST02';
        rpr.ASReportedCodeAC__c = 'TEST02,TEST04';
        rpr.DateReceiptQuestions__c = Date.today();
        rpr.Failure_Occurrence_Date__c = Date.today();
        rpr.Repair_Ordered_Date__c = Date.today();
        rpr.Repair_Shipped_Date__c = Date.today();
        rpr.Repair_Ordered_DateTime__c = Datetime.newInstance(2022,04,13,18,18,18);
        rpr.ReturnType__c = 'A20';
        rpr.AwaitToSendAWS__c = true;
        rpr.AWS_Data_Id__c='0156455';
        //rpr.Returns_Product_waySAP__c = '返送医院';
        insert rpr;

        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Log__c = '[{"userReturnDate":"2021-08-09","userAgreeDAte":"2021-08-09","strategicDepartmenNm":null,"strategicDepartmenCd":"8089815","spareEquipMode":null,"spareEquipLendingDate":null,"SAPrepairApplyDate":"2021-08-05","returnStage":null,"returnLogisticsSendTime":"2021-08-03T09:49:00.000Z","returnLogisticsRemark":"123123","returnLogisticsReceiveTime":"2021-08-19T09:49:00.000Z","returnLogisticsNo":"123123","returnLogisticsMode":null,"RepairType":null,"repairStartDate":"2021-08-09","repairproductsRevDate":"2021-08-10","repairOrderNo2":null,"repairOrderNo":null,"repairOrderCreateDate":"2021-08-03T10:05:44.000Z","repairOrderCompleteDate":"2021-08-09","repairNo":"RS-202108-564405","repairCompleteExpectedDate":null,"repairCompleteDate":"2021-08-09","repairApplicant":"SFDC-05","region":"東京","RCreturnDate":"2021-08-09","RCacceptanceDate":"2021-08-09","quotationDate":null,"province":"北京市","priceApprovalDate":null,"planQuotationDate":"2021-08-11","payCompleteDate":"2021-08-09","partsCompleteDate":"2021-08-09","officeLogisticsReceiveDate":"2021-08-10","MultiYearContractStartDate":null,"MultiYearContractNo":null,"MultiYearContractEndDate":null,"logisticsSendDate":"2021-08-04","logisticsReceiveDate":"2021-08-19","latestPayDate":null,"isRepairWarrantyObj":false,"invoiceReceiveDate":"2021-08-09","invoiceDate":null,"inspectionDate":"2021-08-09","incomeReckoninDate":"2021-08-09","hospitalNm":"1","hospitalCd":"8089815","FSErepairApplyDate":"2021-08-17","FirstQuotationDate":null,"finalTestDate":"2021-08-09","finalQuotationPrice":152.2,"FaultDescData":null,"equipmentModel":"GX2201:111222","equipmentCd":"111222","detectionResult":null,"departmentNm":"8089815","departmentCd":null,"deliveryLogisticsNo":"123123","deliveryLogisticsMode":"快递","ContractStartDate":null,"ContractNo":null,"ContractEndDate":null,"city":"北京市","cancelRepairDate":"2021-08-09","bpsqbh":null,"applySpareEquip":false,"applicantTel":null,"ActualQuotationDate":"2021-08-09","acceptanceFormSendDate":"2021-08-09","acceptanceFormReceivedDate":"2021-08-09","abandonPayDate":null},{"userReturnDate":"2021-08-09","userAgreeDAte":"2021-08-09","strategicDepartmenNm":null,"strategicDepartmenCd":"8089815","spareEquipMode":null,"spareEquipLendingDate":null,"SAPrepairApplyDate":"2021-08-05","returnStage":null,"returnLogisticsSendTime":"2021-08-03T09:49:00.000Z","returnLogisticsRemark":"====","returnLogisticsReceiveTime":"2021-08-04T02:23:00.000Z","returnLogisticsNo":"20210804-1","returnLogisticsMode":null,"RepairType":null,"repairStartDate":"2021-08-09","repairproductsRevDate":"2021-08-10","repairOrderNo2":null,"repairOrderNo":null,"repairOrderCreateDate":"2021-08-04T02:39:59.000Z","repairOrderCompleteDate":"2021-08-09","repairNo":"RS-202108-564406","repairCompleteExpectedDate":"2021-08-09","repairCompleteDate":"2021-08-09","repairApplicant":"SFDC-05","region":"其他","RCreturnDate":"2021-08-09","RCacceptanceDate":"2021-08-09","quotationDate":null,"province":"北京市","priceApprovalDate":null,"planQuotationDate":"2021-08-10","payCompleteDate":"2021-08-09","partsCompleteDate":"2021-08-09","officeLogisticsReceiveDate":"2021-08-10","MultiYearContractStartDate":null,"MultiYearContractNo":"BJ-RS-BJ0063159","MultiYearContractEndDate":null,"logisticsSendDate":"2021-08-21","logisticsReceiveDate":"2021-08-15","latestPayDate":null,"isRepairWarrantyObj":false,"invoiceReceiveDate":"2021-08-09","invoiceDate":null,"inspectionDate":"2021-08-09","incomeReckoninDate":"2021-08-09","hospitalNm":"1","hospitalCd":"8089815","FSErepairApplyDate":"2021-08-17","FirstQuotationDate":null,"finalTestDate":"2021-08-09","finalQuotationPrice":152.2,"FaultDescData":null,"equipmentModel":"GX2201:111222","equipmentCd":"111222","detectionResult":null,"departmentNm":"8089815","departmentCd":null,"deliveryLogisticsNo":"20210804","deliveryLogisticsMode":"快递","ContractStartDate":null,"ContractNo":"BJ-RS-BJ0063159","ContractEndDate":null,"city":"北京市","cancelRepairDate":"2021-08-09","bpsqbh":null,"applySpareEquip":false,"applicantTel":null,"ActualQuotationDate":"2021-08-10","acceptanceFormSendDate":"2021-08-09","acceptanceFormReceivedDate":"2021-08-09","abandonPayDate":null,"supplySpareEquip":true}]';
        iflog.Type__c = '603test';
        insert iflog;

        Repair_reason__c rrn = new Repair_reason__c();
        rrn.Repair__c = rpr.Id;
        rrn.DescriptionName__c = '121212';
        rrn.LocationName__c = '121212';
        rrn.ActivityDescription__c = '121212';
        insert rrn;

        // 戦略科室を得る
        Account[] strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :company.Id AND recordType.DeveloperName = 'Department_Class_OTH'];

        Contact contact2 = new Contact();
        contact2.AccountId = depart.Id;
        contact2.FirstName = '責任者';
        contact2.LastName = 'test1经销商';
        insert contact2;
        // 备品配套1(主体 两个附属品(个体管理 数量管理))
        Fixture_Set__c fsObjA1 = new Fixture_Set__c();
        fsObjA1.Name = 'set1';
        fsObjA1.Fixture_Set_Body_Model_No__c = 'modelNo1';
        fsObjA1.Loaner_name__c = 'name1';
        insert fsObjA1;

        //备品借出申请
        /*Rental_Apply__c raObj = new Rental_Apply__c();
        raObj.Name = 'testra';
        raObj.Product_category__c = 'GI';
        raObj.Demo_purpose1__c = '产品试用';
        raObj.demo_purpose2__c = FixtureUtil.raDemo_purpose2MAP.get('shiyongwuxunjia');
        raObj.direct_send__c = '医疗机构';
        raObj.Loaner_received_staff__c = '王五';
        raObj.Loaner_received_staff_phone__c = '110';
        raObj.direct_shippment_address__c = '北京市';
        raObj.Hospital__c = company.Id;
        raObj.Strategic_dept__c = strategicDep[0].Id;
        raObj.Account__c = depart.Id;
        raObj.Request_shipping_day__c = Date.toDay();  // 希望到货日
        raObj.Hope_Lonaer_date_Num__c = 1;  // 希望借用天数
        // 预定归还日自动生成 预定归还日=（希望到货日+希望借用天数）-1
        // raObj.Request_return_day__c = Date.toDay();  // 预定归还日
        // B.OLY_OCM-669 入力规则: 希望借用天数不能为空
        raObj.Phone_number__c = '1234567890';
        raObj.Loaner_medical_Staff__c = contact2.Id;
        raObj.Repair__c = rpr.Id;
        insert raObj;*/

        Fixture_Set_Detail__c fsdObjA1 = new Fixture_Set_Detail__c();

        // 备品配套
        // Fixture_Set__c fsObj1 = new Fixture_Set__c();
        // fsObj1.Name = 'set1';
        // fsObj1.Fixture_Set_Body_Model_No__c = 'modelNo1';
        // fsObj1.Loaner_name__c = 'name1';
        // insert fsObj1;

        // 产品
        Product2 pro1 = new Product2(Name='name01',IsActive=true,Family='GI',
                Fixture_Model_No__c='n01',Serial_Lot_No__c='S/N tracing',
                Fixture_Model_No_T__c = 'n01',
                ProductCode_Ext__c='pc01',Manual_Entry__c=false);
        // 备品配套明细
        fsdObjA1.Name = '备品配套明细名1';
        fsdObjA1.Name_CHN_Created__c = '中文名称1';
        fsdObjA1.Product2__c = pro1.Id;
        fsdObjA1.Fixture_Set__c = fsObjA1.Id;
        fsdObjA1.Is_Body__c = true;
        fsdObjA1.Is_Optional__c = false;
        fsdObjA1.UniqueKey__c = fsObjA1.Id + ':' + pro1.Id;
        fsdObjA1.SortInt__c = 1;

        // 借出备品配套一览
       /* Rental_Apply_Equipment_Set__c raesObj = new Rental_Apply_Equipment_Set__c();
        raesObj.Rental_Apply__c = raObj.Id;
        raesObj.Fixture_Set__c = fsObjA1.Id;
        raesObj.Cancel_Select__c = false;
        raesObj.Rental_Start_Date__c = Date.toDay();
        raesObj.Rental_End_Date__c = Date.toDay();
        raesObj.IndexFromUniqueKey__c = 1;
        raesObj.UniqueKey__c = '1:'+ fsObjA1.Id + ':1';
        insert raesObj;

        // 借出备品配套一览明细
        Rental_Apply_Equipment_Set_Detail__c raesdObj1 = new Rental_Apply_Equipment_Set_Detail__c();
        raesdObj1.Rental_Apply__c = raObj.Id;
        raesdObj1.Fixture_Set_Detail__c = fsdObjA1.Id;
        raesdObj1.Rental_Num__c = 1;
        raesdObj1.Queue_Number__c = null;
        raesdObj1.Is_Body__c = true;
        raesdObj1.Cancel_Select__c = false;
        raesdObj1.IndexFromUniqueKey__c = 1;
        raesdObj1.UniqueKey__c = '1:'+ raesObj.Id + ':' + fsdObjA1.Id + ':1';
        raesdObj1.Salesdepartment_before__c = '1.华北营业本部';
        raesdObj1.Internal_asset_location_before__c = '北京 备品中心';
        raesdObj1.Product_category_text__c = 'GI';
        raesdObj1.Equipment_Type_text__c = '产品试用';
        raesdObj1.Shippment_loaner_time__c = Date.today();
        raesdObj1.Repair__c = rpr.Id;
        raesdObj1.Fixture_Model_No_text__c = '11111';
        raesdObj1.Rental_Apply_Equipment_Set__c = raesObj.Id;
        raesdObj1.Inspection_result_after__c = 'NG';
        raesdObj1.DataMigration_Flag__c  = true;
        insert raesdObj1;
        raesObj.First_RAESD__c = raesdObj1.Id;
        update raesObj; */
    }

    @isTest
    static void testCallOut1(){
      List<Repair__c> repairList = [select id from Repair__c];
      Test.startTest();
        List<Id> idList = new List<Id>();
        for(Repair__c repair : repairList){
          idList.add(repair.Id);
        }
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Log__c = 'test start \n';
        insert iflog;

        NFM603Controller.callout(iflog.Id,idList);

        Test.stopTest();
    }
    @isTest
    static void testCallOut3(){
      List<Repair__c> repairList = [select id from Repair__c];
      Test.startTest();
        List<Id> idList = new List<Id>();
        for(Repair__c repair : repairList){
          idList.add(repair.Id);
        }
        NFM603Controller.callout('',idList);

        Test.stopTest();
    }
    @isTest
    static void testCallOut1_2(){
      List<Repair__c> repairList = [select id,Repair_Ordered_DateTime__c,OTSRepairOrder__c,SAP_Transfer_time__c,Status__c from Repair__c];
      Test.startTest();
        List<Id> idList = new List<Id>();
        for(Repair__c repair : repairList){
            repair.Repair_Ordered_DateTime__c = Datetime.newInstance(2022,04,13,05,18,18);
        repair.SAP_Transfer_time__c = Datetime.newInstance(2022,04,13,18,18,18);
            repair.OTSRepairOrder__c = '123123123';
          // idList.add(repair.Id);
        }
        upsert repairList;
        for(Repair__c repair : repairList){
          idList.add(repair.Id);
        }
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Log__c = 'test start \n';
        insert iflog;

        NFM603Controller.executefuture(iflog,idList);

        Test.stopTest();
    }

   /*
    @isTest
    static void testcallout2(){
      List<Repair__c> repairList = [select id,RepairOrderStatusCode__c,IncorrectDataComment__c,SAP_not_accept_repair_result__c,Status__c from Repair__c];
      Test.startTest();
        List<Id> idList = new List<Id>();
        for(Repair__c repair : repairList){
            repair.RepairOrderStatusCode__c = 'A99';
            repair.SAP_not_accept_repair_result__c = Date.toDay();
            repair.IncorrectDataComment__c = '123123123';
          // idList.add(repair.Id);
        }
        upsert repairList;
        for(Repair__c repair : repairList){
          idList.add(repair.Id);
        }
        BatchIF_Log__c iflog = new BatchIF_Log__c();
        iflog.Log__c = 'test start \n';
        insert iflog;

        NFM603Controller.executefuture(iflog,idList);

        Test.stopTest();
    }
    */

    // @isTest
    // static void testcallout3(){
    //   BatchIF_Log__c iflog = [select id from BatchIF_Log__c where Type__c = '603test' limit 1];
    //     NFM603Controller.ManualExecute(iflog.Id);
    // }

    // @isTest
    // static void NFM603BatchTest01(){
    //     Test.startTest();
    //     Database.executeBatch(new NFM603Batch(),100);
    //     Test.stopTest();
    // }

    // @isTest
    // static void NFM603BatchTest02(){

    //     List<Repair__c> repairList = [select id from Repair__c];

    //     Test.startTest();

    //     List<Id> idList = new List<Id>();
    //     for(Repair__c repair : repairList){
    //         idList.add(repair.Id);
    //     }
    //     Database.executeBatch(new NFM603Batch(idList),100);
    //     Test.stopTest();
    // }
    @isTest
    static void NFM603execute(){
        List<BatchIF_Log__c> logList = [select id from BatchIF_Log__c];
        Test.startTest();
        BatchIF_Log__c iflog = logList[0];
        NFM603Controller.ManualExecute(iflog.Id);
        Test.stopTest();
    }
    @isTest
    static void NFM603execute1(){
        List<BatchIF_Log__c> logList = [select id from BatchIF_Log__c];
        Test.startTest();
        BatchIF_Log__c iflog = logList[0];
        NFM603Controller.ManualExecute('');
        Test.stopTest();
    }

}