@isTest
private class OFSInsReportLayoutControllerTest {
    @TestSetup
    static void makeData(){
        TestDataUtility.CreatePIPolicyConfiguration('Inspection_Report__c');
        TestDataUtility.CreatePIPolicyConfiguration('Contact');
    }
    public class TestRepo {
        public final Integer ASSETMAX = 8;
        public OFSInsReportLayout__c layout { get; private set; }
        public Account hp { get; private set; }
        public Account depart { get; private set; }
        public Inspection_Report__c ir { get; private set; }
        public List<Asset> assets { get; private set; }
        public Event evnt { get; private set; }
        TestRepo() {
            assets = new List<Asset>();
            createLayout();
            createHospital();
            createEvent();
        }
        public void createEvent() {
            evnt = new Event();
            evnt.StartDateTime = Datetime.now().addDays(1);
            evnt.EndDateTime = Datetime.now().addDays(1).addHours(1);
            insert evnt;
        }
        public void createHospital() {
            hp = new Account();
            hp.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
            hp.Name = 'test hospital';
            insert hp;
            Account section = [Select Id from Account where RecordType.DeveloperName = 'Department_Class_GI' and ParentId =: hp.Id];
            depart = new Account();
            depart.RecordTypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_GI'].id;
            depart.Name         = '*';
            depart.Department_Name__c  = 'OFSInsReportLayoutControllerTestDepart';
            depart.ParentId            = section.Id;
            depart.Department_Class__c = section.Id;
            depart.Hospital__c         = hp.Id;
            insert depart;
        }
        public void createInspectionReport(Date inspectionDate) {
            //Profile prof = [select Id from Profile where Name ='901_经销商社区普通权限_2重验证'];
            User loginUser = [Select Id, Alias, Province__c from User where Id =: UserInfo.getUserId()];
            loginUser.Job_Category__c = '销售服务';
            //update loginUser;
            loginUser = [Select Id, Alias, Province__c from User where Job_Category__c = '销售服务' limit 1];

            ir = new Inspection_Report__c(Name = '*', Inspection_Date__c = inspectionDate, Hospital__c = hp.Id);
            ir.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Inspection_Report__c' and DeveloperName = 'EndoscopeSystem'].id;
            ir.Hospital__c = hp.Id;
            ir.Reporter__c = loginUser.Id;
            ir.Manual_Department__c = 'test';
            ir.Inspection_StartTime__c = Datetime.now();
            ir.Inspection_EndTime__c = Datetime.now().addHours(1);
            ir.Phone__c = '11112222';
            ir.Responsible_Person__c = 'test';
            ir.Next_StartTime__c = Datetime.now().addDays(1);
            ir.Next_EndTime__c = Datetime.now().addDays(1).addHours(1);
            ir.NextInspection_Day__c = Date.today().addDays(1);
            ir.Next_StartHour_Page__c = '09';
            ir.Next_StartMinute_Page__c = '00';
            ir.Next_EndHour_Page__c = '10';
            ir.Next_EndMinute_Page__c = '00';
            ir.Event_ID__c = evnt.Id;
            insert ir;
        }
        private void createLayout() {
            layout = new OFSInsReportLayout__c();
            layout.Name = 'test';
            layout.recordType_devName__c = 'EndoscopeSystem';
            layout.section1__c = '{"id":"001","title":"基本信息","column":"2","showHeader":"true"}';
            layout.field1__c = '{"sectionId":"001", "api":{"columns":["Name","Hospital__c", "Department__c"], "lables":["点检检测单号", "医院", "科室"]}, "lable":""}';
            
            layout.section2__c = '{"id":"002","title":"信息","column":"2","showHeader":"false"}';
            layout.field2__c = '{"sectionId":"002","api":"Hospital__c"}';
            layout.field3__c = '{"sectionId":"002","api":"Manual_Department__c","isInput":"true"}';
            layout.field4__c = '{"sectionId":"002","api":"Status__c","right":"true","isInput":"true"}';
            layout.field5__c = '{"sectionId":"002","api":"NextInspection_Day__c"}';
            layout.field6__c = '{"sectionId":"002","api":"Inspection_Date__c"}';
            
            insert layout;
        }
        private Asset createAsset(String name, String serialNo) {
            Asset asset = new Asset();
            asset.Name = name;
            asset.AccountId = depart.Id;
            asset.Hospital__c = hp.Id;
            asset.SerialNumber = serialNo;
            asset.InstallDate = Date.today();
            return asset;
        }
        public void initAssets() {
            for (Integer i= 0; i < ASSETMAX; i++) {
                assets.add(createAsset('testAsset'+i, '0000'+i));
            }
            insert assets;
        }
        public String getAssetIds(Integer num) {
            String irStr = '';
            for (Integer i = 0; i < num; i++) {
                irStr += assets[i].Id + '_';
            }
            irStr = irStr.removeEnd('_');
            return irStr;
        }
        
