/**
 * This class contains unit tests for validating the behavior of Apex classes
 * and triggers.
 *
 * Unit tests are class methods that verify whether a particular piece
 * of code is working properly. Unit test methods take no arguments,
 * commit no data to the database, and are flagged with the testMethod
 * keyword in the method definition.
 *
 * All test methods in an organization are executed whenever Apex code is deployed
 * to a production organization to confirm correctness, ensure code
 * coverage, and prevent regressions. All Apex classes are
 * required to have at least 75% code coverage in order to be deployed
 * to a production organization. In addition, all triggers must have some code coverage.
 *
 * The @isTest class annotation indicates this class only contains test
 * methods. Classes defined with the @isTest annotation do not count against
 * the organization size limit for all Apex scripts.
 *
 * See the Apex Language Reference for more information about Testing and Code Coverage.
 */
@isTest
private class OpportunityMemberTriggerTest {

    private static Opportunity oppTestCase( ) {
        Opportunity target = new Opportunity( Name = 'test', StageName = '引合', CloseDate = Date.today(),
                                              Trade__c = '内貿', CurrencyIsoCode = 'CNY');
        return target;
    }
    private static OpportunityTeamMember oppMemTestCase(String oppId, String userId, String roleName) {
        OpportunityTeamMember target = new OpportunityTeamMember(
            OpportunityId = oppId, UserId = userId, TeamMemberRole = roleName);
        return target;
    }

    private static User userTestCase(String nameSt, String aliasSt, Id profileid) {
        User target = new User(Test_staff__c = true,
                               LastName = nameSt,
                               FirstName = 'test',
                               Alias = aliasSt,
                               Email = 'Test@sunbridge.com',
                               Username = nameSt + '@sunbridge.com',
                               CommunityNickname = nameSt,
                               IsActive = true,
                               EmailEncodingKey = 'ISO-2022-JP',
                               TimeZoneSidKey = 'Asia/Tokyo',
                               LocaleSidKey = 'ja_JP',
                               LanguageLocaleKey = 'ja',
                               ProfileId = profileid,
                               Job_Category__c = '支援',
                               Province__c = '東京'
                              );
        return target;
    }

    static testMethod void opportunityMemberDuplicateErrorTest() {
        Profile p = [select id from Profile where Name = '系统管理员'];
        //ユーザ作成
        User ur1 = userTestCase('test01', 'test01', p.id);
        ur1.Job_Category__c = '销售推广';
        User ur2 = userTestCase('test02', 'test02', p.id);
        User ur3 = userTestCase('test03', 'test03', p.id);
        User ur4 = userTestCase('test04', 'test04', p.id);
        User ur5 = userTestCase('test05', 'test05', p.id);
        insert new User[] {ur1, ur2, ur3, ur4, ur5};
        //引合作成
        Opportunity opp = oppTestCase();
        insert opp;

        //引合チームinsert，直接追加 error
        OpportunityTeamMember oppMem2 = oppMemTestCase(opp.id, ur2.id, 'FSE');
        insert oppMem2;
        try {
            OpportunityTeamMember oppMem3 = oppMemTestCase(opp.id, ur3.id, '副担当');
            insert oppMem3;
        } catch (DmlException e) {
            System.assert(e.getMessage().contains('Insert failed.'), e.getMessage());
            System.assert(e.getMessage().contains('不能直接追加修改删除［副担当］'), e.getMessage());
        }
        

        //引合チームinsert, double error
        opp.Opportunity_sub_owner__c = ur1.id;
        opp.Opportunity_stms_owner__c = ur5.id;
        update opp;
        try {
            OpportunityTeamMember oppMem3 = oppMemTestCase(opp.id, ur3.id, '副担当');
            OpportunityMemberTrigger.syncMBOpportunityOtmMap.put(opp.id, oppMem3);
            insert oppMem3;
        } catch (DmlException e) {
            System.assert(e.getMessage().contains('Insert failed.'), e.getMessage());
            System.assert(e.getMessage().contains(System.Label.Error_Message_OppTeamMember01), e.getMessage());
        }
        

        //引合チームupdate
        try {
            oppMem2.TeamMemberRole = '副担当';
            OpportunityMemberTrigger.syncMBOpportunityOtmMap.put(opp.id, oppMem2);
            update oppMem2;
        } catch (DmlException e) {
            System.assert(e.getMessage().contains('Update failed.'), e.getMessage());
            System.assert(e.getMessage().contains(System.Label.Error_Message_OppTeamMember01), e.getMessage());
        }
        
    }

