@isTest
private class OPDManualSortControllerTest {
    static testMethod void init() {
        ControllerUtil.EscapeNFM001Trigger = true;
        StaticParameter.EscapeNFM001Trigger = true;
        StaticParameter.EscapeNFM001AgencyContractTrigger = true;
        StaticParameter.EscapeNFM001AgencyContractTrigger2 = true;
        StaticParameter.EscapeOppandStaTrigger = true;
        Date toDate = Date.today();
        Boolean userProfileCheck = false;
        // 获取从次月14日至再次月13日的日期
        Date startDate = toDate.addMonths(1).toStartOfMonth().addDays(13);
        Date endDate = toDate.addMonths(2).toStartOfMonth().addDays(12);
        User user = new User();
        System.runAs(new User(Id = Userinfo.getUserId())) {
            String flag='NG2';
            String d1='产品试用';
            String dept='医疗华北营业本部';
            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.Province__c = '北京市';
            user.Dept__c = dept;
            user.Job_Category__c = '销售推广';
            user.Use_Start_Date__c = Date.today().addMonths(-6);
            insert user;
        }
        RecordType rectCam =
            [SELECT Id FROM RecordType
             WHERE IsActive = true AND SobjectType = 'Campaign'
                              AND DeveloperName = 'ServiceEngineerTraining'];
        Campaign cam = new Campaign();
        cam.Name = 'cam';
        cam.Name2__c = '1234';
        cam.RecordTypeId = rectCam.Id;
        cam.StartDate = startDate.addDays(2);
        cam.EndDate = startDate.addDays(5);
        cam.Mailflg_after45__c = true;
        cam.Mailflg_cancel__c = true;
        cam.Mailflg_before15__c = true;
        cam.Mailflg_before7__c = true;
        cam.Mailflg_after3__c = true;
        insert cam;

        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 hospital = new Account();
        hospital.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'HP'].id;
        hospital.Name = 'test hospital';
        hospital.Is_Active__c = '有効';
        hospital.Attribute_Type__c = '卫生部';
        hospital.Speciality_Type__c = '综合医院';
        hospital.Grade__c = '一级';
        hospital.OCM_Category__c = 'SLTV';
        hospital.Is_Medical__c = '医疗机构';
        hospital.State_Master__c = al.id;
        hospital.City_Master__c = al2.id;
        hospital.Town__c = '东京';
        insert hospital;

        Opportunity opp = new Opportunity(
            Name='Opp',
            StageName='引合',
            CloseDate=Date.today().addDays(10),
            Close_Forecasted_Date__c=Date.today(),
            CurrencyIsoCode = 'CNY'
        );
        insert opp;

        Statu_Achievements__c Sac = new Statu_Achievements__c(
            name = 'zhucan_one',
            Opportunity__c = opp.id,
            DeliveryDate__c = Date.today(),
            ContractNO__c = 'ContractNO1',
            ContractAmount__c = 1000
        );
        insert Sac;
        // Opportunity opp1 = new Opportunity(
        //     Name='Opp1',
        //     StageName='注残',
        //     CloseDate=Date.today().addDays(10),
        //     Close_Forecasted_Date__c=Date.today(),
        //     CurrencyIsoCode = 'CNY'
        // );
        // insert opp1;

        OPDPlan__c oPDPlan = new OPDPlan__c();
        oPDPlan.Status__c = '计划中';
        oPDPlan.If_AutoSort__c = 1;
        oPDPlan.NoOpp_Reason__c = 'HCP对应';     //无询价理由
        oPDPlan.OPDLendSortDraft__c = 1;       //备品借出优先度
        oPDPlan.OPDType__c = '询价';
        oPDPlan.OPDLendSort__c = 1;
        oPDPlan.OPDLendSortDraft__c = 1;
        oPDPlan.RentalApplyNum__c = 1;
        oPDPlan.Related_Opportunity1_ID__c = opp.Id;
        oPDPlan.OPDPlan_ImplementDate__c = startDate.addDays(2);
        oPDPlan.NoOpp_Reason__c = null;
        oPDPlan.PlanProdDetail__c = 'CF-H170I*1;';

        // insert oPDPlan;