        public void sqlIr() {
            this.ir = [select Id, Name, Status__c, Inspection_Date__c, Reporter__c from Inspection_Report__c where Id =: ir.Id];
        }
    }
    
    //点検報告書を新規、保存、テスト
    @isTest
    static void CreateUnitTest() {
        // TO DO: implement unit test
        Test.startTest();
        TestRepo repo = new TestRepo();
        repo.createInspectionReport(null);
        // 2021-05-13 mzy SFDC点检报告逻辑更新
        repo.initAssets();
        repo.sqlIr();
        Apexpages.currentPage().getParameters().put('name', repo.ir.name);
        // 2021-05-13 mzy SFDC点检报告逻辑更新
        Apexpages.currentPage().getParameters().put('hpId', repo.hp.Id);
        Apexpages.currentPage().getParameters().put('rt', 'EndoscopeSystem');
        OFSInsReportLayoutController controller = new OFSInsReportLayoutController();
        
        //init
        controller.init();
        system.assertNotEquals(null, controller.ir.Name);
        system.assertEquals('草案中', controller.ir.Status__c);
        system.assertEquals(repo.ASSETMAX, controller.unCheckedInfoList.size());
        
        //Assetをチェックして、明細を作る
        controller.unCheckedInfoList[0].rec_checkBox_c = true;
        controller.exchangeAsset();
        system.assertEquals(repo.ASSETMAX-1, controller.unCheckedInfoList.size());
        system.assertEquals(11, controller.checkedInfoList.size());
        
        controller.saveBtn();
        List<Inspection_Report__c> irs = [select id, Name from Inspection_Report__c where Id =:controller.ir.Id];
        system.assertEquals(1, irs.size());
        List<Inspection_Item__c> ahList = [Select Id, Name, AssetId__c, Inspection_ReportId__c from Inspection_Item__c  Where Inspection_ReportId__c = :controller.ir.Id order by Name];
        system.assertEquals(1, ahList.size());
        Test.stopTest();
    }
    
    //編集テスト
    @isTest
    static void EditUnitTest() {
        Test.startTest();
        TestRepo repo = new TestRepo();
        repo.createInspectionReport(null);
        repo.initAssets();
        repo.sqlIr();
        Apexpages.currentPage().getParameters().put('id', repo.ir.Id);
        Apexpages.currentPage().getParameters().put('name', repo.ir.name);
        Apexpages.currentPage().getParameters().put('asset_ids', repo.getAssetIds(5));
        OFSInsReportLayoutController controller = new OFSInsReportLayoutController();
        
        //init
        controller.init();
        system.assertEquals(repo.ir.name, controller.ir.Name);
        system.assertEquals(repo.ir.Status__c, controller.ir.Status__c);
        system.assertEquals(repo.ASSETMAX-5, controller.unCheckedInfoList.size());
        
        //Assetをチェックして、明細を作る
        controller.unCheckedInfoList[0].rec_checkBox_c = true;
        controller.exchangeAsset();
        system.assertEquals(repo.ASSETMAX-6, controller.unCheckedInfoList.size());
        system.assertEquals(16, controller.checkedInfoList.size());
        
        controller.saveBtn();

        //system.assertEquals(null,ApexPages.getMessages()[0].getDetail());
        //system.assertEquals('1', controller.ir.NextInspection_Day__c + '|' + controller.ir.Next_StartHour_Page__c + '|' + controller.ir.Next_StartMinute_Page__c + '|' + controller.ir.Next_EndHour_Page__c + '|' + controller.ir.Next_EndMinute_Page__c);

        list<Inspection_Report__c> irs = [select id, Name from Inspection_Report__c where Name =:controller.ir.Name];
        system.assertEquals(1, irs.size());
        
        List<Inspection_Item__c> ahList = [Select Id, Name, AssetId__c, Inspection_ReportId__c from Inspection_Item__c  Where Inspection_ReportId__c = :controller.ir.Id order by Name];
        system.assertEquals(6, ahList.size());

        Integer cnt1 = controller.productCount;
        Integer cnt2 = controller.productCount2;

        controller.text1 = 'S:SerialNumber';
        controller.cond1 = 'equals';
        controller.val1 = '00000';
        controller.searchBtn();
        controller.sortKey = '1';
        controller.sortTable();
        controller.showPDF();
        controller.submit();

        controller.DownPage();
        controller.UpPage();

        Test.stopTest();
    }
    