    static testMethod void opportunityMemberDeleteErrorTest() {
        Profile p = [select id from Profile where Name = '系统管理员'];
        //ユーザ作成
        User ur1 = userTestCase('test01', 'test01', p.id);
        ur1.Job_Category__c = '销售推广';
        User ur2 = userTestCase('test02', 'test02', p.id);
        User ur3 = userTestCase('test03', 'test03', p.id);
        insert new User[] {ur1, ur2, ur3};
        //引合作成
        Opportunity opp = oppTestCase();
        opp.Opportunity_sub_owner__c = ur1.id;
        opp.Opportunity_stms_owner__c = ur2.id;
        insert opp;
        OpportunityTeamMember otmList = [Select Id, UserId, OpportunityId, TeamMemberRole from OpportunityTeamMember where OpportunityId = :opp.Id and TeamMemberRole = '副担当'];
        try {
            delete otmList;
        } catch (DmlException e) {
            System.assert(e.getMessage().contains('Delete failed.'), e.getMessage());
            System.assert(e.getMessage().contains('不能直接追加修改删除［副担当］'), e.getMessage());
        }
        
    }

    // Opportunity_sub_owner__c => OpportunityTeamMember
    static testMethod void testOpportunity_sub_owner() {
        Profile p = [select Id from Profile where id = :System.Label.ProfileId_SystemAdmin];
        // ユーザー作成
        User subOwner = new User(Test_staff__c = true, LastName = 'oppSub', Province__c = '新疆自治区', Job_Category__c = '销售推广',
                                 FirstName = 'owner', Alias = 'hp', CommunityNickname = 'subOwner', Email = 'olympus_subowner@sb.com', Username = 'olympus_siubowner@sb.com',
                                 IsActive = true, EmailEncodingKey = 'ISO-2022-JP', TimeZoneSidKey = 'Asia/Tokyo', LocaleSidKey = 'ja_JP', LanguageLocaleKey = 'ja', ProfileId = p.id
                                );
        User subOwner2 = new User(Test_staff__c = true, LastName = 'oppSub2', Province__c = '新疆自治区', Job_Category__c = '销售推广',
                                  FirstName = 'owner', Alias = 'hp', CommunityNickname = 'subOwner2', Email = 'olympus_subowner2@sb.com', Username = 'olympus_siubowner2@sb.com',
                                  IsActive = true, EmailEncodingKey = 'ISO-2022-JP', TimeZoneSidKey = 'Asia/Tokyo', LocaleSidKey = 'ja_JP', LanguageLocaleKey = 'ja', ProfileId = p.id
                                 );
        User subOwner3 = new User(Test_staff__c = true, LastName = 'oppSub3', Province__c = '新疆自治区', Job_Category__c = '销售推广',
                                  FirstName = 'owner', Alias = 'hp', CommunityNickname = 'subOwner3', Email = 'olympus_subowner3@sb.com', Username = 'olympus_siubowner3@sb.com',
                                  IsActive = true, EmailEncodingKey = 'ISO-2022-JP', TimeZoneSidKey = 'Asia/Tokyo', LocaleSidKey = 'ja_JP', LanguageLocaleKey = 'ja', ProfileId = p.id
                                 );
        User subOwner4 = new User(Test_staff__c = true, LastName = 'oppSub4', Province__c = '新疆自治区', Job_Category__c = '销售推广',
                                  FirstName = 'owner', Alias = 'hp', CommunityNickname = 'subOwner4', Email = 'olympus_subowner4@sb.com', Username = 'olympus_siubowner4@sb.com',
                                  IsActive = true, EmailEncodingKey = 'ISO-2022-JP', TimeZoneSidKey = 'Asia/Tokyo', LocaleSidKey = 'ja_JP', LanguageLocaleKey = 'ja', ProfileId = p.id
                                 );
        insert new User[] {subOwner, subOwner2, subOwner3, subOwner4};
        subOwner = [select id,Alias__c from  User where id = : subOwner.id];
        // 取引先作成
        List<RecordType> rectHp = [select Id from RecordType where IsActive = true and SobjectType = 'Account' and Name = '病院'];
        List<RecordType> rectDpt = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name = '診療科 呼吸科'];
        Account hp = new Account(RecordTypeId = rectHp[0].Id, Name = 'SoakupTestHp', OwnerId = UserInfo.getUserId(),
                                 OCM_Category__c = 'LLL', FSE_ENG_Main_Leader__c = subOwner.id,
                                 FSE_GI_Main_Leader__c = subOwner.id,
                                 FSE_SP_Main_Leader__c = subOwner.id,
                                 FSE_ENG_Vice_Leader__c = subOwner.Alias__c,
                                 FSE_GI_Vice_Leader__c = subOwner.Alias__c,
                                 FSE_SP_Vice_Leader__c = subOwner.Alias__c
                                );
        insert hp;
        List<Account> dcs = [Select Id, Name, Department_Class_Label__c from Account where Parent.Id = :hp.Id and Department_Class_Label__c = '呼吸科'];