        OPDPlan__c oPDPlan1 = new OPDPlan__c();
        oPDPlan1.Status__c = '计划中';
        oPDPlan1.If_AutoSort__c =  1;
        oPDPlan1.NoOpp_Reason__c = 'HCP对应';     //无询价理由
        oPDPlan1.OPDLendSortDraft__c = 2;       //备品借出优先度
        oPDPlan1.OPDType__c = '科室';
        oPDPlan1.OPDLendSort__c = 1;
        oPDPlan1.OPDLendSortDraft__c = 2;
        oPDPlan1.RentalApplyNum__c = 2;
        oPDPlan1.Related_Opportunity1_ID__c = opp.Id;
        oPDPlan1.OPDPlan_ImplementDate__c = startDate.addDays(4);
        oPDPlan1.NoOpp_Reason__c = null;
        oPDPlan1.PlanProdDetail__c = 'CF-H170I*1;';

        // insert oPDPlan1;
        insert new OPDPlan__c[] {oPDPlan, oPDPlan1};

        Plan_Rental_Equipment__c planRE1 = new Plan_Rental_Equipment__c();
        planRE1.OPD_Plan__c = oPDPlan.Id;
        planRE1.Rental_Equipment__c = 'CF-H170I';
        planRE1.Name = 'CF-H170I';
        planRE1.Rental_Quantity__c = '1';
        planRE1.ProductCode__c = 'N4480080';
        planRE1.MDM_Model_No__c = 'CF-H170I';
        insert planRE1;

        Account[] strategicDep = [SELECT ID, Name FROM Account WHERE parentId = :hospital.Id AND recordType.DeveloperName = 'Department_Class_OTH'];

         Account dep = new Account();
        dep.recordtypeId = [Select Id FROM RecordType WHERE IsActive = true and SobjectType = 'Account' and DeveloperName = 'Department_OTH'].id;
        dep.Name = 'test dep';
        dep.AgentCode_Ext__c = '9999998';
        dep.ParentId = strategicDep[0].Id;
        dep.Department_Class__c = strategicDep[0].Id;
        dep.Hospital__c = hospital.Id;
        insert dep;

        // Contact contact2 = new Contact();
        // contact2.AccountId = dep.Id;
        // contact2.FirstName = '責任者';
        // contact2.LastName = 'test1经销商';
        // insert contact2;

        Contact contact2 = new Contact();
        contact2.AccountId = dep.Id;
        contact2.RecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Agency').getRecordTypeId();
        contact2.FirstName = '責任者';
        contact2.LastName = 'test1经销商';
        contact2.Agency_User__c = true;
        insert contact2;
        
        Test.startTest();
        //备品借出申请
        Rental_Apply__c raObj = new Rental_Apply__c();
        raObj.Name = 'testra';
        raObj.OPDPlan__c = oPDPlan.Id;
        raObj.Rental_Status__c = '草案中';
        raObj.Owner_province_text__c = '北京市';
        // raObj.Salesdept__c = '医疗华北营业本部';
        // raObj.OPD_OrderNum__c = 1;
        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 = hospital.Id;
        raObj.Strategic_dept__c = strategicDep[0].Id;
        raObj.Account__c = dep.Id;
        raObj.Request_shipping_day__c = startDate.addDays(1);  // 希望到货日
        raObj.Phone_number__c = '1234567890';
        raObj.Loaner_medical_Staff__c = contact2.Id;
        raObj.Campaign__c = cam.Id;
        raObj.applyUser__c = user.Id;
        raObj.Person_In_Charge__c = user.Id;
        // insert raObj;