    // 点検履歴テスト
    @isTest
    static void OFSInsReportAssetHistoryControllerTest() {
        User loginUser = [Select Id, Alias, Province__c from User where Id =: UserInfo.getUserId()];
        loginUser.Job_Category__c = '销售服务';
        update loginUser;
        TestRepo repo = new TestRepo();
        repo.createInspectionReport(System.today());
        repo.initAssets();
        repo.sqlIr();
        // 明細を追加、点検履歴が作れないことを確認
        List<Inspection_Item__c> irItems = new List<Inspection_Item__c>();
        irItems.add(new Inspection_Item__c(Inspection_ReportId__c = repo.ir.Id,
            AssetId__c = repo.assets[0].Id,
            IsNormal__c = true,
            Diagnosis__c = 'Diagnosis1'
        ));
        irItems.add(new Inspection_Item__c(Inspection_ReportId__c = repo.ir.Id,
            AssetId__c = repo.assets[1].Id,
            IsNormal__c = false,
            Diagnosis__c = 'Diagnosis2'
        ));
        insert irItems;
        OFSInsReportAssetHistoryController.upsertInspection_Item(repo.ir, irItems);
        String insReportLike = '%' + repo.ir.Name + '%';
        List<AssetHistory__c> ahList = [Select Id from AssetHistory__c where Asset_Inspection_ExtID__c like :insReportLike];
        //system.assertEquals(0, ahList.size());
        
        // 填写完毕 後 にする、点検履歴が作れたことを確認
        repo.ir.status__c = '填写完毕';

        //deloitte-zhj 20231009 必填院方负责人 start
        Contact con = new Contact();
		con.LastName = 'lastname2';
		con.FirstName = 'firstname2';
		con.Email = 'olympustest033@sunbridge.com';
		con.MobilePhone = '99999999';
		con.Work_Location_manual__c = 'location2';
		con.Post_picklist__c = '部长';
		con.Job_Category_picklist__c = '销售推广';
		con.Hire_date_text__c = Date.today().addMonths(-6);
		con.Gender_text__c = '男';
		con.dept__c = '服务本部';
		con.Pregnant_Rest__c = true;
		insert con;
        repo.ir.Responsible_Person_F__c = con.Id; 
        //deloitte-zhj 20231009 必填院方负责人 end
        OFSInsReportAssetHistoryController.upsertInspection_Report(repo.ir);
        repo.sqlIr();
        OFSInsReportAssetHistoryController.upsertInspection_Item(repo.ir, irItems);
        ahList = [Select Id from AssetHistory__c where Asset_Inspection_ExtID__c like :insReportLike];
        //system.assertEquals(2, ahList.size());
        // １つ を削除対象にした場合
        OFSInsReportAssetHistoryController.deleteInspection_Item(repo.ir, new Inspection_Item__c[] {irItems[1]});
        ahList = [Select Id from AssetHistory__c where Asset_Inspection_ExtID__c like :insReportLike];
        //system.assertEquals(1, ahList.size());
        
        // 草案中 戻した場合、点検履歴が全部削除されず、次回同じ点検を提出する時、削除
        repo.ir.status__c = '草案中';
        OFSInsReportAssetHistoryController.upsertInspection_Report(repo.ir);
        repo.sqlIr();
        OFSInsReportAssetHistoryController.upsertInspection_Item(repo.ir, new Inspection_Item__c[] {irItems[0]});
        ahList = [Select Id from AssetHistory__c where Asset_Inspection_ExtID__c like :insReportLike];
        //system.assertEquals(1, ahList.size());
        //2021-06-15 mzy add end
        OFSInsReportAssetHistoryController.delAssetHistory();
        OFSInsReportAssetHistoryController.upsertAssetHistory(ahList);        
        OFSInsReportAssetHistoryController.upsertExtAssetHistory(ahList);
        //2021-06-15 mzy add end

    }

