@isTest
private class RentalApplyTriggerTest {
    private static Id pricebookId = ControllerUtil.getStandardPricebook().Id;
    // 20220527 ljh SWAG-CDTEFS start
    // AWSServiceTool2没上线就把这部分注释 start 20220408
   @TestSetup
    static void setup(){
        TestDataUtility.CreatePIPolicyConfigurations(new string[]{'Agency_Contact__c','Contact'});
    } 
    
  @isTest
    static void Test1(){
        Test.setMock(HttpCalloutMock.class, new HttpMock());

        List<Agency_Contact__c> lra = new List<Agency_Contact__c>();
        lra.add(new Agency_Contact__c(
        ));
        insert lra;
        Test.startTest();
        //system.debug(PIHelper.getPIIntegrationInfo('Agency_Contact__c').newEncryptUrl);
        AWSServiceTool2.EncryptPushCore(Json.serialize(lra),'Agency_Contact__c');
        AWSServiceTool2.EncryptPushFuture(null,null);
        Test.stopTest();
    }

  @isTest
    static void Test2(){
        Test.setMock(HttpCalloutMock.class, new HttpMock());

        List<Agency_Contact__c> lra = new List<Agency_Contact__c>();
        lra.add(new Agency_Contact__c(
            Aws_Data_Id__c = '123456'
        ));
        insert lra;
        Test.startTest();
        //system.debug(PIHelper.getPIIntegrationInfo('Agency_Contact__c').newEncryptUrl);
        AWSServiceTool2.EncryptPushCore(Json.serialize(lra),'Agency_Contact__c');
        Test.stopTest();
    }

    @isTest
    static void Test3(){
        Test.setMock(HttpCalloutMock.class, new HttpMock());


        Test.startTest();
        AWSServiceTool2.EncryptPushData(new string[]{'0031000000O4Cff'});

        Test.stopTest();
    }

  //@isTest
  //  static void Test2(){
  //      Test.setMock(HttpCalloutMock.class, new HttpMock());

  //      List<Agency_Contact__c> lra = new List<Agency_Contact__c>();
  //      lra.add(new Agency_Contact__c(
  //          Id = 'a2R1m0000007BPD',
  //          Aws_Data_Id__c = '123456'
  //      ));
  //      Test.startTest();
  //      //system.debug(PIHelper.getPIIntegrationInfo('Agency_Contact__c').newEncryptUrl);
  //      AWSServiceTool2.EncryptPushCore(Json.serialize(lra),'Agency_Contact__c');
  //      Test.stopTest();
  //  }
    
    class HttpMock implements HttpCalloutMock{
        
