global class AccountSetOwnerBatch implements Database.Batchable<sObject> {
    
    String query;
    
    global AccountSetOwnerBatch() {
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String[] departmentTypes = new String[] {'戦略科室分類 その他', '戦略科室分類 呼吸科', '戦略科室分類 婦人科', '戦略科室分類 普外科', '戦略科室分類 泌尿科', '戦略科室分類 消化科', '戦略科室分類 耳鼻喉科','戦略科室分類ET'};
        //战略科室类型
        List<RecordType> rects = [select Id, Name from RecordType where IsActive = true and SobjectType = 'Account' and Name IN :departmentTypes];
        List<String> deptRectIds = new List<String>();
        for (RecordType rect : rects) {
            deptRectIds.add(rect.Id);
        }
        //战略科室
        return Database.getQueryLocator([select id,OwnerId,ParentId from Account where RecordTypeId in :deptRectIds and Owner.IsActive = true and Is_Active__c <> '無効']);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {
        //战略科室id
        List<id> accIdlist = new List<id>();
        List<Account> accZDeptList = new List<Account>();
        //战略科室
        accZDeptList = scope;

        Map<id, Account> accZDeptMap = new Map<id, Account>();
        for(Account accZDept :accZDeptList){
            if(!accZDeptMap.containskey(accZDept.id)){
                accIdlist.add(accZDept.id);
            }
            accZDeptMap.put(accZDept.id, accZDept);
        }

        //科室
        List<Account> updateDeptList = new List<Account>();
        List<Account> accDeptList = [select id,OwnerId,ParentId from Account where ParentId in :accIdlist and Is_Active__c <> '無効'];
        for(Account accDept : accDeptList){
            //科室对应的战略科室
            Account accZDepts = accZDeptMap.get(accDept.ParentId);
            if(accZDepts != null && accDept.OwnerId != accZDepts.OwnerId){
                accDept.OwnerId = accZDepts.OwnerId;
                updateDeptList.add(accDept);
            }
        }
        if(updateDeptList.size() >0){
            update updateDeptList;
        }
        
        //客户人员
        List<Contact> updateConList = new List<Contact>();
        List<Contact> ConList = [select id, Name, OwnerId, Strategic_dept_Class__c from Contact where Strategic_dept_Class__c in :accIdlist and Isactive__c <> '無効'];
        for(Contact Con : ConList){
            //客户人员对应的战略科室
            Account accZDeptc = accZDeptMap.get(Con.Strategic_dept_Class__c);
            if(accZDeptc != null && Con.OwnerId != accZDeptc.OwnerId){
                Con.OwnerId = accZDeptc.OwnerId;
                updateConList.add(Con);
            }
        }
        if(updateConList.size() > 0){
            update updateConList;
        }
    }
    
    global void finish(Database.BatchableContext BC) {
        //
    }
    
}