    //編集テスト wrong ID, right name
    @isTest
    static void EditUnitTest2() {
        // TO DO: implement unit test
        Test.startTest();
        TestRepo repo = new TestRepo();
        repo.createInspectionReport(null);
        
        repo.initAssets();
        repo.sqlIr();
        
        String wrongId = repo.ir.Id;
        wrongId = wrongId.substring(0, 14) + wrongId.substring(13, 14);
        Apexpages.currentPage().getParameters().put('id', wrongId);
        Apexpages.currentPage().getParameters().put('name', repo.ir.name);
        Apexpages.currentPage().getParameters().put('asset_ids', repo.getAssetIds(5));
        OFSInsReportLayoutController controller = new OFSInsReportLayoutController();
        
        //init
        controller.init();
/*        system.assertEquals(repo.ir.name, controller.ir.Name);
        system.assertEquals(repo.ir.Status__c, controller.ir.Status__c);
        system.assertEquals(repo.ASSETMAX-5, controller.unCheckedInfoList.size());
        
        //Assetをチェックして、明細を作る
        controller.unCheckedInfoList[0].rec_checkBox_c = true;
        controller.exchangeAsset();
        system.assertEquals(repo.ASSETMAX-6, controller.unCheckedInfoList.size());
        system.assertEquals(16, controller.checkedInfoList.size());
        
        controller.save();
        list<Inspection_Report__c> irs = [select id, Name from Inspection_Report__c where Name =:controller.ir.Name];
        system.assertEquals(1, irs.size());
        
        List<Inspection_Item__c> ahList = [Select Id, Name, AssetId__c, Inspection_ReportId__c from Inspection_Item__c  Where Inspection_ReportId__c = :controller.ir.Id order by Name];
        //system.assertEquals(6, ahList.size());*/
        Test.stopTest();
    }

    @isTest
    static void CreateUnitTest_ex1() {
        // TO DO: implement unit test
        Test.startTest();
        TestRepo repo = new TestRepo();
        repo.initAssets();
        Apexpages.currentPage().getParameters().put('hpId', repo.depart.Id);
        Apexpages.currentPage().getParameters().put('rt', 'EndoscopeSystem');
        OFSInsReportLayoutController controller = new OFSInsReportLayoutController();

        //init
        controller.init();
    }

    @isTest
    static void CreateUnitTest_ex2() {
        // TO DO: implement unit test
        Test.startTest();
        TestRepo repo = new TestRepo();
        repo.initAssets();
        Apexpages.currentPage().getParameters().put('hpId', repo.depart.ParentId);
        Apexpages.currentPage().getParameters().put('rt', 'EndoscopeSystem');
        OFSInsReportLayoutController controller = new OFSInsReportLayoutController();

        //init
        controller.init();
    }
    
    //add by rentx 20210708 start
    @isTest
    static void VMTest() {
        //创建一个维修合同
        Account company1 = new Account();
        company1.RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('HP').getRecordTypeId();
        company1.Name = '病院テスト1';
        List<Account> hps = new Account[]{company1};
        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 and RecordType_DeveloperName__c = 'Department_Class_BF'];
        StaticParameter.EscapeAccountTrigger = true;
        Account depart1 = new Account();
        depart1.RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Department_BF').getRecordTypeId();
        depart1.Name         = '*';
        depart1.Department_Name__c  = '診療科1';
        depart1.ParentId            = dc1s[0].Id;
        depart1.Department_Class__c = dc1s[0].Id;
        depart1.Hospital__c         = company1.Id;
        insert depart1;
        Account depart2 = new Account();
        depart2.RecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Department_BF').getRecordTypeId();
        depart2.Name         = '*';
        depart2.Department_Name__c  = '消化科1';
        depart2.ParentId            = dc1s[0].Id;
        depart2.Department_Class__c = dc1s[0].Id;
        depart2.Hospital__c         = company1.Id;
        insert depart2;
        StaticParameter.EscapeSyncProduct2Trigger = true;
        Product2 prd1 = new Product2();
        prd1.ProductCode_Ext__c     = 'HistoryPrd1';
        prd1.ProductCode            = 'HistoryPrd1';
        prd1.Repair_Product_Code__c = 'HistoryPrd1_RP';
        prd1.Name                   = 'HistoryPrd1';
        prd1.Manual_Entry__c        = false;
        prd1.Extend_new_product_gurantee__c = true;
        prd1.Extend_Gurantee_Start__c = Date.today().addDays(-60);
        prd1.Extend_Gurantee_End__c = Date.today().addDays(60);
        insert prd1;