        Rental_Apply__c raObj1 = new Rental_Apply__c();
        raObj1.Name = 'testra1';
        raObj1.OPDPlan__c = oPDPlan1.Id;
        raObj1.Rental_Status__c = '草案中';
        raObj1.Owner_province_text__c = '北京市';
        // raObj.Salesdept__c = '医疗华北营业本部';
        // raObj1.OPD_OrderNum__c = 1;
        raObj1.Product_category__c = 'GI';
        raObj1.Demo_purpose1__c = '产品试用';
        raObj1.demo_purpose2__c = FixtureUtil.raDemo_purpose2MAP.get('yigoudaihuo');
        raObj1.direct_send__c = '医疗机构';
        raObj1.Loaner_received_staff__c = '王五';
        raObj1.Loaner_received_staff_phone__c = '110';
        raObj1.direct_shippment_address__c = '北京市';
        raObj1.Hospital__c = hospital.Id;
        raObj1.Strategic_dept__c = strategicDep[0].Id;
        raObj1.Account__c = dep.Id;
        raObj1.Request_shipping_day__c = startDate.addDays(1);  // 希望到货日
        raObj1.Phone_number__c = '1234567890';
        raObj1.Loaner_medical_Staff__c = contact2.Id;
        raObj1.Campaign__c = cam.Id;
        raObj1.applyUser__c = user.Id;
        raObj1.Person_In_Charge__c = user.Id;
        raObj1.Follow_UP_Opp__c = opp.Id;
        raObj1.Statu_Achievements__c = Sac.Id;
        // insert raObj1;
        insert new Rental_Apply__c [] {raObj,raObj1};
        Test.stopTest();
        String Salesdept = '医疗华北营业本部';
        List<Rental_Apply__c> renApplyList = [SELECT Id, Name
                                               FROM Rental_Apply__c
                                               WHERE Salesdept__c =:Salesdept
                                               AND OPDPlan__r.RentalApplyNum__c != null 
                                               AND OPDPlan__r.OPDPlan_ImplementDate__c >=: startDate
                                               AND OPDPlan__r.OPDPlan_ImplementDate__c <=: endDate
                                               AND OPDPlan__r.If_AutoSort__c = 1
                                               AND RA_Status__c IN ('草案中','申请中','已批准','申请中（OPD未通过）')  //20231224 sx add 备品智能化添加状态申请中（OPD未通过） 优化
                                               ORDER BY OPDPlan__r.RentalApplyNum__c ASC];

        System.assertEquals(2, renApplyList.size());
        List<ProLine> proLines = new List<ProLine>();
        List<RentalApply> rentalApplys = new List<RentalApply>();
        ProLine proLine1 = new ProLine();
        RentalApply renApp = new RentalApply();
        RentalApply renApp1 = new RentalApply();
        renApp.Id = raObj.Id;
        renApp.Num = 2;
        renApp.OrdNumFlag = TRUE;
        renApp1.Id = raObj1.Id;
        renApp1.Num = 3;
        renApp1.OrdNumFlag = TRUE;

        rentalApplys.add(renApp);
        rentalApplys.add(renApp1);
        proLine1.renApply = rentalApplys;
        proLine1.weekDayCheck = true;
        proLine1.userProfileCheck = true;
        proLines.add(proLine1);
        String jsonRecords = System.JSON.serialize(proLines);
        OPDManualSortController.initRenApply();
        OPDManualSortController.selectRental('医疗华北营业本部');
        OPDManualSortController.saveRenApply(jsonRecords);

    }  
    public class ProLine { 
        @AuraEnabled
        public List<RentalApply> renApply { get; set; } 
        @AuraEnabled
        public Boolean weekDayCheck { get; set; } 
        @AuraEnabled
        public Boolean userProfileCheck { get; set; } 
        // @AuraEnabled
        // public String userSalesdept { get; set; } 
    }

    public class RentalApply {
        @AuraEnabled
        public String id { get; set; } 
        @AuraEnabled
        public String Name { get; set; } 
        @AuraEnabled
        public String OPDPlan { get; set; } 
        @AuraEnabled
        public String Hospital { get; set; } 
        @AuraEnabled
        public String OCSM { get; set; } 
        @AuraEnabled
        public Date OPDUseDate { get; set; } 
        @AuraEnabled
        public String Reson { get; set; } 
        @AuraEnabled
        public Date RequestDate { get; set; } 
        @AuraEnabled
        public Integer Num { get; set; } 
        @AuraEnabled
        public Boolean selected { get; set; } 
        @AuraEnabled
        public Boolean isupdate { get; set; } 
        @AuraEnabled
        public Boolean OrdNumFlag { get; set; } 
        @AuraEnabled
        public String OPDType { get; set; }//OPD计划来源
        @AuraEnabled
        public String OPDPlanStatus { get; set; }//OPD计划状态
        @AuraEnabled
        public String RAStatus { get; set; }//借出状态
        @AuraEnabled
        public String RentalAssistantName { get; set; }//备品助理
        @AuraEnabled
        public String InternalLocation { get; set; }//备品存放地
        @AuraEnabled
        public Date RequestReturnDay { get; set; }//预定归还日
        @AuraEnabled
        public String ShipmentPostCode { get; set; }//邮政编码
    } 
}