        Account depart = new Account();
        depart.RecordTypeId = rectDpt[0].Id;
        depart.Name         = '*';
        depart.Department_Name__c  = '診療科';
        depart.ParentId            = dcs[0].Id;
        depart.Department_Class__c = dcs[0].Id;
        depart.Hospital__c         = hp.Id;
        insert depart;

        RecordType rectOpp = [select id from RecordType where IsActive = true and SobjectType = 'Opportunity' and DeveloperName = 'Opportunity'];

        List<MB_Opportunity__c> mbopps = [select Id, Opportunity__c from MB_Opportunity__c];
        System.assertEquals(0, mbopps.size());

        System.Test.StartTest();
        Opportunity opp = new Opportunity(
            Name = 'test opp',
            OwnerId = UserInfo.getUserId(),
            Opportunity_sub_owner__c = subOwner.Id,
            Opportunity_stms_owner__c = subOwner3.Id,
            SAP_Province__c = '青海省',
            Opportunity_Category__c = 'GIGI',
            Distributor_InCharge_opp__c = true,
            StageName = '引合',
            CurrencyIsoCode = 'CNY',
            CloseDate = Date.today(),
            AccountId = depart.Id,
            RecordTypeId = rectOpp.Id,
            Closing_Bid_Date__c = Date.today().addDays(-5),
            Hospital__c = hp.Id,
            Group_purchase_PCL__c  = true,
            Competitor__c = 'A'
        );
        insert opp;

        Statu_Achievements__c sta = new Statu_Achievements__c();
        StaticParameter.EscapeNFM010UpsertStatuAchievementsTrigger = true;
        sta.DeliveryDate__c = Date.today();
        sta.Opportunity__c = opp.id;
        sta.ET_SP_Consumption__c  = false;
        sta.ContractAmount__c = 1234;
        upsert sta;
        List<OpportunityTeamMember> otmList = [Select Id, UserId, OpportunityId, TeamMemberRole from OpportunityTeamMember where OpportunityId = :opp.Id order by TeamMemberRole];
        System.assertEquals('副担当', otmList[0].TeamMemberRole);


        OpportunityMemberTrigger.syncMBOpportunityOtmMap = new Map<Id, OpportunityTeamMember>();
        OpportunityMemberTrigger.syncMBOpportunityOtmMapSTMS = new Map<Id, OpportunityTeamMember>();
        opp.Opportunity_sub_owner__c = subOwner2.Id;
        opp.Opportunity_stms_owner__c = subOwner4.Id;
        update opp;
        otmList = [Select Id, UserId, OpportunityId, TeamMemberRole from OpportunityTeamMember where OpportunityId = :opp.Id order by TeamMemberRole];
     
        System.assertEquals('副担当', otmList[0].TeamMemberRole);

        OpportunityMemberTrigger.syncMBOpportunityOtmMap = new Map<Id, OpportunityTeamMember>();
        OpportunityMemberTrigger.syncMBOpportunityOtmMapSTMS = new Map<Id, OpportunityTeamMember>();
        opp.Opportunity_sub_owner__c = null;
        opp.Opportunity_stms_owner__c = null;
        update opp;
        otmList = [Select Id, UserId, OpportunityId, TeamMemberRole from OpportunityTeamMember where OpportunityId = :opp.Id];
        System.assertEquals(0, otmList.size());
        System.Test.StopTest();
    }
}