        Oly_TriggerHandler.bypass('AssetHandler');

        Asset ast = new Asset();
        ast.RecordTypeId = Schema.SObjectType.Asset.getRecordTypeInfosByDeveloperName().get('HPAsset').getRecordTypeId();
        ast.SerialNumber = 'abcdefg';
        ast.Name = '测试资产1';
        ast.AccountId              = depart1.Id;
        ast.Department_Class__c    = dc1s[0].Id;
        ast.Hospital__c            = company1.Id;
        ast.Product2Id             = prd1.Id;
        ast.Guarantee_period_for_products__c = Date.today().addDays(30);
        ast.InstallDate                      = Date.today().addDays(-3);
        ast.Manage_type__c = '个体管理';
        // ast.FirstApproveDate_old__c = Date.today().addDays(-30);
        insert ast;
        Maintenance_Contract__c contract = new Maintenance_Contract__c();
        contract.Name = 'tect contract';
        contract.status__c ='契約';
        contract.Maintenance_Contract_No__c = 'Kami_Contract_No';
        contract.Contract_Conclusion_Date__c = Date.today();
        contract.Hospital__c = company1.Id;
        contract.Department_Class__c = dc1s[0].Id;
        contract.Department__c = depart1.Id;
        contract.Contract_Start_Date__c = Date.today().addDays( -10);   // 10日前
        contract.Contract_End_Date__c = Date.today().addDays( 5);       // 5日後
        contract.SalesOfficeCode_selection__c = '北京RC';
        contract.RecordTypeId = Schema.SObjectType.Maintenance_Contract__c.getRecordTypeInfosByDeveloperName().get('VM_Contract').getRecordTypeId();
        insert contract;

        // 创建一个维修合同/保有设备
        // 中間テーブルを設ける
        // Oly_TriggerHandler.bypass('SetContractEstimatePriceHandler');
        // Oly_TriggerHandler.bypass('MaintenanceContractAssetTrigger');
        // Maintenance_Contract_Asset__c middleTable = new Maintenance_Contract_Asset__c();
        // middleTable.Asset__c = ast.Id;
        // middleTable.Maintenance_Contract__c = contract.id;
        // middleTable.endDateGurantee_Text__c = Date.today().addDays(100);
        // middleTable.Check_object__c = true;
        // insert middleTable;
        
        System.runAs(new User(Id = UserInfo.getUserId())){
            // TO DO: implement unit test
            Test.startTest();
            // TestRepo repo = new TestRepo();
            // repo.initAssets();
            Apexpages.currentPage().getParameters().put('hpId', company1.Id);
            Apexpages.currentPage().getParameters().put('rt', 'EndoscopeSystem');
            Apexpages.currentPage().getParameters().put('vmId', contract.Id);
            OFSInsReportLayoutController controller = new OFSInsReportLayoutController();
            controller.init();

            Test.stopTest();
        }

    }

    @isTest
    static void testMethod1() {
        System.runAs(new User(Id = UserInfo.getUserId())){
            Test.startTest();
            TestRepo repo = new TestRepo();
            repo.createInspectionReport(null);
            repo.initAssets();
            repo.sqlIr();
            //创建一个点检明细
            Inspection_Item__c item = new Inspection_Item__c();
            item.Inspection_ReportId__c = repo.ir.Id;
            insert item;

            Apexpages.currentPage().getParameters().put('id', item.Id);
            OFSInsReportLayoutController controller = new OFSInsReportLayoutController();
            
            controller.init();


            controller.save();
            controller.submit();
            Test.stopTest();
        }
    }
    //add by rentx 20210708 end

}