        public HTTPResponse respond(HTTPRequest request) {
        // 创建一个假的回应
        System.debug('------------------------------------------------------');
        HttpResponse response = new HttpResponse();
        string body = '';
        system.debug(request.getEndpoint());
        if(request.getEndpoint().contains('token')){
            system.debug('url=token');
            response.setHeader('Content-Type', 'application/json');
      body='{ "message": "", "object": "freqfewqfewewfewfew", "status": "", "success": true, "timestamp": 0, "txId": "" }';          
        } else if(request.getEndpoint().contains('insert')){
            system.debug('url=Insert');
            response.setHeader('Content-Type', 'application/json');
      body='{ "message": "", "object": [ { "dataId": "123456", "directShippmentAddress": "", "directShippmentAddressEncrypt": "", "isDelete": 0, "phoneNumber": "", "phoneNumberEncrypt": "", "sfRecordId": "a2R1m0000007BPD" } ], "status": "", "success": true, "timestamp": 0, "txId": "" }';          
        } else if(request.getEndpoint().contains('update')){
            system.debug('url=update');
            response.setHeader('Content-Type', 'application/json');
      body='{ "message": "", "object": [ { "dataId": "123456", "directShippmentAddress": "", "directShippmentAddressEncrypt": "", "isDelete": 0, "phoneNumber": "", "phoneNumberEncrypt": "", "sfRecordId": "a2R1m0000007BPD" } ], "status": "", "success": true, "timestamp": 0, "txId": "" }';          
        } else{
          
        }
        
        response.setBody(body);
        response.setStatus('OK');
        response.setStatusCode(200);
        return response;
        // }
    }
    }
    // AWSServiceTool2没上线就把这部分注释 end
    // 20220527 ljh SWAG-CDTEFS end
    static testMethod void myUnitTest() {
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001Trigger = true;
        // システム管理者
        User user = new User(Test_staff__c = true);
        user.LastName = '_サンブリッジ';
        user.FirstName = 'う';
        user.Alias = 'う';
        user.Email = 'olympusTest03@sunbridge.com';
        user.Username = 'olympusTest03@sunbridge.com';
        user.CommunityNickname = 'う';
        user.IsActive = true;
        user.EmailEncodingKey = 'ISO-2022-JP';
        user.TimeZoneSidKey = 'Asia/Tokyo';
        user.LocaleSidKey = 'ja_JP';
        user.LanguageLocaleKey = 'ja';
        user.ProfileId = System.Label.ProfileId_SystemAdmin;
        user.Job_Category__c = '销售推广';
        user.Province__c = '上海市';
        user.Dept__c='医疗华北营业本部';
        user.Use_Start_Date__c = Date.today().addMonths(-6);
        user.SalesManager__c = UserInfo.getUserId();
        user.BuchangApprovalManagerSales__c = UserInfo.getUserId();
        user.JingliApprovalManager__c = UserInfo.getUserId();
        user.BuchangApprovalManager__c = UserInfo.getUserId();
        user.ZongjianApprovalManager__c = UserInfo.getUserId();

        // MIXED_DML_OPERATION, DML operation on setup object is not permitted Error
        System.runAs(new User(Id = Userinfo.getUserId())) {
            user.Foul_Points__c = Integer.valueOf(System.Label.EquipmentRentalBlackList);
            insert user;
            List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '病院'];
            if (rectCo.size() == 0) {
                return ;
            }
            List<RecordType> rectSct = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '戦略科室分類 呼吸科'];
            if (rectSct.size() == 0) {
                return;
            }
            List<RecordType> rectDpt = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN ('診療科 消化科', '診療科 呼吸科') order by Name desc];
            if (rectDpt.size() == 0) {
                return;
            }

            // insert
            Account company1 = new Account();
            Account company2 = new Account();
            company1.RecordTypeId = rectCo[0].Id;
            company1.Name = '病院テスト1';
            company2.RecordTypeId = rectCo[0].Id;
            company2.Name = '病院テスト2';
            List<Account> hps = new Account[] {company1, company2};
            insert hps;

            List<Account> dc1s = [Select Id, Name, Department_Class_Label__c, Sys_Dept_Name_Change_Chk__c from Account where Parent.Id = :company1.Id order by Department_Class_Label__c];
            List<Account> dc2s = [Select Id, Name, Department_Class_Label__c, Sys_Dept_Name_Change_Chk__c from Account where Parent.Id = :company2.Id order by Department_Class_Label__c];

            Account depart1 = new Account();
            depart1.RecordTypeId = rectDpt[0].Id;
            depart1.Name         = '*';
            depart1.Department_Name__c  = '診療科1';
            depart1.ParentId            = dc1s[0].Id;
            depart1.Department_Class__c = dc1s[0].Id;
            depart1.Hospital__c         = company1.Id;

            Account depart2 = new Account();
            depart2.RecordTypeId = rectDpt[1].Id;
            depart2.Name         = '*';
            depart2.Department_Name__c  = '診療科2';
            depart2.ParentId            = dc2s[1].Id;
            depart2.Department_Class__c = dc2s[1].Id;
            depart2.Hospital__c         = company2.Id;

            insert new Account[] {depart1, depart2};

            //联系人
            Contact core = new Contact(email = 'jplumber@salesforce.com',
                                       firstname = 'Joe',
                                       lastname = 'Plumber',
                                       accountid = company1.id);
            insert core;

            //备品借出申请
            Account hospital = new Account();
            hospital.RecordTypeId = rectCo[0].Id;
            Rental_Apply__c rentalApply = new Rental_Apply__c();
            //rentalApply.OwnerId = user2.Id;
            //rentalApply.CurrencyIsoCode = 'CNY';
            rentalApply.Name = 'test00001';
            rentalApply.Person_In_Charge__c = user.Id;
            rentalApply.applyUser__c = user.Id;
            rentalApply.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
            rentalApply.Asset_loaner_start_day__c = Date.today();
            rentalApply.Asset_loaner_closed_day__c = Date.today().addDays(10);
            rentalApply.direct_send__c = '经销商';
            rentalApply.direct_shippment_address__c = 'test';
            rentalApply.Request_return_day__c = Date.today() + 30;
            rentalApply.Demo_purpose1__c = '产品试用';
            rentalApply.Demo_purpose2__c = FixtureUtil.raDemo_purpose2MAP.get('shiyongwuxunjia');
            rentalApply.Demo_purpose_text__c = '申请理由Test';
            rentalApply.Request_demo_detail__c = 'IT测试';
            rentalApply.Accsessary__c = '水气按钮';
            rentalApply.Loaner_received_staff__c = 'test00001';
            rentalApply.Loaner_received_staff_phone__c = 'test00001';
            rentalApply.Request_shipping_day__c = Date.today();
            rentalApply.Hope_Lonaer_date_Num__c = 1;
            rentalApply.Account__c = depart1.Id;
            rentalApply.Strategic_dept__c = dc1s[0].Id;
            rentalApply.Hospital__c = company1.Id;
            rentalApply.Loaner_medical_Staff__c = core.Id;
            rentalApply.Request_return_day__c = Date.today() + 5;
            rentalApply.Phone_number__c = '12222222222';

            insert rentalApply;

            // 黑名单用户不能提交申请的限制删除
            rentalApply.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Shen_Qing_Zhong.ordinal());
            rentalApply.Person_In_Charge__c = user.Id;

            System.Test.startTest();

            try {
                update rentalApply;
                // TODO OCSM_BP3-187 assert失败 先注释掉 start
                //System.assertEquals(Integer.valueOf(System.Label.EquipmentRentalBlackList), user.Foul_Points__c);
                //System.assertEquals(user.Id, rentalApply.OwnerId);
                // TODO OCSM_BP3-187 assert失败 先注释掉 end
                // throw new ControllerUtil.myException('没有发生，黑名单用户不能提交申请');
            } catch (Exception e) {
                // System.assertEquals(FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal()), rentalApply.Status__c);
                //new User(Id = Userinfo.getUserId())
                // System.assertEquals(user.id, Userinfo.getUserId());
                rentalApply = [SELECT Name
                               FROM Rental_Apply__c
                               WHERE Id = :rentalApply.Id];
                System.assertEquals(false, e.getMessage().contains('已超期借用备品过多，不能提交备品借出申请。备品借出申请：' + rentalApply.name));
            }

            System.Test.stopTest();
        }
    }

    // 测试修理有效申请
    // static testMethod void myUnitTestRepair() {
    //     // システム管理者
    //     User user = new User(Test_staff__c = true);
    //     user.LastName = '_サンブリッジ';
    //     user.FirstName = 'う';
    //     user.Alias = 'う';
    //     user.Email = 'olympusTest03@sunbridge.com';
    //     user.Username = 'olympusTest03@sunbridge.com';
    //     user.CommunityNickname = 'う';
    //     user.IsActive = true;
    //     user.EmailEncodingKey = 'ISO-2022-JP';
    //     user.TimeZoneSidKey = 'Asia/Tokyo';
    //     user.LocaleSidKey = 'ja_JP';
    //     user.LanguageLocaleKey = 'ja';
    //     user.ProfileId = System.Label.ProfileId_SystemAdmin;
    //     user.Job_Category__c = '销售推广';
    //     user.Province__c = '上海市';
    //     user.Dept__c='医疗华北营业本部';
    //     user.Use_Start_Date__c = Date.today().addMonths(-6);
    //     user.SalesManager__c = UserInfo.getUserId();
    //     user.BuchangApprovalManagerSales__c = UserInfo.getUserId();
    //     user.JingliApprovalManager__c = UserInfo.getUserId();
    //     user.BuchangApprovalManager__c = UserInfo.getUserId();
    //     user.ZongjianApprovalManager__c = UserInfo.getUserId();
    //     user.JingliEquipmentManager__c = UserInfo.getUserId();
    //     user.Buzhang_Equipment_Manager__c = UserInfo.getUserId();
    //     System.runAs(user) {
    //         StaticParameter.rentalApplyIsRunning = true;
    //         StaticParameter.EscapeNFM001AgencyContractTrigger = true;
    //         ControllerUtil.EscapeNFM001Trigger = true;
    //         // 病院を作る
    //         Account hospital = new Account();
    //         hospital.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'HP'].id;
    //         hospital.Name = 'test hospital';
    //         insert hospital;

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

    //         // 診療科を作る
    //         Account dep = new Account();
    //         dep.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'Department_GI'].id;
    //         dep.Name = 'test dep';
    //         dep.ParentId = strategicDep[0].Id;
    //         dep.Department_Class__c = strategicDep[0].Id;
    //         dep.Hospital__c = hospital.Id;
    //         insert dep;

    //         //联系人
    //         Contact core = new Contact(email = 'jplumber@salesforce.com',
    //                                    firstname = 'Joe',
    //                                    lastname = 'Plumber',
    //                                    accountid = dep.id);
    //         insert core;

    //         // 製品を作る
    //         Product2 productA = new Product2( Name = 'テスト商品',
    //                                           Fixture_Model_No__c = 'n01');
    //         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[0].Id;
    //         asset.Hospital__c = hospital.Id;
    //         asset.SerialNumber = 'testserial';
    //         insert asset;

    //         Fixture_Set__c fixtures1 = new Fixture_Set__c();
    //         fixtures1.Name = 'set1';
    //         fixtures1.Loaner_name__c = 'name1';
    //         insert new Fixture_Set__c[] {fixtures1};

    //         Fixture_Set_Detail__c fsd1 = new Fixture_Set_Detail__c();
    //         fsd1.Product2__c = productA.Id;
    //         fsd1.Fixture_Set__c = fixtures1.Id;
    //         fsd1.Is_Body__c = true;
    //         fsd1.Is_Optional__c = false;
    //         fsd1.UniqueKey__c = fixtures1.Id + ':' + productA.Id;
    //         fsd1.SortInt__c = 1;

    //         insert new Fixture_Set_Detail__c[] {fsd1};


    //         // 修理做成
    //         Repair__c repair01 = new Repair__c();
    //         repair01.Account__c = dep.Id;
    //         repair01.Department_Class__c = strategicDep[0].Id;
    //         repair01.Hospital__c = hospital.Id;
    //         repair01.Delivered_Product__c = asset.Id;
    //         repair01.SERVICE_CONTRACT_JUDEGE_DAY__C = Date.today().addDays(0);  // 维修合同判断日がサービス契約の中間辺りの日付
    //         insert repair01;

    //         Rental_Apply__c ra = new Rental_Apply__c();
    //         ra.Name = 'test';
    //         ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
    //         ra.Request_shipping_day__c = Date.today().addDays(3);
    //         ra.Hope_Lonaer_date_Num__c = 1;
    //         ra.Request_return_day__c = Date.today().addDays(8);
    //         ra.Person_In_Charge__c = user.Id;
    //         ra.applyUser__c = user.Id;
    //         ra.SalesManager__c = user.Id;
    //         ra.Repair__c = repair01.Id;
    //         ra.Demo_purpose1__c = '其他';
    //         ra.Demo_purpose2__c = '其他';
    //         ra.Account__c = dep.Id;
    //         ra.Strategic_dept__c = dep.Id;
    //         ra.Hospital__c = hospital.Id;
    //         ra.Loaner_medical_Staff__c = core.Id;
    //         ra.Phone_number__c = '12222222222';
    //         insert ra;

    //         Rental_Apply_Equipment_Set__c es1 = new Rental_Apply_Equipment_Set__c();
    //         es1.Rental_Apply__c = ra.Id;
    //         es1.Fixture_Set__c = fixtures1.Id;
    //         es1.IndexFromUniqueKey__c = 1;
    //         es1.UniqueKey__c = '1:' + fixtures1.Id + ':1';

    //         insert new Rental_Apply_Equipment_Set__c[] {es1};

    //         //创建借出配套明细
    //         Rental_Apply_Equipment_Set_Detail__c esd1 = new Rental_Apply_Equipment_Set_Detail__c();
    //         esd1.Rental_Apply__c = ra.Id;
    //         esd1.Fixture_Set_Detail__c = fsd1.Id;
    //         esd1.Rental_Num__c = 1;
    //         esd1.Queue_Number__c = 0;
    //         esd1.Rental_Apply_Equipment_Set__c = es1.Id;
    //         esd1.Salesdepartment_before__c = '1.华北营业本部';
    //         esd1.Internal_asset_location_before__c = '北京 备品中心';
    //         esd1.Product_category_text__c = 'GI';
    //         esd1.Equipment_Type_text__c = '产品试用';
    //         esd1.IndexFromUniqueKey__c = 1;
    //         esd1.UniqueKey__c = '1:' + es1.Id + ':' + fsd1.Id + ':1';
    //         esd1.Is_Body__c = true;
    //         insert esd1;
    //         System.Test.startTest();
    //         Repair__c repair = [SELECT ID, Status1__c FROM Repair__c WHERE Id = :repair01.Id];
    //         System.assertEquals(FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal()), repair.Status1__c);

    //         // 没有明细的申请书状态没法变成填写完毕
    //         ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Tian_Xie_Wan_Bi.ordinal());
    //         update ra;
    //         Rental_Apply__c rental_Apply =  [SELECT Id, Status__c FROM Rental_Apply__c
    //                                          WHERE Id = :ra.Id];
    //         // TODO OCSM_BP3-187 assert失败 先注释掉 start                        
    //         //System.assertEquals(FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Tian_Xie_Wan_Bi.ordinal()), rental_Apply.Status__c);
    //         // TODO OCSM_BP3-187 assert失败 先注释掉 end

    //         repair = [SELECT ID, Effective_RentalApply_No__c , Offer_Rental__c, Status1__c FROM Repair__c WHERE Id = :repair01.Id];
    //         System.assertEquals(FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal()), repair.Status1__c);
    //         // System.assertEquals(1, repair.Effective_RentalApply_No__c);
    //         //System.assertEquals(true, repair.Offer_Rental__c);

    //         ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
    //         update ra;
    //         // 有明细参照的申请书不能无法
    //         delete esd1;
    //         delete es1;
    //         delete ra;

    //         repair = [SELECT ID, Effective_RentalApply_No__c , Offer_Rental__c FROM Repair__c WHERE Id = :repair01.Id];
    //         System.assertEquals(0, repair.Effective_RentalApply_No__c);
    //         System.assertEquals(false, repair.Offer_Rental__c);

    //         System.Test.stopTest();
    //     }
    // }

    // 测试EquipmentRentalBlackList_ChangeOwner_Threshold
    static testMethod void myUnitTestChangeOwnerThreshold() {
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001Trigger = true;
        // システム管理者
        User user = new User(Test_staff__c = true);
        user.LastName = '_サンブリッジ';
        user.FirstName = 'う';
        user.Alias = 'う';
        user.Email = 'olympusTest03@sunbridge.com';
        user.Username = 'olympusTest03@sunbridge.com';
        user.CommunityNickname = 'う';
        user.IsActive = true;
        user.EmailEncodingKey = 'ISO-2022-JP';
        user.TimeZoneSidKey = 'Asia/Tokyo';
        user.LocaleSidKey = 'ja_JP';
        user.LanguageLocaleKey = 'ja';
        user.ProfileId = System.Label.ProfileId_SystemAdmin;
        user.Job_Category__c = '销售推广';
        user.Province__c = '上海市';
        user.Dept__c='医疗华北营业本部';
        user.Use_Start_Date__c = Date.today().addMonths(-6);
        user.SalesManager__c = UserInfo.getUserId();
        user.BuchangApprovalManagerSales__c = UserInfo.getUserId();
        user.JingliApprovalManager__c = UserInfo.getUserId();
        user.BuchangApprovalManager__c = UserInfo.getUserId();
        user.ZongjianApprovalManager__c = UserInfo.getUserId();

        // MIXED_DML_OPERATION, DML operation on setup object is not permitted Error
        System.runAs(new User(Id = Userinfo.getUserId())) {
            user.Foul_Points__c = Integer.valueOf(System.Label.EquipmentRentalBlackList_ChangeOwner_Threshold);
            insert user;
            List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '病院'];
            if (rectCo.size() == 0) {
                return ;
            }
            List<RecordType> rectSct = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '戦略科室分類 呼吸科'];
            if (rectSct.size() == 0) {
                return;
            }
            List<RecordType> rectDpt = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN ('診療科 消化科', '診療科 呼吸科') order by Name desc];
            if (rectDpt.size() == 0) {
                return;
            }

            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;

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

            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;

            //联系人
            Contact core = new Contact(email = 'jplumber@salesforce.com',
                                       firstname = 'Joe',
                                       lastname = 'Plumber',
                                       accountid = dep.id);
            insert core;

            // 製品を作る
            Product2 productA = new Product2( Name = 'テスト商品',
                                              Fixture_Model_No__c = 'n01');
            insert productA;

            // 納入機器を作成する
            Asset asset = new Asset();
            asset.Name = 'テスト機器';
            asset.AccountId = dep.Id;
            asset.Department_Class__c = strategicDep[0].Id;
            asset.Hospital__c = hospital.Id;
            asset.SerialNumber = 'testserial';
            insert asset;

            Fixture_Set__c fixtures1 = new Fixture_Set__c();
            fixtures1.Name = 'set1';
            fixtures1.Loaner_name__c = 'name1';
            insert new Fixture_Set__c[] {fixtures1};

            Fixture_Set_Detail__c fsd1 = new Fixture_Set_Detail__c();
            fsd1.Product2__c = productA.Id;
            fsd1.Fixture_Set__c = fixtures1.Id;
            fsd1.Is_Body__c = true;
            fsd1.Is_Optional__c = false;
            fsd1.UniqueKey__c = fixtures1.Id + ':' + productA.Id;
            fsd1.SortInt__c = 1;

            insert new Fixture_Set_Detail__c[] {fsd1};

            Rental_Apply__c ra = new Rental_Apply__c();
            ra.Name = 'test';
            ra.applyUser__c = user.Id;
            ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
            ra.Request_shipping_day__c = Date.today().addDays(3);
            ra.Hope_Lonaer_date_Num__c = 1;
            ra.Request_return_day__c = Date.today().addDays(8);
            ra.Demo_purpose1__c = '其他';
            ra.Demo_purpose2__c = '其他';
            ra.Account__c = dep.Id;
            ra.Strategic_dept__c = dep.Id;
            ra.Hospital__c = hospital.Id;
            ra.Loaner_medical_Staff__c = core.Id;
            ra.Phone_number__c = '12222222222';
            ra.Person_In_Charge__c = user.Id;
            insert ra;

            Rental_Apply_Equipment_Set__c es1 = new Rental_Apply_Equipment_Set__c();
            es1.Rental_Apply__c = ra.Id;
            es1.Fixture_Set__c = fixtures1.Id;
            es1.IndexFromUniqueKey__c = 1;
            es1.UniqueKey__c = '1:' + fixtures1.Id + ':1';

            insert new Rental_Apply_Equipment_Set__c[] {es1};

            //创建借出配套明细
            Rental_Apply_Equipment_Set_Detail__c esd1 = new Rental_Apply_Equipment_Set_Detail__c();
            esd1.Rental_Apply__c = ra.Id;
            esd1.Fixture_Set_Detail__c = fsd1.Id;
            esd1.Rental_Num__c = 1;
            esd1.Queue_Number__c = 0;
            esd1.Rental_Apply_Equipment_Set__c = es1.Id;
            esd1.Salesdepartment_before__c = '1.华北营业本部';
            esd1.Internal_asset_location_before__c = '北京 备品中心';
            esd1.Product_category_text__c = 'GI';
            esd1.Equipment_Type_text__c = '产品试用';
            esd1.IndexFromUniqueKey__c = 1;
            esd1.UniqueKey__c = '1:' + es1.Id + ':' + fsd1.Id + ':1';
            esd1.Is_Body__c = true;
            insert esd1;

            System.Test.startTest();

            // 没有明细的申请书状态没法变成填写完毕
            try {
                ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Tian_Xie_Wan_Bi.ordinal());
                ra.Person_In_Charge__c = user.Id;
                update ra;
                // throw new ControllerUtil.myException('没有发生，黑名单用户不能提交申请');
            } catch (Exception e) {
                ra = [SELECT Name
                               FROM Rental_Apply__c
                               WHERE Id = :ra.Id];
                // TODO OCSM_BP3-187 assert失败 先注释掉 start
                //System.assertEquals(true, e.getMessage().contains('已超期借用备品过多，不能提交备品借出申请。备品借出申请'));
                // TODO OCSM_BP3-187 assert失败 先注释掉 end
            }
            System.Test.stopTest();
        }
    }

    // 去掉"犯规点数超过Max的时候不能申请"的限制条件。【EquipmentRentalBlackList_ChangeOwner_Threshold为999999999的时候, 事实上就是不check 】
    static testMethod void testBlackApplyNoError() {
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001Trigger = true;
        // システム管理者
        User user = new User(Test_staff__c = true);
        user.LastName = '_サンブリッジ';
        user.FirstName = 'う';
        user.Alias = 'う';
        user.Email = 'olympusTest03@sunbridge.com';
        user.Username = 'olympusTest03@sunbridge.com';
        user.CommunityNickname = 'う';
        user.IsActive = true;
        user.EmailEncodingKey = 'ISO-2022-JP';
        user.TimeZoneSidKey = 'Asia/Tokyo';
        user.LocaleSidKey = 'ja_JP';
        user.LanguageLocaleKey = 'ja';
        user.ProfileId = System.Label.ProfileId_SystemAdmin;
        user.Job_Category__c = '销售推广';
        user.Province__c = '上海市';
        user.Dept__c='医疗华北营业本部';
        user.Use_Start_Date__c = Date.today().addMonths(-6);
        user.SalesManager__c = UserInfo.getUserId();
        user.BuchangApprovalManagerSales__c = UserInfo.getUserId();
        user.JingliApprovalManager__c = UserInfo.getUserId();
        user.BuchangApprovalManager__c = UserInfo.getUserId();
        user.ZongjianApprovalManager__c = UserInfo.getUserId();

        // MIXED_DML_OPERATION, DML operation on setup object is not permitted Error
        System.runAs(new User(Id = Userinfo.getUserId())) {
            user.Foul_Points__c = Integer.valueOf(System.Label.EquipmentRentalBlackList_ChangeOwner_Threshold)-1;
            insert user;
            List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '病院'];
            if (rectCo.size() == 0) {
                return ;
            }
            List<RecordType> rectSct = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '戦略科室分類 呼吸科'];
            if (rectSct.size() == 0) {
                return;
            }
            List<RecordType> rectDpt = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN ('診療科 消化科', '診療科 呼吸科') order by Name desc];
            if (rectDpt.size() == 0) {
                return;
            }

            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;

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

            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;

            //联系人
            Contact core = new Contact(email = 'jplumber@salesforce.com',
                                       firstname = 'Joe',
                                       lastname = 'Plumber',
                                       accountid = dep.id);
            insert core;

            // 製品を作る
            Product2 productA = new Product2( Name = 'テスト商品',
                                              Fixture_Model_No__c = 'n01');
            insert productA;

            // 納入機器を作成する
            Asset asset = new Asset();
            asset.Name = 'テスト機器';
            asset.AccountId = dep.Id;
            asset.Department_Class__c = strategicDep[0].Id;
            asset.Hospital__c = hospital.Id;
            asset.SerialNumber = 'testserial';
            insert asset;

            Fixture_Set__c fixtures1 = new Fixture_Set__c();
            fixtures1.Name = 'set1';
            fixtures1.Loaner_name__c = 'name1';
            insert new Fixture_Set__c[] {fixtures1};

            Fixture_Set_Detail__c fsd1 = new Fixture_Set_Detail__c();
            fsd1.Product2__c = productA.Id;
            fsd1.Fixture_Set__c = fixtures1.Id;
            fsd1.Is_Body__c = true;
            fsd1.Is_Optional__c = false;
            fsd1.UniqueKey__c = fixtures1.Id + ':' + productA.Id;
            fsd1.SortInt__c = 1;

            insert new Fixture_Set_Detail__c[] {fsd1};

            Rental_Apply__c ra = new Rental_Apply__c();
            ra.Name = 'test';
            ra.applyUser__c = user.Id;
            ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
            ra.Request_shipping_day__c = Date.today().addDays(3);
            ra.Hope_Lonaer_date_Num__c = 1;
            ra.Request_return_day__c = Date.today().addDays(8);
            ra.Demo_purpose1__c = '其他';
            ra.Demo_purpose2__c = '其他';
            ra.Account__c = dep.Id;
            ra.Strategic_dept__c = dep.Id;
            ra.Hospital__c = hospital.Id;
            ra.Loaner_medical_Staff__c = core.Id;
            ra.Phone_number__c = '12222222222';
            ra.Person_In_Charge__c = user.Id;
            insert ra;



            Rental_Apply_Equipment_Set__c es1 = new Rental_Apply_Equipment_Set__c();
            es1.Rental_Apply__c = ra.Id;
            es1.Fixture_Set__c = fixtures1.Id;
            es1.IndexFromUniqueKey__c = 1;
            es1.UniqueKey__c = '1:' + fixtures1.Id + ':1';

            insert new Rental_Apply_Equipment_Set__c[] {es1};

            //创建借出配套明细
            Rental_Apply_Equipment_Set_Detail__c esd1 = new Rental_Apply_Equipment_Set_Detail__c();
            esd1.Rental_Apply__c = ra.Id;
            esd1.Fixture_Set_Detail__c = fsd1.Id;
            esd1.Rental_Num__c = 1;
            esd1.Queue_Number__c = 0;
            esd1.Rental_Apply_Equipment_Set__c = es1.Id;
            esd1.Salesdepartment_before__c = '1.华北营业本部';
            esd1.Internal_asset_location_before__c = '北京 备品中心';
            esd1.Product_category_text__c = 'GI';
            esd1.Equipment_Type_text__c = '产品试用';
            esd1.IndexFromUniqueKey__c = 1;
            esd1.UniqueKey__c = '1:' + es1.Id + ':' + fsd1.Id + ':1';
            esd1.Is_Body__c = true;
            insert esd1;
           
            System.Test.startTest();

            // 没有明细的申请书状态没法变成填写完毕
            try {
                ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Tian_Xie_Wan_Bi.ordinal());
                ra.OwnerId = 'test';
                update ra;
                System.assertEquals(FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Tian_Xie_Wan_Bi.ordinal()), ra.Status__c);
                System.assertEquals(user.Id, ra.OwnerId);
                throw new ControllerUtil.myException('没有发生，黑名单用户不能提交申请');
            } catch (Exception e) {
                ra = [SELECT Name
                               FROM Rental_Apply__c
                               WHERE Id = :ra.Id];
                System.assertEquals(false, e.getMessage().contains('已超期借用备品过多，不能提交备品借出申请。备品借出申请'));
            }
            System.Test.stopTest();
        }
    }
    static testMethod void test22() {
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001Trigger = true;
        // システム管理者
        User user = new User(Test_staff__c = true);
        user.LastName = '_サンブリッジ';
        user.FirstName = 'う';
        user.Alias = 'う';
        user.Email = 'olympusTest03@sunbridge.com';
        user.Username = 'olympusTest03@sunbridge.com';
        user.CommunityNickname = 'う';
        user.IsActive = true;
        user.EmailEncodingKey = 'ISO-2022-JP';
        user.TimeZoneSidKey = 'Asia/Tokyo';
        user.LocaleSidKey = 'ja_JP';
        user.LanguageLocaleKey = 'ja';
        user.ProfileId = System.Label.ProfileId_SystemAdmin;
        user.Job_Category__c = '销售推广';
        user.Province__c = '上海市';
        user.Dept__c='医疗华北营业本部';
        user.Use_Start_Date__c = Date.today().addMonths(-6);
        user.SalesManager__c = UserInfo.getUserId();
        user.BuchangApprovalManagerSales__c = UserInfo.getUserId();
        user.JingliApprovalManager__c = UserInfo.getUserId();
        user.BuchangApprovalManager__c = UserInfo.getUserId();
        user.ZongjianApprovalManager__c = UserInfo.getUserId();

        // MIXED_DML_OPERATION, DML operation on setup object is not permitted Error
        System.runAs(new User(Id = Userinfo.getUserId())) {
            user.Foul_Points__c = Integer.valueOf(System.Label.EquipmentRentalBlackList_ChangeOwner_Threshold)-1;
            insert user;
            List<RecordType> rectCo = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '病院'];
            if (rectCo.size() == 0) {
                return ;
            }
            List<RecordType> rectSct = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '戦略科室分類 呼吸科'];
            if (rectSct.size() == 0) {
                return;
            }
            List<RecordType> rectDpt = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN ('診療科 消化科', '診療科 呼吸科') order by Name desc];
            if (rectDpt.size() == 0) {
                return;
            }

            // 病院を作る
            Account hospital = new Account();
            hospital.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'HP'].id;
            hospital.Name = 'test hospital';
            insert hospital;

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

            // 診療科を作る
            Account dep = new Account();
            dep.recordtypeId = [Select Id FROM RecordType WHERE DeveloperName = 'Department_GI'].id;
            dep.Name = 'test dep';
            dep.ParentId = strategicDep[0].Id;
            dep.Department_Class__c = strategicDep[0].Id;
            dep.Hospital__c = hospital.Id;
            insert dep;

            //联系人
            Contact core = new Contact(email = 'jplumber@salesforce.com',
                                       firstname = 'Joe',
                                       lastname = 'Plumber',
                                       accountid = dep.id);
            insert core;

            // 製品を作る
            Product2 productA = new Product2( Name = 'テスト商品',
                                              Fixture_Model_No__c = 'n01');
            insert productA;

            // 納入機器を作成する
            Asset asset = new Asset();
            asset.Name = 'テスト機器';
            asset.AccountId = dep.Id;
            asset.Department_Class__c = strategicDep[0].Id;
            asset.Hospital__c = hospital.Id;
            asset.SerialNumber = 'testserial';
            insert asset;

            Fixture_Set__c fixtures1 = new Fixture_Set__c();
            fixtures1.Name = 'set1';
            fixtures1.Loaner_name__c = 'name1';
            insert new Fixture_Set__c[] {fixtures1};

            Fixture_Set_Detail__c fsd1 = new Fixture_Set_Detail__c();
            fsd1.Product2__c = productA.Id;
            fsd1.Fixture_Set__c = fixtures1.Id;
            fsd1.Is_Body__c = true;
            fsd1.Is_Optional__c = false;
            fsd1.UniqueKey__c = fixtures1.Id + ':' + productA.Id;
            fsd1.SortInt__c = 1;

            insert new Fixture_Set_Detail__c[] {fsd1};

            Rental_Apply__c ra = new Rental_Apply__c();
            ra.Name = 'test';
            ra.applyUser__c = user.Id;
            ra.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
            ra.Request_shipping_day__c = Date.today().addDays(3);
            ra.Hope_Lonaer_date_Num__c = 1;
            ra.Request_return_day__c = Date.today().addDays(8);
            ra.Demo_purpose1__c = '其他';
            ra.Demo_purpose2__c = '其他';
            ra.Account__c = dep.Id;
            ra.Strategic_dept__c = dep.Id;
            ra.Hospital__c = hospital.Id;
            ra.Loaner_medical_Staff__c = core.Id;
            ra.Phone_number__c = '12222222222';
            ra.Person_In_Charge__c = user.Id;
            insert ra;



            Rental_Apply_Equipment_Set__c es1 = new Rental_Apply_Equipment_Set__c();
            es1.Rental_Apply__c = ra.Id;
            es1.Fixture_Set__c = fixtures1.Id;
            es1.IndexFromUniqueKey__c = 1;
            es1.UniqueKey__c = '1:' + fixtures1.Id + ':1';

            insert new Rental_Apply_Equipment_Set__c[] {es1};

            //创建借出配套明细
            Rental_Apply_Equipment_Set_Detail__c esd1 = new Rental_Apply_Equipment_Set_Detail__c();
            esd1.Rental_Apply__c = ra.Id;
            esd1.Fixture_Set_Detail__c = fsd1.Id;
            esd1.Rental_Num__c = 1;
            esd1.Queue_Number__c = 0;
            esd1.Rental_Apply_Equipment_Set__c = es1.Id;
            esd1.Salesdepartment_before__c = '1.华北营业本部';
            esd1.Internal_asset_location_before__c = '北京 备品中心';
            esd1.Product_category_text__c = 'GI';
            esd1.Equipment_Type_text__c = '产品试用';
            esd1.IndexFromUniqueKey__c = 1;
            esd1.UniqueKey__c = '1:' + es1.Id + ':' + fsd1.Id + ':1';
            esd1.Is_Body__c = true;
            insert esd1;

            System.Test.startTest();

            Rental_Apply__c ra1 = new Rental_Apply__c();
            ra1.Name = 'test123';
            ra1.applyUser__c = user.Id;
            ra1.Status__c = FixtureUtil.raStatusMap.get(FixtureUtil.RaStatus.Cao_An_Zhong.ordinal());
            ra1.Request_shipping_day__c = Date.today().addDays(3);
            ra1.Hope_Lonaer_date_Num__c = 1;
            ra1.Request_return_day__c = Date.today().addDays(8);
            ra1.Demo_purpose1__c = '其他';
            ra1.Demo_purpose2__c = '其他';
            ra1.Account__c = dep.Id;
            ra1.Strategic_dept__c = dep.Id;
            ra1.Hospital__c = hospital.Id;
            ra1.Loaner_medical_Staff__c = core.Id;
            ra1.Phone_number__c = '12222222222';
            ra1.Zsq_Rental_Apply__c = ra.id;
            ra1.Person_In_Charge__c = user.Id;
            insert ra1;
            
            System.Test.stopTest();
        }
    }
}