/*
 * HWAG-BG682M accountDailyUpdateBatch 更新询价和客户人员主担当的内容拆出来新batch
 */

global class OpportunityAndContactDailyUpdateBatch implements Database.Batchable<sObject>, Database.Stateful {

    private String query;
    private String salesdepartment;
    private BatchIF_Log__c iflog;

    private Integer runLimit;
    private List<String> runTarget;
    private String AccountList;

    global OpportunityAndContactDailyUpdateBatch() {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OpportunityAndContactDailyUpdateBatch start1\n';
        iflog.ErrorLog__c = '';
        insert iflog;
     }
    global OpportunityAndContactDailyUpdateBatch(String dePartment) {
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OpportunityAndContactDailyUpdateBatch start2\n';
        iflog.ErrorLog__c = '';
        insert iflog;

        salesdepartment = dePartment;
     }
     global OpportunityAndContactDailyUpdateBatch(Integer limitNum, String targetId1, String targetId2, String targetId3, String targetId4, String targetId5) {
        //执行五条数据
        iflog = new BatchIF_Log__c();
        iflog.Type__c = 'PushNotification';
        iflog.Is_Error__c = 0;
        iflog.Log__c = 'OpportunityAndContactDailyUpdateBatch start4\n';
        iflog.ErrorLog__c = '';
        insert iflog;

        runLimit = limitNum;
        runTarget = new List<String>();
        if (targetId1 != null && targetId1 != '') {
            runTarget.add(targetId1);
        }
        if (targetId2 != null && targetId2 != '') {
            runTarget.add(targetId2);
        }
        if (targetId3 != null && targetId3 != '') {
            runTarget.add(targetId3);
        }
        if (targetId4 != null && targetId4 != '') {
            runTarget.add(targetId4);
        }
        if (targetId5 != null && targetId5 != '') {
            runTarget.add(targetId5);
        }
        system.debug(runTarget);
    }

	global Database.QueryLocator start(Database.BatchableContext BC) {
        if (salesdepartment == null || salesdepartment == '') {
            query = ' select Id,FSE_Main__c,GI_Main__c,SP_Main__c,GI_Product_Leader__c,GS_Product_Leader__c,GYN_Product_Leader__c,BF_owner__c, ';
            query += 'ET_Product_Leader__c,BF_Product_Leader__c,ENT_Product_Leader__c,FSE_GI_Vice_Leader__c,FSE_SP_Vice_Leader__c,GYN_owner__c,';
            /* SWAG-B7LADC 2018/12/19 FSE ENG   start*/
            query += 'FSE_ENG_Vice_Leader__c, FSE_ENG_Main_Leader__c, ';
            /* SWAG-B7LADC 2018/12/19 FSE ENG   end*/
            query += 'ENT_owner_ID__c,Original_Date_Flag__c,ET_owner__c,URO_owner_ID__c ,URO_Produc_Leader__c,FSE_SP_Main_Leader__c, FSE_GI_Main_Leader__c, ParentId, OwnerId,Energy_LeaderStr__c,FSE_Extend_viceLeaderStr__c,Extend_Leader_Str__c,';
            query += 'FSE_Main__r.IsActive ,GI_Main__r.IsActive ,URO_owner_ID__r.IsActive ,ET_owner__r.IsActive ,';
            query += 'ENT_owner_ID__r.IsActive ,BF_owner__r.IsActive ,SP_Main__r.IsActive ,GYN_owner__r.IsActive ';
            query += ' from Account where Is_Active__c = \'有効\' and RecordType.DeveloperName = \'HP\'';
            if (runTarget != null && runTarget.size() > 0) {
                query += ' and id = :runTarget ';
            }
            if (runLimit != null && runLimit > 0) {
                query += ' limit ' + runLimit;
            }
        } else {
            query = ' select Id,FSE_Main__c,GI_Main__c,SP_Main__c,GI_Product_Leader__c,GS_Product_Leader__c,GYN_Product_Leader__c,BF_owner__c, ';
            query += 'ET_Product_Leader__c,BF_Product_Leader__c,ENT_Product_Leader__c,FSE_GI_Vice_Leader__c,FSE_SP_Vice_Leader__c,GYN_owner__c,';
            query += 'ENT_owner_ID__c,Original_Date_Flag__c,ET_owner__c,URO_owner_ID__c ,URO_Produc_Leader__c,FSE_SP_Main_Leader__c, FSE_GI_Main_Leader__c, ParentId, OwnerId,Energy_LeaderStr__c,FSE_Extend_viceLeaderStr__c,Extend_Leader_Str__c,';
            query += 'FSE_Main__r.IsActive ,GI_Main__r.IsActive ,URO_owner_ID__r.IsActive ,ET_owner__r.IsActive ,';
            /* SWAG-B7LADC 2018/12/19 FSE ENG   start*/
            query += 'FSE_ENG_Vice_Leader__c, FSE_ENG_Main_Leader__c, ';
            /* SWAG-B7LADC 2018/12/19 FSE ENG   end*/
            query += 'ENT_owner_ID__r.IsActive ,BF_owner__r.IsActive ,SP_Main__r.IsActive ,GYN_owner__r.IsActive ';
            query += ' from Account where Is_Active__c = \'有効\' and RecordType.DeveloperName = \'HP\' and '+
            ' Salesdepartment_HP__c = \'' + salesdepartment + '\'';
        }
        system.debug('=====query:' + query);
        return Database.getQueryLocator(query);
    
    }
    
    global void execute(Database.BatchableContext BC, List<SObject> hpList){
         List<Account> deptClassUpdateList = [select Id, RecordType.DeveloperName, Parent.Original_Date_Flag__c, ParentId, Parent.ownerId, Parent.owner.Alias__c, OwnerId from Account where Parent.Is_Active__c = '有効' and Parent.RecordType.DeveloperName = 'HP' and Hospital_Department_Class__c = :hpList order by Hospital_Department_Class__c, Account_Sort__c];

         List<Account> deptUpdateList = [select Id, RecordType.DeveloperName, Parent.Parent.Original_Date_Flag__c, Parent.owner.Alias__c, Parent.ParentId, Parent.Parent.ownerId, OwnerId from Account where Parent.Parent.Is_Active__c = '有効' and Parent.Parent.RecordType.DeveloperName = 'HP' and Hospital__c = :hpList order by Hospital__c, Account_Sort__c];
		 
         AccountDailyUpdateBatch.updateFromHosToContact(deptUpdateList, iflog);
         updateFromHosToContact(deptUpdateList, iflog);

    }
     //同步所属的询价（业务机会）的所有人
    public static void updateFromHosToContact(List<Account> deptUpdateList, BatchIF_Log__c iflog) {
		 List<Opportunity> updateOpportunityList =
            [select id, Ownerid, Account.ownerId from Opportunity
        where Accountid in:deptUpdateList
        and isOwnerDiffWithAccount__c = true
            AND owner_not_automatically_update__c = FALSE ];
        for (Opportunity opp : updateOpportunityList) {
            if (opp.Ownerid != opp.Account.ownerId) {
                opp.Ownerid = opp.Account.ownerId;
            }
        }
        Integer indexCon = 0;
        Database.SaveResult[] lsrUpdateCon = Database.update(updateOpportunityList, false);
        for (Database.SaveResult lsrChild : lsrUpdateCon) {
            if (!lsrChild.isSuccess()) {
                iflog.Is_Error__c = 3;
                Database.Error emsg = lsrChild.getErrors()[0];
                iflog.ErrorLog__c += 'ownerId: ' + updateOpportunityList.get(indexCon).ownerId + ' \n'
                                     + 'OpportunityID: ' + updateOpportunityList.get(indexCon).Id + '\n ConLog:' + emsg.getMessage() + '\n';

            }
            indexCon ++ ;
        }

    }
    global void finish(Database.BatchableContext BC) {
        system.debug('=====iflog:' + iflog.id);
        iflog.Log__c += 'OpportunityAndContactDailyUpdateBatch finish()\n';
        iflog.Log__c += '\nOpportunityAndContactDailyUpdateBatch end';

        String tmp = iflog.ErrorLog__c;
        if (tmp.length() > 65000) {
            tmp = tmp.substring(0, 65000);
            tmp += ' ...have more lines...';
            iflog.ErrorLog__c = tmp;
        }
        String tmp2 = iflog.Log__c;
        if (tmp2.length() > 65000) {
            tmp2 = tmp2.substring(0, 65000);
            tmp2 += ' ...have more lines...';
            iflog.Log__c = tmp2;
        }
        if (System.Label.Log_IO_Flag == 'Keep') {
            update iflog;
        } else if (System.Label.Log_IO_Flag == 'Auto') {
            if (iflog.Is_Error__c > 0) {
                update iflog;
            }
        }
        //add by rentx 2020-12-29
        if (String.isNotBlank(salesdepartment) && salesdepartment.equals('1.华北')) {
            Database.executeBatch(new ConsumablesApplyOrLendBatch(), 50);
        }
        //add by rentx 2020-12-29

        //20200819 ljh add start
        //Database.executeBatch(new ConsumablesApplyOrLendBatch(), 50);
        //20200819 ljh add end
    }
}