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

  private String query;
  private String salesdepartment;
  private boolean refreshFlag;
  private BatchIF_Log__c iflog;

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

  global AccountDailyUpdateBatch() {
    iflog = new BatchIF_Log__c();
    iflog.Type__c = 'PushNotification';
    iflog.Is_Error__c = 0;
    iflog.Log__c = 'AccountDailyUpdateBatch start1\n';
    iflog.ErrorLog__c = '';
    insert iflog;

    refreshFlag = false;
  }

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

    salesdepartment = dePartment;
    refreshFlag = false;
  }

  global AccountDailyUpdateBatch(boolean refresh) {
    //特殊功能，用于原有数据刷新员工编码，添加FLAG
    iflog = new BatchIF_Log__c();
    iflog.Type__c = 'PushNotification';
    iflog.Is_Error__c = 0;
    iflog.Log__c = 'AccountDailyUpdateBatch start3\n';
    iflog.ErrorLog__c = '';
    insert iflog;

    refreshFlag = refresh;
  }

  global AccountDailyUpdateBatch(Integer limitNum, String targetId1, String targetId2, String targetId3, String targetId4, String targetId5) {
    //特殊功能，用于原有数据刷新员工编码，添加FLAG
    iflog = new BatchIF_Log__c();
    iflog.Type__c = 'PushNotification';
    iflog.Is_Error__c = 0;
    iflog.Log__c = 'AccountDailyUpdateBatch 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);
    }
    refreshFlag = false;
    system.debug(runTarget);
  }

  global Database.QueryLocator start(Database.BatchableContext BC) {
    /*      iflog = new BatchIF_Log__c();
            iflog.Type__c = 'PushNotification';
            iflog.Is_Error__c = 0;
            iflog.Log__c = 'AccountDailyUpdateBatch start5\n';
            iflog.ErrorLog__c = '';
            insert iflog;*/
    system.debug('=====iflog:' + iflog.id);
    if (refreshFlag) {
      query = 'select id,GI_Main_Employee_No__c,GI_Main__r.Employee_No__c,BF_owner_Employee_No__c,BF_owner__r.Employee_No__c,'
              /* SWAG-B7LADC 2018/12/19 FSE ENG   start*/
              + 'FSE_ENG_Main_Leader_Employee_No__c, FSE_ENG_Main_Leader__r.Employee_No__c, '
              /* SWAG-B7LADC 2018/12/19 FSE ENG   end*/
              + 'ET_owner_Employee_No__c,ET_owner__r.Employee_No__c,SP_Main_Employee_No__c,SP_Main__r.Employee_No__c,URO_owner_Employee_No__c,URO_owner_ID__r.Employee_No__c,GYN_owner_Employee_No__c,GYN_owner__r.Employee_No__c,ENT_owner_Employee_No__c,ENT_owner_ID__r.Employee_No__c,FSE_GI_Main_Leader_Employee_No__c,FSE_GI_Main_Leader__r.Employee_No__c,FSE_SP_Main_Leader_Employee_No__c,FSE_SP_Main_Leader__r.Employee_No__c from Account where Is_Active__c <> \'無効\' and RecordType.DeveloperName = \'HP\' ';
    } else 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*/
      // HWAG-BG682M  start
      query += 'ET_owner_Old__c, ET_Product_Leader_Old__c, FSE_ENG_Main_Leader_Old__c, '
               + 'FSE_ENG_Vice_Leader_Old__c, FSE_GI_Main_Leader_Old__c, FSE_GI_Vice_Leader_Old__c, '
               + 'FSE_SP_Main_Leader_Old__c, FSE_SP_Vice_Leader_Old__c, FSE_Main_Old__c, '
               + 'FSE_Extend_viceLeaderStr_Old__c, BF_owner_Old__c, BF_Product_Leader_Old__c, '
               + 'ENT_owner_ID_Old__c, ENT_Product_Leader_Old__c, GI_Main_Old__c, '
               + 'GI_Product_Leader_Old__c, Extend_Leader_Str_Old__c, Energy_LeaderStr_Old__c, '
               + 'URO_owner_ID_Old__c, URO_Produc_Leader_Old__c, SP_Main_Old__c, '
               + 'GS_Product_Leader_Old__c, GYN_owner_Old__c, GYN_Product_Leader_Old__c, ';
      // HWAG-BG682M  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*/
      // HWAG-BG682M  start
      query += 'ET_owner_Old__c, ET_Product_Leader_Old__c, FSE_ENG_Main_Leader_Old__c, '
               + 'FSE_ENG_Vice_Leader_Old__c, FSE_GI_Main_Leader_Old__c, FSE_GI_Vice_Leader_Old__c, '
               + 'FSE_SP_Main_Leader_Old__c, FSE_SP_Vice_Leader_Old__c, FSE_Main_Old__c, '
               + 'FSE_Extend_viceLeaderStr_Old__c, BF_owner_Old__c, BF_Product_Leader_Old__c, '
               + 'ENT_owner_ID_Old__c, ENT_Product_Leader_Old__c, GI_Main_Old__c, '
               + 'GI_Product_Leader_Old__c, Extend_Leader_Str_Old__c, Energy_LeaderStr_Old__c, '
               + 'URO_owner_ID_Old__c, URO_Produc_Leader_Old__c, SP_Main_Old__c, '
               + 'GS_Product_Leader_Old__c, GYN_owner_Old__c, GYN_Product_Leader_Old__c, ';
      // HWAG-BG682M  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 ' +
               // HWAG-BG682M  start
               ' isUpdateOwnerInform__c = true and ' +
               // HWAG-BG682M  end
               ' Salesdepartment_HP__c = \'' + salesdepartment + '\'';
    }
    system.debug('=====query:' + query);
    return Database.getQueryLocator(query);
  }

  WebService static String executeWebSide(String Hospitalid) {
    BatchIF_Log__c iflog = new BatchIF_Log__c();
    iflog.Type__c = 'PushNotification';
    iflog.Is_Error__c = 0;
    iflog.Log__c = 'AccountDailyUpdateBatch start0\n';
    iflog.ErrorLog__c = '';
    insert iflog;

    List<Account> hospitalList = [select Id, name,
                                  GI_Main__c,
                                  FSE_Main__c,
                                  SP_Main__c,
                                  GYN_owner__c,
                                  BF_owner__c,
                                  ENT_owner_ID__c,
                                  ET_owner__c,
                                  FSE_SP_Main_Leader__c,
                                  FSE_GI_Main_Leader__c,
                                  /* SWAG-B7LADC 2018/12/19 FSE ENG   start*/
                                  FSE_ENG_Main_Leader__c,
                                  FSE_ENG_Vice_Leader__c,
                                  /* SWAG-B7LADC 2018/12/19 FSE ENG   end*/
                                  URO_owner_ID__c ,
                                  GI_Product_Leader__c,
                                  GS_Product_Leader__c,
                                  GYN_Product_Leader__c,
                                  ET_Product_Leader__c,
                                  BF_Product_Leader__c,
                                  ENT_Product_Leader__c,
                                  FSE_GI_Vice_Leader__c,
                                  FSE_SP_Vice_Leader__c,
                                  URO_Produc_Leader__c,
                                  FSE_Extend_viceLeaderStr__c,
                                  Energy_LeaderStr__c,
                                  Extend_Leader_Str__c,
                                  FSE_Main__r.IsActive,
                                  GI_Main__r.IsActive,
                                  URO_owner_ID__r.IsActive,
                                  ET_owner__r.IsActive,
                                  ENT_owner_ID__r.IsActive,
                                  BF_owner__r.IsActive,
                                  SP_Main__r.IsActive,
                                  GYN_owner__r.IsActive,
                                  ParentId,
                                  Original_Date_Flag__c,
                                  OwnerId
                                  from Account where Is_Active__c = '有効' and RecordType.DeveloperName = 'HP' and Id = :Hospitalid];
    if (hospitalList.size() == 0) {
      return System.Label.NotExist_DeptClass;
    } else {
      List<Account> deptClassUpdateList = [select Id,
                                           name,
                                           Parent.ownerId,
                                           RecordType.DeveloperName,
                                           ParentId,
                                           Parent.owner.Alias__c,
                                           Parent.Original_Date_Flag__c,
                                           Energy_LeaderStr__c,
                                           OwnerId
                                           from Account
                                           where Parent.Is_Active__c = '有効'
                                               and Parent.RecordType.DeveloperName = 'HP'
                                                   and Hospital_Department_Class__c = :Hospitalid
                                                       order by Hospital_Department_Class__c, Account_Sort__c];

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


      updateFromHosToDept(hospitalList, deptClassUpdateList, deptUpdateList, iflog, null);
      //updateFromHosToOppor(hospitalList);
      updateFromHosToContact(deptUpdateList, iflog);

      if (iflog.Is_Error__c == 0) {
        iflog.Log__c += 'AccountDailyUpdateBatch end4';
        String tmp2 = iflog.Log__c;
        if (tmp2.length() > 65000) {
          tmp2 = tmp2.substring(0, 65000);
          tmp2 += ' ...have more lines...';
          iflog.Log__c = tmp2;
        }
        update iflog;

        return 'OK';
      } else {
        String tmp = iflog.ErrorLog__c;
        if (tmp.length() > 65000) {
          tmp = tmp.substring(0, 65000);
          tmp += ' ...have more lines...';
          iflog.ErrorLog__c = tmp;
        }
        iflog.Log__c += 'AccountDailyUpdateBatch end4';
        String tmp2 = iflog.Log__c;
        if (tmp2.length() > 65000) {
          tmp2 = tmp2.substring(0, 65000);
          tmp2 += ' ...have more lines...';
          iflog.Log__c = tmp2;
        }
        update iflog;

        return '反应权限组出现错误' + (System.Label.Log_IO_Flag == 'Fin' ? ('，详情可查询BatchIF日志表，ID：' + iflog.id) : '，欲知详细错误内容，请打开BatchLog记录功能，并再次执行');
      }
    }
  }

  //同步所属询价的担当人
  //public static void updateFromHosToOppor(List<Account> hospitalList){
  //  List<opportunity> updateOpporOwner = [select id,Ownerid,Hospital__r.ownerid from opportunity where Hospital__c in:hospitalList];
  //  for(opportunity oppor : updateOpporOwner){
  //      if(oppor.Ownerid != oppor.Hospital__r.ownerId){
  //          oppor.Ownerid = oppor.Hospital__r.ownerId;
  //      }
  //  }
  //  Database.SaveResult[] lsrUpdateoppor = Database.update(updateOpporOwner, false);
  //  for(Database.SaveResult lsrChild : lsrUpdateoppor ){
  //      if( !lsrChild.isSuccess() ){
  //          ErrorRecord.Log__c += 'Error>>>>>>ID:'+lsrChild.getId()+' Log:';
  //          for(Database.Error evErrors : lsrChild.getErrors()){
  //              ErrorRecord.Log__c += evErrors;
  //          }
  //          ErrorRecord.Log__c += '\n';
  //      }
  //  }
  //}

  //同步所属的客户人员（联系人）的所有人
  public static void updateFromHosToContact(List<Account> deptUpdateList, BatchIF_Log__c iflog) {


    List<contact> updateContact =
      [select id, Ownerid, Account.ownerId from contact
       where Accountid in:deptUpdateList
       and isOwnerDiffWithAccount__c = true];
    for (contact con : updateContact) {
      if (con.Ownerid != con.Account.ownerId) {
        con.Ownerid = con.Account.ownerId;
      }
    }
    Integer indexCon = 0;
    Database.SaveResult[] lsrUpdateCon = Database.update(updateContact, false);
    for (Database.SaveResult lsrChild : lsrUpdateCon) {
      if (!lsrChild.isSuccess()) {
        iflog.Is_Error__c = 3;
        Database.Error emsg = lsrChild.getErrors()[0];
        iflog.ErrorLog__c += 'ownerId: ' + updateContact.get(indexCon).ownerId + ' \n'
                             + 'contactID: ' + updateContact.get(indexCon).Id + '\n ConLog:' + emsg.getMessage() + '\n';

      }
      indexCon ++ ;
    }

  }

  public static void updateFromHosToDept(List<Account> hospitalList, List<Account> deptClassUpdateList, List<Account> deptUpdateList, BatchIF_Log__c iflog, string salesdepartment) {

    StaticParameter.EscapeNFM001AgencyContractTrigger = true;
    ControllerUtil.EscapeNFM001Trigger = true;
    if (String.isNotBlank(salesdepartment)) {
      StaticParameter.EscapeOpportunityownerUpdate = true;
    }
    Map<String, Account> hosOwnermap = new Map<String, Account>();
    String shareStr = '';
    List<String> hosIDList = new List<String>();

    //当出现问题，输出这个医院ID串，基本可以把问题限定在一批医院之中
    String ErrorIDStr = '';

    List<String> allAccountList = new List<String>();
    List<String> deptClassidList = new List<String>();
    List<String> deptidList = new List<String>();
    /*
     * HWAG-BG682M start
     * 将医院各个主担当原字段改为现字段
     */
    for (Account acc : hospitalList) {
      if (acc.GI_Main__c != null) {
        if (acc.GI_Main__r.IsActive == true) {
          acc.OwnerId = acc.GI_Main__c;
        }
        acc.ET_owner_Old__c = acc.ET_owner__c;
        acc.ET_Product_Leader_Old__c = acc.ET_Product_Leader__c;
        acc.FSE_ENG_Main_Leader_Old__c = acc.FSE_ENG_Main_Leader__c;
        acc.FSE_ENG_Vice_Leader_Old__c = acc.FSE_ENG_Vice_Leader__c;
        acc.FSE_GI_Main_Leader_Old__c = acc.FSE_GI_Main_Leader__c;
        acc.FSE_GI_Vice_Leader_Old__c = acc.FSE_GI_Vice_Leader__c;
        acc.FSE_SP_Main_Leader_Old__c = acc.FSE_SP_Main_Leader__c;
        acc.FSE_SP_Vice_Leader_Old__c = acc.FSE_SP_Vice_Leader__c;
        acc.FSE_Main_Old__c = acc.FSE_Main__c;
        acc.FSE_Extend_viceLeaderStr_Old__c = acc.FSE_Extend_viceLeaderStr__c;
        acc.BF_owner_Old__c = acc.BF_owner__c;
        acc.BF_Product_Leader_Old__c = acc.BF_Product_Leader__c;
        acc.ENT_owner_ID_Old__c = acc.ENT_owner_ID__c;
        acc.ENT_Product_Leader_Old__c = acc.ENT_Product_Leader__c;
        acc.GI_Main_Old__c = acc.GI_Main__c;
        acc.GI_Product_Leader_Old__c = acc.GI_Product_Leader__c;
        acc.Extend_Leader_Str_Old__c = acc.Extend_Leader_Str__c;
        acc.Energy_LeaderStr_Old__c = acc.Energy_LeaderStr__c;
        acc.URO_owner_ID_Old__c = acc.URO_owner_ID__c;
        acc.URO_Produc_Leader_Old__c = acc.URO_Produc_Leader__c;
        acc.SP_Main_Old__c = acc.SP_Main__c;
        acc.GS_Product_Leader_Old__c = acc.GS_Product_Leader__c;
        acc.GYN_owner_Old__c = acc.GYN_owner__c;
        acc.GYN_Product_Leader_Old__c = acc.GYN_Product_Leader__c;
      }
    }


    // 原来医院在最开始更新，现在挪去最后更新，原代码注释掉，
    // Integer indexIHl = 0;
    // Database.SaveResult[] hpsr = Database.update(hospitalList, false);
    // for (Database.SaveResult lsrChild : hpsr) {
    //     if (!lsrChild.isSuccess()) {
    //         iflog.Is_Error__c = 1;
    //         Database.Error emsg = lsrChild.getErrors()[0];
    //         iflog.ErrorLog__c += 'GI_Main__c: ' + hospitalList.get(indexIHl).GI_Main__c + ' \n'
    //                              + 'Accountid: ' + hospitalList.get(indexIHl).Id + '\n hosLog:' + emsg.getMessage() + '\n';
    //     }
    //     indexIHl ++;
    // }

    //HWAG-BG682M end

    for (Account acc : hospitalList) {
      hosOwnermap.put(acc.Id, acc);
      hosIDList.add(acc.Id);
      if (acc.Original_Date_Flag__c == false) {
        allAccountList.add(acc.Id);
      }

      //acc.OwnerId = acc.GI_Main__c;

      ErrorIDStr += acc.Id + '\n';
    }
    //HWAG-BG682M start
    list<account> UpdatedeptClassList = new list<account>();
    list<account> UpdatedeptList = new list<account>();

    //HWAG-BG682M end
    for (Account deptClass : deptClassUpdateList) {
      if (deptClass.Parent.Original_Date_Flag__c == false) {
        allAccountList.add(deptClass.Id);
        deptClassidList.add(deptClass.Id);
      }




      if (deptClass.RecordType.DeveloperName == 'Department_Class_ET') {
        //戦略科室分類ET
        if (hosOwnermap.get(deptClass.ParentId).ET_owner__c != null) {
          //HWAG-BG682M start
          if (deptClass.ownerid != hosOwnermap.get(deptClass.ParentId).ET_owner__c) {
            UpdatedeptClassList.add(deptClass);
          }
          //CHAN-BHA4FC 能量担当赋值到战略科室 start
          else if (deptClass.Energy_LeaderStr__c != hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c) {
            UpdatedeptClassList.add(deptClass);
          }
          deptClass.Energy_LeaderStr__c = hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c;
          //CHAN-BHA4FC end
          //HWAG-BG682M end
          deptClass.ownerid = hosOwnermap.get(deptClass.ParentId).ET_owner__c;
        }
      } else if (deptClass.RecordType.DeveloperName == 'Department_Class_GI') {
        //戦略科室分類 消化科
        if (hosOwnermap.get(deptClass.ParentId).GI_Main__c != null) {
          //HWAG-BG682M start
          if (deptClass.ownerid != hosOwnermap.get(deptClass.ParentId).GI_Main__c) {
            UpdatedeptClassList.add(deptClass);
          }
          //CHAN-BHA4FC 能量担当赋值到战略科室 start
          else if (deptClass.Energy_LeaderStr__c != hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c) {
            UpdatedeptClassList.add(deptClass);
          }
          deptClass.Energy_LeaderStr__c = hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c;
          //CHAN-BHA4FC end
          //HWAG-BG682M end
          deptClass.ownerid = hosOwnermap.get(deptClass.ParentId).GI_Main__c;
        }
      } else if (deptClass.RecordType.DeveloperName == 'Department_Class_URO') {
        //戦略科室分類 泌尿科
        if (hosOwnermap.get(deptClass.ParentId).URO_owner_ID__c != null) {
          //HWAG-BG682M start
          if (deptClass.ownerid != hosOwnermap.get(deptClass.ParentId).URO_owner_ID__c) {
            UpdatedeptClassList.add(deptClass);
          }
          //CHAN-BHA4FC 能量担当赋值到战略科室 start
          else if (deptClass.Energy_LeaderStr__c != hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c) {
            UpdatedeptClassList.add(deptClass);
          }
          deptClass.Energy_LeaderStr__c = hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c;
          //CHAN-BHA4FC end
          //HWAG-BG682M end
          deptClass.ownerid = hosOwnermap.get(deptClass.ParentId).URO_owner_ID__c;
        }
      } else if (deptClass.RecordType.DeveloperName == 'Department_Class_GS'
                 || deptClass.RecordType.DeveloperName == 'Department_Class_OTH') {
        //戦略科室分類 普外科&戦略科室分類 その他
        if (hosOwnermap.get(deptClass.ParentId).SP_Main__c != null) {
          //HWAG-BG682M start
          if (deptClass.ownerid != hosOwnermap.get(deptClass.ParentId).SP_Main__c) {
            UpdatedeptClassList.add(deptClass);
          }
          //CHAN-BHA4FC 能量担当赋值到战略科室 start
          else if (deptClass.Energy_LeaderStr__c != hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c) {
            UpdatedeptClassList.add(deptClass);
          }
          deptClass.Energy_LeaderStr__c = hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c;
          //CHAN-BHA4FC end
          //HWAG-BG682M end
          deptClass.ownerid = hosOwnermap.get(deptClass.ParentId).SP_Main__c;
        }
      } else if (deptClass.RecordType.DeveloperName == 'Department_Class_GYN') {
        //戦略科室分類 婦人科
        if (hosOwnermap.get(deptClass.ParentId).GYN_owner__c != null) {
          //HWAG-BG682M start
          if (deptClass.ownerid != hosOwnermap.get(deptClass.ParentId).GYN_owner__c) {
            UpdatedeptClassList.add(deptClass);
          }
          //CHAN-BHA4FC 能量担当赋值到战略科室 start
          else if (deptClass.Energy_LeaderStr__c != hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c) {
            UpdatedeptClassList.add(deptClass);
          }
          deptClass.Energy_LeaderStr__c = hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c;
          //CHAN-BHA4FC end
          //HWAG-BG682M end
          deptClass.ownerid = hosOwnermap.get(deptClass.ParentId).GYN_owner__c;
        }
      } else if (deptClass.RecordType.DeveloperName == 'Department_Class_BF') {
        //戦略科室分類 呼吸科
        if (hosOwnermap.get(deptClass.ParentId).BF_owner__c != null) {
          //HWAG-BG682M start
          if (deptClass.ownerid != hosOwnermap.get(deptClass.ParentId).BF_owner__c) {
            UpdatedeptClassList.add(deptClass);
          }
          //CHAN-BHA4FC 能量担当赋值到战略科室 start
          else if (deptClass.Energy_LeaderStr__c != hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c) {
            UpdatedeptClassList.add(deptClass);
          }
          deptClass.Energy_LeaderStr__c = hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c;
          //CHAN-BHA4FC end
          //HWAG-BG682M end
          deptClass.ownerid = hosOwnermap.get(deptClass.ParentId).BF_owner__c;
        }
      } else if (deptClass.RecordType.DeveloperName == 'Department_Class_ENT') {
        //戦略科室分類 耳鼻喉科
        if (hosOwnermap.get(deptClass.ParentId).ENT_owner_ID__c != null) {
          //HWAG-BG682M start
          if (deptClass.ownerid != hosOwnermap.get(deptClass.ParentId).ENT_owner_ID__c) {
            UpdatedeptClassList.add(deptClass);
          }
          //CHAN-BHA4FC 能量担当赋值到战略科室 start
          else if (deptClass.Energy_LeaderStr__c != hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c) {
            UpdatedeptClassList.add(deptClass);
          }
          deptClass.Energy_LeaderStr__c = hosOwnermap.get(deptClass.ParentId).Energy_LeaderStr__c;
          //CHAN-BHA4FC end
          //HWAG-BG682M end
          deptClass.ownerid = hosOwnermap.get(deptClass.ParentId).ENT_owner_ID__c;
        }
      }
      //deptClass.ownerid = hosOwnermap.get(deptClass.ParentId);
    }
    for (Account dept : deptUpdateList) {
      if (dept.Parent.Parent.Original_Date_Flag__c == false) {
        allAccountList.add(dept.Id);
        deptidList.add(dept.Id);
      }

      //dept.ownerid = hosOwnermap.get(dept.Parent.ParentId);
      if (dept.RecordType.DeveloperName == 'Department_GI') {
        //診療科 消化科
        //HWAG-BG682M start
        if (dept.ownerid != hosOwnermap.get(dept.Parent.ParentId).GI_Main__c) {
          UpdatedeptList.add(dept);
        }
        //CHAN-BHA4FC 能量担当赋值到普通科室 start
        else if (dept.Energy_LeaderStr__c != hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c) {
          UpdatedeptList.add(dept);
        }
        dept.Energy_LeaderStr__c = hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c;
        //CHAN-BHA4FC end
        //HWAG-BG682M end
        dept.ownerid = hosOwnermap.get(dept.Parent.ParentId).GI_Main__c;
      } else if (dept.RecordType.DeveloperName == 'Department_URO') {
        //診療科 泌尿科
        //HWAG-BG682M start
        if (dept.ownerid != hosOwnermap.get(dept.Parent.ParentId).URO_owner_ID__c) {
          UpdatedeptList.add(dept);
        }
        //CHAN-BHA4FC 能量担当赋值到普通科室 start
        else if (dept.Energy_LeaderStr__c != hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c) {
          UpdatedeptList.add(dept);
        }
        dept.Energy_LeaderStr__c = hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c;
        //CHAN-BHA4FC end
        //HWAG-BG682M end
        dept.ownerid = hosOwnermap.get(dept.Parent.ParentId).URO_owner_ID__c;
      } else if (dept.RecordType.DeveloperName == 'Department_GS'
                 || dept.RecordType.DeveloperName == 'Department_OTH') {
        //診療科 普外科&診療科 その他
        //HWAG-BG682M start
        if (dept.ownerid != hosOwnermap.get(dept.Parent.ParentId).SP_Main__c) {
          UpdatedeptList.add(dept);
        }
        //CHAN-BHA4FC 能量担当赋值到普通科室 start
        else if (dept.Energy_LeaderStr__c != hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c) {
          UpdatedeptList.add(dept);
        }
        dept.Energy_LeaderStr__c = hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c;
        //CHAN-BHA4FC end
        //HWAG-BG682M end
        dept.ownerid = hosOwnermap.get(dept.Parent.ParentId).SP_Main__c;
      } else if (dept.RecordType.DeveloperName == 'Department_GYN') {
        //診療科 婦人科
        //HWAG-BG682M start
        if (dept.ownerid != hosOwnermap.get(dept.Parent.ParentId).GYN_owner__c) {
          UpdatedeptList.add(dept);
        }
        //CHAN-BHA4FC 能量担当赋值到普通科室 start
        else if (dept.Energy_LeaderStr__c != hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c) {
          UpdatedeptList.add(dept);
        }
        dept.Energy_LeaderStr__c = hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c;
        //CHAN-BHA4FC end
        //HWAG-BG682M end
        dept.ownerid = hosOwnermap.get(dept.Parent.ParentId).GYN_owner__c;
      } else if (dept.RecordType.DeveloperName == 'Department_BF') {
        //診療科 呼吸科
        //HWAG-BG682M start
        if (dept.ownerid != hosOwnermap.get(dept.Parent.ParentId).BF_owner__c) {
          UpdatedeptList.add(dept);
        }
        //CHAN-BHA4FC 能量担当赋值到普通科室 start
        else if (dept.Energy_LeaderStr__c != hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c) {
          UpdatedeptList.add(dept);
        }
        dept.Energy_LeaderStr__c = hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c;
        //CHAN-BHA4FC end
        //HWAG-BG682M end
        dept.ownerid = hosOwnermap.get(dept.Parent.ParentId).BF_owner__c;
      } else if (dept.RecordType.DeveloperName == 'Department_ENT') {
        //診療科 耳鼻喉科
        //HWAG-BG682M start
        if (dept.ownerid != hosOwnermap.get(dept.Parent.ParentId).ENT_owner_ID__c) {
          UpdatedeptList.add(dept);
        }
        //CHAN-BHA4FC 能量担当赋值到普通科室 start
        else if (dept.Energy_LeaderStr__c != hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c) {
          UpdatedeptList.add(dept);
        }
        dept.Energy_LeaderStr__c = hosOwnermap.get(dept.Parent.ParentId).Energy_LeaderStr__c;
        //CHAN-BHA4FC end
        //HWAG-BG682M end
        dept.ownerid = hosOwnermap.get(dept.Parent.ParentId).ENT_owner_ID__c;
      }
      //deptClass.ownerid = hosOwnermap.get(deptClass.ParentId);
    }
    /*        try{
                update deptClassUpdateList;
                update deptUpdateList;
                shareStr = 'Fin';
            }catch(exception oe){
                ErrorRecord.Log__c =+ 'Error>>>>>>'+oe.getMessage();
                ErrorRecord.Is_Error__c = 1;
            }*/
    integer indexDc = 0;
    Database.SaveResult[] dcsr = Database.update(UpdatedeptClassList, false);
    for (Database.SaveResult lsrChild : dcsr) {
      if (!lsrChild.isSuccess()) {
        iflog.Is_Error__c = 1;
        Database.Error emsg = lsrChild.getErrors()[0];
        iflog.ErrorLog__c += 'ownerid: ' + UpdatedeptClassList.get(indexDc).ownerid + ' \n'
                             + 'Accountid: ' + UpdatedeptClassList.get(indexDc).Id + '\n DcLog:' + emsg.getMessage() + '\n';

      }
      indexDc ++ ;
    }
    integer indexDul = 0;
    Database.SaveResult[] dpsr = Database.update(UpdatedeptList, false);
    for (Database.SaveResult lsrChild : dpsr) {
      if (!lsrChild.isSuccess()) {
        iflog.Is_Error__c = 1;
        Database.Error emsg = lsrChild.getErrors()[0];
        iflog.ErrorLog__c += 'ownerid: ' + UpdatedeptList.get(indexDul).ownerid + ' \n'
                             + 'Accountid: ' + UpdatedeptList.get(indexDul).Id + '\n dLog:' + emsg.getMessage() + '\n';

      }
      indexDul ++ ;
    }

    shareStr = 'Fin';

    if (shareStr == 'Fin') {
      List<AccountTeamMember> addTeamList = new List<AccountTeamMember>();
      List<AccountTeamMember> hosiptalTeamList = [select AccountId, UserId, AccountAccessLevel,
                              OpportunityAccessLevel, CaseAccessLevel, TeamMemberRole from AccountTeamMember where AccountId in :hosIDList];
      List<AccountTeamMember> editUpdateList = new List<AccountTeamMember>();//编辑权限的部分
      List<AccountTeamMember> shareUpdateList = new List<AccountTeamMember>();
      List<AccountTeamMember> shareInsertList = new List<AccountTeamMember>();
      /**
      //检索医院对应的客户小组（查阅权限组），先删除战略科室，科室的原有成员，然后将小组成员添加到对应的战略科室，科室。
      //然后编辑共享，是这些成员获得edit权限
      */
      //:::删除
      List<AccountTeamMember> deleteTeamList =
        [select Id, UserId, TeamMemberRole, AccountId, AccountAccessLevel
         from AccountTeamMember
         where AccountId in :deptClassidList or Accountid in:deptidList];
      Database.delete(deleteTeamList, false);

      //:::修改为Edit
      Map<String, List<AccountTeamMember>> TeamMapHosi = new Map<String, List<AccountTeamMember>>();
      for (AccountTeamMember act : hosiptalTeamList) {
        if (TeamMapHosi.containsKey(act.AccountId)) {
          List<AccountTeamMember> addNewaTm = TeamMapHosi.get(act.AccountId);
          addNewaTm.add(act);
          //TeamMapHosi.put(act.AccountId,addNewaTm);
        } else {
          List<AccountTeamMember> addNewaTm = new List<AccountTeamMember>();
          addNewaTm.add(act);
          TeamMapHosi.put(act.AccountId, addNewaTm);
        }
      }
      //新增的项目推广担当、FSE副担当、能量担当, 输入多个，中间半角逗号隔开，名字匹配，添加到客户小组
      //先删除之前的Team
      List<AccountTeamMember> deleteAtmList = [select id  from AccountTeamMember where AccountId in:allAccountList];
      Database.DeleteResult[] deleteAtmListRs = Database.delete(deleteAtmList, false);

      //先删除之前的Share
      String rowCause = 'Manual';
      List<AccountShare> deleteASList = [SELECT Id, AccountId, UserOrGroupId FROM AccountShare where AccountId in:allAccountList and rowCause = :rowCause limit 9999];
      Database.DeleteResult[] deleteASListRs = Database.delete(deleteASList, false);

      //添加新的
      Map<id, List<String>> LeaderShareInsert = new Map<id, List<String>>();

      List<String> AllLeaderShareNameList = new List<String>();

      Map<String, String> teamRoleMap = new Map<String, String>();

      Map<String, String> teamFSESPRoleMap = new Map<String, String>();

      Map<String, String> teamFSEGISPRoleMap = new Map<String, String>();

      Map<String, Map<String, List<String>>> HosToClassDepts = new Map<String, Map<String, List<String>>>();

      for (Account acc : hospitalList) {

        //筛选标签
        if (acc.Original_Date_Flag__c == false) {

          List<String> NameListunPrase = new List<String>();

          List<String> OthDeptUsrList = new List<String>();

          Map<String, List<String>> ClassDeptsToUser = new Map<String, List<String>>();
          /**
              GI_Product_Leader__c
          */
          if (acc.GI_Product_Leader__c != null && acc.GI_Product_Leader__c != '') {
            String LineWhat = acc.GI_Product_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.GI_Product_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '推广担当');

              DeptUsrList.add(usrName);
              OthDeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('GI', DeptUsrList);

          } else {

          }
          /**
              GS_Product_Leader__c
          */
          if (acc.GS_Product_Leader__c != null && acc.GS_Product_Leader__c != '') {
            String LineWhat = acc.GS_Product_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.GS_Product_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '推广担当');

              DeptUsrList.add(usrName);
              OthDeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('GS', DeptUsrList);
          } else {

          }
          /**
              GYN_Product_Leader__c
          */
          if (acc.GYN_Product_Leader__c != null && acc.GYN_Product_Leader__c != '') {
            String LineWhat = acc.GYN_Product_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.GYN_Product_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '推广担当');

              DeptUsrList.add(usrName);
              OthDeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('GYN', DeptUsrList);
          } else {

          }
          /**
              ET_Product_Leader__c
          */
          if (acc.ET_Product_Leader__c != null && acc.ET_Product_Leader__c != '') {
            String LineWhat = acc.ET_Product_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.ET_Product_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '推广担当');

              DeptUsrList.add(usrName);
              OthDeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('ET', DeptUsrList);
          } else {

          }
          /**
              URO_Produc_Leader__c
          */
          if (acc.URO_Produc_Leader__c != null && acc.URO_Produc_Leader__c != '') {
            String LineWhat = acc.URO_Produc_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.URO_Produc_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '推广担当');

              DeptUsrList.add(usrName);
              OthDeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('URO', DeptUsrList);
          } else {

          }
          /**
              BF_Product_Leader__c
          */
          if (acc.BF_Product_Leader__c != null && acc.BF_Product_Leader__c != '') {
            String LineWhat = acc.BF_Product_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.BF_Product_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '推广担当');

              DeptUsrList.add(usrName);
              OthDeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('BF', DeptUsrList);
          } else {

          }
          /**
              ENT_Product_Leader__c
          */
          if (acc.ENT_Product_Leader__c != null && acc.ENT_Product_Leader__c != '') {
            String LineWhat = acc.ENT_Product_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.ENT_Product_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '推广担当');

              DeptUsrList.add(usrName);
              OthDeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('ENT', DeptUsrList);
          } else {

          }
          /**
              FSE_GI_Vice_Leader__c
          */
          if (acc.FSE_GI_Vice_Leader__c != null && acc.FSE_GI_Vice_Leader__c != '') {
            String LineWhat = acc.FSE_GI_Vice_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.FSE_GI_Vice_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);

              //teamRoleMap.put(UsrName, '副担当');
              if (teamFSEGISPRoleMap.containsKey(UsrName)) {
                //continue;
              } else {
                teamFSEGISPRoleMap.put(UsrName, '副担当');
              }

              DeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('FSE_GI', DeptUsrList);
          } else {

          }
          /**
              FSE_SP_Vice_Leader__c
          */
          if (acc.FSE_SP_Vice_Leader__c != null && acc.FSE_SP_Vice_Leader__c != '') {
            String LineWhat = acc.FSE_SP_Vice_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.FSE_SP_Vice_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);

              if (teamFSEGISPRoleMap.containsKey(UsrName)) {
                //continue;
              } else {
                teamFSEGISPRoleMap.put(UsrName, '副担当');
              }
              DeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('FSE_SP', DeptUsrList);
          } else {

          }


          /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
              FSE_ENG_Vice_Leader__c
          */
          if (acc.FSE_ENG_Vice_Leader__c != null && acc.FSE_ENG_Vice_Leader__c != '') {
            String LineWhat = acc.FSE_ENG_Vice_Leader__c;
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.FSE_ENG_Vice_Leader__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);

              //teamRoleMap.put(UsrName, '副担当');
              if (teamFSEGISPRoleMap.containsKey(UsrName)) {
                //continue;
              } else {
                teamFSEGISPRoleMap.put(UsrName, '副担当');
              }

              DeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('FSE_ENG', DeptUsrList);
          }

          /* SWAG-B7LADC 2018/12/19 FSE ENG副担当   end*/
          /**
              Energy_LeaderStr__c
          */
          if (acc.Energy_LeaderStr__c != null && acc.Energy_LeaderStr__c != '') {
            String LineWhat = acc.Energy_LeaderStr__c;
            Map<String, String> DeptToUsr = new Map<String, String>();
            List<String> DeptUsrList = new List<String>();
            for (String UsrName : acc.Energy_LeaderStr__c.split('[,\\，]')) {
              NameListunPrase.add(UsrName);
              AllLeaderShareNameList.add(UsrName);
              teamRoleMap.put(UsrName, '能量主担当');

              DeptUsrList.add(usrName);
            }
            ClassDeptsToUser.put('Energy', DeptUsrList);
          } else {
            //iflog.Log__c += acc.Id + ' Energy_LeaderStr__c>>>>>null\n';
          }
          ClassDeptsToUser.put('OTH', OthDeptUsrList);

          LeaderShareInsert.put(acc.Id, NameListunPrase);
          HosToClassDepts.put(acc.id, ClassDeptsToUser);
          System.debug(LeaderShareInsert + '223344');

        }
      }

      /**
          检索配对
      */
      //检索所有担当人
      //讲昵称和id进行配对
      List<User> loopUser = [select id, Alias__c from user where Alias__c in:AllLeaderShareNameList];
      Map<String, id> allLearUserMap = new Map<String, id>();
      Map<id, String> allLearidUserMap = new Map<id, String>();

      for (User usr : loopUser) {
        allLearUserMap.put(usr.Alias__c, usr.Id);
        allLearidUserMap.put(usr.Id, usr.Alias__c);
      }
      Map<String, String> UsrMatchAcc = new Map<String, String>();

      for (List<String> usrList : LeaderShareInsert.values()) {
        for (String usrName : usrList) {
          if (allLearUserMap.containsKey(usrName)) {
            UsrMatchAcc.put(usrName, allLearUserMap.get(usrName));
          }
        }
      }
      System.debug(allLearUserMap + '123123123');
      //新建客户共享小组成员
      List<AccountTeamMember> insertShareMember = new List<AccountTeamMember>();

      List<AccountTeamMember> insertFSEShareMember = new List<AccountTeamMember>();

      List<AccountTeamMember> insertOTHShareMember = new List<AccountTeamMember>();

      Set<String> insertOTHUserIDSet = new Set<String>();

      String AQ = '';
      Map<String, String> accFSEid = new Map<String, String>();
      Map<String, String> accFSEGIid = new Map<String, String>();
      Map<String, String> accFSESPid = new Map<String, String>();
      /* SWAG-B7LADC 2018/12/19 FSE ENG主担当 start */
      Map<String, String> accFSEENGid = new Map<String, String>();
      /* SWAG-B7LADC 2018/12/19 FSE ENG主担当 end */
      Map<String, Set<id>> FSEleaderIDMap = new Map<String, Set<id>>();
      //医院小组
      for (Account acc : hospitalList) {
        if (acc.Original_Date_Flag__c == false) {

          accFSEid.put(acc.id, acc.FSE_Main__c);
          accFSEGIid.put(acc.id, acc.FSE_GI_Main_Leader__c);
          accFSESPid.put(acc.id, acc.FSE_SP_Main_Leader__c);
          /* SWAG-B7LADC 2018/12/19 FSE ENG主担当 start */
          accFSEENGid.put(acc.id, acc.FSE_ENG_Main_Leader__c);
          /* SWAG-B7LADC 2018/12/19 FSE ENG主担当 end */
          Set<id> FSEleaderID = new Set<id>();
          FSEleaderIDMap.put(acc.id, FSEleaderID);
          FSEleaderID.add(acc.GI_Main__c);
          FSEleaderID.add(acc.FSE_Main__c);
          FSEleaderID.add(acc.SP_Main__c);
          FSEleaderID.add(acc.GYN_owner__c);
          FSEleaderID.add(acc.BF_owner__c);
          FSEleaderID.add(acc.ENT_owner_ID__c);
          FSEleaderID.add(acc.ET_owner__c);

          FSEleaderID.add(acc.URO_owner_ID__c);

          for (String usrNameOne : LeaderShareInsert.get(acc.Id)) {
            if ( !FSEleaderID.contains(allLearUserMap.get(usrNameOne)) ) {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = allLearUserMap.get(usrNameOne),
                AccountId = acc.Id,
                AccountAccessLevel = 'read',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = (teamRoleMap.get(usrNameOne) == null ? teamFSEGISPRoleMap.get(usrNameOne) : teamRoleMap.get(usrNameOne))
              );
              insertShareMember.add(insertMem);
              System.debug(usrNameOne + '‘22222222222’' + allLearUserMap.get(usrNameOne) + '1111111111');
            }
          }
          System.debug(allLearUserMap);
          //添加FSE
          //添加各个主担当
          system.debug('FSEleaderID:' + FSEleaderID);
          for (id UsrID : FSEleaderID) {
            if (UsrID != null) {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = UsrID,
                AccountId = acc.Id,
                AccountAccessLevel = 'read',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None'
              );

              insertFSEShareMember.add(insertMem);
              // SWAG-BCDCM8 start
              if (UsrID != null && UsrID.equals(acc.SP_Main__c)) {
                AccountTeamMember insertMem2 = new AccountTeamMember(
                  UserId = UsrID,
                  AccountId = acc.Id,
                  AccountAccessLevel = 'Edit',
                  OpportunityAccessLevel = 'None',
                  CaseAccessLevel = 'None',
                  TeamMemberRole = 'SP主担当'
                );
                insertFSEShareMember.add(insertMem2);
              }
              // SWAG-BCDCM8 end

            }
          }
          //FSEleaderID.add(acc.FSE_GI_Main_Leader__c);
          //FSEleaderID.add(acc.FSE_SP_Main_Leader__c);
          AccountTeamMember insertMem = new AccountTeamMember(
            UserId = acc.FSE_GI_Main_Leader__c,
            AccountId = acc.Id,
            AccountAccessLevel = 'read',
            OpportunityAccessLevel = 'None',
            CaseAccessLevel = 'None',
            TeamMemberRole = 'FSE主担当'
          );
          insertFSEShareMember.add(insertMem);
          insertMem = new AccountTeamMember(
            UserId = acc.FSE_SP_Main_Leader__c,
            AccountId = acc.Id,
            AccountAccessLevel = 'read',
            OpportunityAccessLevel = 'None',
            CaseAccessLevel = 'None',
            TeamMemberRole = 'FSE主担当'
          );
          insertFSEShareMember.add(insertMem);
          /* SWAG-B7LADC 2018/12/19 FSE ENG主担当 医院只读 start */
          if (acc.FSE_ENG_Main_Leader__c != null) {
            insertMem = new AccountTeamMember(
              UserId = acc.FSE_ENG_Main_Leader__c,
              AccountId = acc.Id,
              AccountAccessLevel = 'read',
              OpportunityAccessLevel = 'None',
              CaseAccessLevel = 'None',
              TeamMemberRole = 'FSE主担当'
            );
            insertFSEShareMember.add(insertMem);
          }
          /* SWAG-B7LADC 2018/12/19 FSE ENG主担当 医院只读 start */
        }
      }
      //战略科室小组
      Id backacc = null;
      for (Account acc : deptClassUpdateList) {

        if (acc.Parent.Original_Date_Flag__c == false) {
          if (backacc != acc.ParentId) {
            insertOTHUserIDSet = new Set<String>();
            backacc = acc.ParentId;
          }
          if (acc.RecordType.DeveloperName == 'Department_Class_ET') {
            //戦略科室分類ET
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String>  UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.ParentId).get('ET');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

          } else if (acc.RecordType.DeveloperName == 'Department_Class_GI') {
            //戦略科室分類 消化科
            Map<String, String> UsrNameExsit = new Map<String, String>();
            List<String>  UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.ParentId).get('GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_Class_URO') {
            //戦略科室分類 泌尿科

            Map<String, String> UsrNameExsit = new Map<String, String>();
            List<String> UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c
            */
            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c
            */

            UserNameList = HosToClassDepts.get(acc.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.ParentId).get('URO');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_Class_GS') {
            //戦略科室分類 普外科&戦略科室分類 その他
            List<String> UserNameList = new List<String>();

            Map<String, String> UsrNameExsit = new Map<String, String>();

            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c
            */
            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c
            */

            UserNameList = HosToClassDepts.get(acc.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.ParentId).get('GS');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_Class_GYN') {
            //戦略科室分類 婦人科
            List<String> UserNameList = new List<String>();
            Map<String, String> UsrNameExsit = new Map<String, String>();

            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.ParentId).get('GYN');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_Class_BF') {
            //戦略科室分類 呼吸科
            List<String> UserNameList = new List<String>();
            Map<String, String> UsrNameExsit = new Map<String, String>();

            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.ParentId).get('BF');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_Class_ENT') {
            //戦略科室分類 耳鼻喉科
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String> UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.ParentId).get('ENT');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }



          } else if (acc.RecordType.DeveloperName == 'Department_Class_OTH') {
            // 戦略科室分類 その他
            Map<String, String> UsrNameExsit = new Map<String, String>();
            List<String>  UserNameList = HosToClassDepts.get(acc.ParentId).get('OTH');
            if (UserNameList != null && UserNameList.size() > 0) {
              for (String usrName : UserNameList) {
                insertOTHUserIDSet.add(allLearUserMap.get(usrName));
              }
            }
            system.debug('11111111:' + FSEleaderIDMap);
            Set<id> FSEleaderID = FSEleaderIDMap.get(acc.ParentId);
            for (id UsrID : FSEleaderID) {
              if (UsrID != null) {
                if (insertOTHUserIDSet.contains(UsrID)) {
                  insertOTHUserIDSet.remove(UsrID);
                }
                AccountTeamMember insertMem = new AccountTeamMember(
                  UserId = UsrID,
                  AccountId = acc.Id,
                  AccountAccessLevel = 'Edit',
                  OpportunityAccessLevel = 'None',
                  CaseAccessLevel = 'None',
                  TeamMemberRole = ''
                );
                insertFSEShareMember.add(insertMem);
              }
            }
            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (insertOTHUserIDSet.contains(allLearUserMap.get(usrName))) {
                    insertOTHUserIDSet.remove(allLearUserMap.get(usrName));
                  }
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    if (insertOTHUserIDSet.contains(allLearUserMap.get(usrName))) {
                      insertOTHUserIDSet.remove(allLearUserMap.get(usrName));
                    }
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
            UserNameList = HosToClassDepts.get(acc.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    if (insertOTHUserIDSet.contains(allLearUserMap.get(usrName))) {
                      insertOTHUserIDSet.remove(allLearUserMap.get(usrName));
                    }
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '能量主担当'
                    );
                    insertShareMember.add(insertMem);
                  }
                }
              }
            }

            if (insertOTHUserIDSet.contains(accFSEid.get(acc.ParentId))) {
              insertOTHUserIDSet.remove(accFSEid.get(acc.ParentId));
            }
            if (insertOTHUserIDSet.contains(acc.Parent.ownerId)) {
              insertOTHUserIDSet.remove(acc.Parent.ownerId);
            }
            if (insertOTHUserIDSet.contains(accFSESPid.get(acc.ParentId))) {
              insertOTHUserIDSet.remove(accFSESPid.get(acc.ParentId));
            }
            if (insertOTHUserIDSet.contains(accFSEGIid.get(acc.ParentId))) {
              insertOTHUserIDSet.remove(accFSEGIid.get(acc.ParentId));
            }

            for (String atmUserId : insertOTHUserIDSet) {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = atmUserId,
                AccountId = acc.Id,
                AccountAccessLevel = 'read',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = '推广担当'
              );
              insertShareMember.add(insertMem);
              insertOTHShareMember.add(insertMem);
            }
            // SWAG-BH7BBS 注释掉以下代码 start
            // AccountTeamMember insertMemP = new AccountTeamMember(
            //     UserId = acc.Parent.ownerId,
            //     AccountId = acc.Id,
            //     AccountAccessLevel = 'Edit',
            //     OpportunityAccessLevel = 'None',
            //     CaseAccessLevel = 'None',
            //     TeamMemberRole = teamRoleMap.get(acc.Parent.owner.Alias__c)
            // );
            // insertShareMember.add(insertMemP);
            // SWAG-BH7BBS end
          }

          //添加FSE
          //FSE 主担当
          if (accFSEid.get(acc.ParentId) != null && accFSEid.get(acc.ParentId) != '') {
            AccountTeamMember insertMem = new AccountTeamMember(
              UserId = accFSEid.get(acc.ParentId),
              AccountId = acc.Id,
              AccountAccessLevel = 'Edit',
              OpportunityAccessLevel = 'None',
              CaseAccessLevel = 'None',
              TeamMemberRole = 'FSE主担当'
            );
            insertFSEShareMember.add(insertMem);
          }

          /* SWAG-B7LADC 2018/12/19 FSE-ENG主担当 设置编辑战略科室权限 start */
          if (acc.RecordType.DeveloperName == 'Department_Class_GS' ||
              acc.RecordType.DeveloperName == 'Department_Class_URO' ||
              acc.RecordType.DeveloperName == 'Department_Class_GYN' ||
              acc.RecordType.DeveloperName == 'Department_Class_OTH' ||
              acc.RecordType.DeveloperName == 'Department_Class_ENT') {
            if (accFSEENGid.get(acc.ParentId) != null && accFSEENGid.get(acc.ParentId) != '') {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = accFSEENGid.get(acc.ParentId),
                AccountId = acc.Id,
                AccountAccessLevel = 'Edit',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = 'FSE主担当'
              );
              insertFSEShareMember.add(insertMem);
            }
          }
          /* SWAG-B7LADC 2018/12/19 FSE-ENG主担当 设置编辑战略科室权限 end */
          //FSE-SP 主担当
          if (acc.RecordType.DeveloperName == 'Department_Class_GS' ||
              acc.RecordType.DeveloperName == 'Department_Class_URO' ||
              acc.RecordType.DeveloperName == 'Department_Class_GYN' ||
              acc.RecordType.DeveloperName == 'Department_Class_OTH' ||
              acc.RecordType.DeveloperName == 'Department_Class_ENT') {
            if (accFSESPid.get(acc.ParentId) != null && accFSESPid.get(acc.ParentId) != '') {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = accFSESPid.get(acc.ParentId),
                AccountId = acc.Id,
                AccountAccessLevel = 'Edit',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = 'FSE主担当'
              );
              insertFSEShareMember.add(insertMem);
            }
          }
          //FSE-GI 主担当
          if (acc.RecordType.DeveloperName == 'Department_Class_GI' ||
              acc.RecordType.DeveloperName == 'Department_Class_BF' ||
              acc.RecordType.DeveloperName == 'Department_Class_ET' ||
              acc.RecordType.DeveloperName == 'Department_Class_OTH') {
            if (accFSEGIid.get(acc.ParentId) != null && accFSEGIid.get(acc.ParentId) != '') {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = accFSEGIid.get(acc.ParentId),
                AccountId = acc.Id,
                AccountAccessLevel = 'Edit',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = 'FSE主担当'
              );
              insertFSEShareMember.add(insertMem);
            }
          }
        }
      }
      //科室小组
      backacc = null;
      for (Account acc : deptUpdateList) {
        //AccountTeamMember insertMemP = new AccountTeamMember(
        //                          UserId = acc.Parent.Parent.ownerId,
        //                          AccountId = acc.Id,
        //                          AccountAccessLevel = 'read',
        //                          OpportunityAccessLevel = 'None',
        //                          CaseAccessLevel ='None'
        //                          );
        //insertShareMember.add(insertMemP);
        if (acc.Parent.Parent.Original_Date_Flag__c == false) {
          if (backacc != acc.Parent.ParentId) {
            insertOTHUserIDSet = new Set<String>();
            backacc = acc.Parent.ParentId;
          }
          if (acc.RecordType.DeveloperName == 'Department_ET') {
            //科室分類ET
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String>  UserNameList = HosToClassDepts.get(acc.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }



            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('ET');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_GI') {
            //科室分類 消化科
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String> UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_URO') {
            //科室分類 泌尿科
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String> UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                  }
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('URO');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_GS') {
            //科室分類 普外科
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String> UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                  }
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '能量主担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('GS');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_GYN') {
            //科室分類 婦人科
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String> UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                  }
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('GYN');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_BF') {
            //科室分類 呼吸科
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String> UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('BF');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
          } else if (acc.RecordType.DeveloperName == 'Department_ENT') {
            //科室分類 耳鼻喉科
            Map<String, String> UsrNameExsit = new Map<String, String>();

            List<String> UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  AccountTeamMember insertMem = new AccountTeamMember(
                    UserId = allLearUserMap.get(usrName),
                    AccountId = acc.Id,
                    AccountAccessLevel = 'Edit',
                    OpportunityAccessLevel = 'None',
                    CaseAccessLevel = 'None',
                    TeamMemberRole = '副担当'
                  );
                  insertShareMember.add(insertMem);
                  UsrNameExsit.put(usrName, usrName);
                  //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                  }
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('ENT');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = teamRoleMap.get(usrName)
                    );
                    //UsrNameExsit.put(usrName,usrName);
                    insertShareMember.add(insertMem);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }


          } else if (acc.RecordType.DeveloperName == 'Department_OTH') {
            //科室分類 その他
            Map<String, String> UsrNameExsit = new Map<String, String>();
            List<String>  UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('OTH');
            if (UserNameList != null && UserNameList.size() > 0) {
              for (String usrName : UserNameList) {
                insertOTHUserIDSet.add(allLearUserMap.get(usrName));
              }
            }
            Set<id> FSEleaderID = FSEleaderIDMap.get(acc.Parent.ParentId);
            for (id UsrID : FSEleaderID) {
              if (UsrID != null) {
                if (insertOTHUserIDSet.contains(UsrID)) {
                  insertOTHUserIDSet.remove(UsrID);
                }
                AccountTeamMember insertMem = new AccountTeamMember(
                  UserId = UsrID,
                  AccountId = acc.Id,
                  AccountAccessLevel = 'Edit',
                  OpportunityAccessLevel = 'None',
                  CaseAccessLevel = 'None',
                  TeamMemberRole = ''
                );
                insertFSEShareMember.add(insertMem);
              }
            }

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_SP');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    if (insertOTHUserIDSet.contains(allLearUserMap.get(usrName))) {
                      insertOTHUserIDSet.remove(allLearUserMap.get(usrName));
                    }
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }

            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c start
            */
            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_ENG');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                  }
                }
              }
            }
            /** SWAG-B7LADC 2018/12/19 FSE ENG副担当
                FSE_ENG_Vice_Leader__c end
            */

            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_GI');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    if (insertOTHUserIDSet.contains(allLearUserMap.get(usrName))) {
                      insertOTHUserIDSet.remove(allLearUserMap.get(usrName));
                    }
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'Edit',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '副担当'
                    );
                    insertShareMember.add(insertMem);
                    UsrNameExsit.put(usrName, usrName);
                    //insertOTHUserIDSet.add(allLearUserMap.get(usrName));
                  }
                }
              }
            }
            UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('Energy');
            if (UserNameList != null) {
              if (UserNameList.size() > 0) {
                for (String usrName : UserNameList) {
                  if (!UsrNameExsit.containsKey(usrName)) {
                    if (insertOTHUserIDSet.contains(allLearUserMap.get(usrName))) {
                      insertOTHUserIDSet.remove(allLearUserMap.get(usrName));
                    }
                    AccountTeamMember insertMem = new AccountTeamMember(
                      UserId = allLearUserMap.get(usrName),
                      AccountId = acc.Id,
                      AccountAccessLevel = 'read',
                      OpportunityAccessLevel = 'None',
                      CaseAccessLevel = 'None',
                      TeamMemberRole = '能量主担当'
                    );
                    insertShareMember.add(insertMem);
                  }
                }
              }
            }
            //List<String> UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_GI');
            //if(UserNameList !=null){
            //  if(UserNameList.size()>0){
            //      for(String usrName : UserNameList){
            //          insertOTHUserIDSet.add(allLearUserMap.get(usrName));
            //      }
            //  }
            //}

            //UserNameList = HosToClassDepts.get(acc.Parent.ParentId).get('FSE_SP');
            //if(UserNameList !=null){
            //  if(UserNameList.size()>0){
            //      for(String usrName : UserNameList){
            //          insertOTHUserIDSet.add(allLearUserMap.get(usrName));
            //      }
            //  }
            //}
            if (insertOTHUserIDSet.contains(accFSEid.get(acc.Parent.ParentId))) {
              insertOTHUserIDSet.remove(accFSEid.get(acc.Parent.ParentId));
            }
            if (insertOTHUserIDSet.contains(acc.Parent.Parent.ownerId)) {
              insertOTHUserIDSet.remove(acc.Parent.Parent.ownerId);
            }
            if (insertOTHUserIDSet.contains(accFSESPid.get(acc.Parent.ParentId))) {
              insertOTHUserIDSet.remove(accFSESPid.get(acc.Parent.ParentId));
            }
            if (insertOTHUserIDSet.contains(accFSEGIid.get(acc.Parent.ParentId))) {
              insertOTHUserIDSet.remove(accFSEGIid.get(acc.Parent.ParentId));
            }
            for (String atmUserId : insertOTHUserIDSet) {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = atmUserId,
                AccountId = acc.Id,
                AccountAccessLevel = 'read',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = '推广担当'
              );
              insertShareMember.add(insertMem);
            }
            // SWAG-BH7BBS 注释掉以下代码 start
            // AccountTeamMember insertMemP = new AccountTeamMember(
            //     UserId = acc.Parent.Parent.ownerId,
            //     AccountId = acc.Id,
            //     AccountAccessLevel = 'read',
            //     OpportunityAccessLevel = 'None',
            //     CaseAccessLevel = 'None',
            //     TeamMemberRole = teamRoleMap.get(acc.Parent.owner.Alias__c)
            // );
            // insertShareMember.add(insertMemP);
            // SWAG-BH7BBS end
          }

          //添加FSE
          if (accFSEid.get(acc.Parent.ParentId) != null && accFSEid.get(acc.Parent.ParentId) != '') {
            AccountTeamMember insertMem = new AccountTeamMember(
              UserId = accFSEid.get(acc.Parent.ParentId),
              AccountId = acc.Id,
              AccountAccessLevel = 'Edit',
              OpportunityAccessLevel = 'None',
              CaseAccessLevel = 'None',
              TeamMemberRole = 'FSE主担当'
            );
            insertFSEShareMember.add(insertMem);
          }

          /* SWAG-B7LADC 2018/12/19 FSE-ENG主担当 设置编辑战略科室权限 start */
          if (acc.RecordType.DeveloperName == 'Department_GS' ||
              acc.RecordType.DeveloperName == 'Department_URO' ||
              acc.RecordType.DeveloperName == 'Department_GYN' ||
              acc.RecordType.DeveloperName == 'Department_OTH' ||
              acc.RecordType.DeveloperName == 'Department_ENT') {
            if (accFSEENGid.get(acc.Parent.ParentId) != null && accFSEENGid.get(acc.Parent.ParentId) != '') {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = accFSEENGid.get(acc.Parent.ParentId),
                AccountId = acc.Id,
                AccountAccessLevel = 'Edit',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = 'FSE主担当'
              );
              insertFSEShareMember.add(insertMem);
            }
          }
          /* SWAG-B7LADC 2018/12/19 FSE-ENG主担当 设置编辑战略科室权限 end */

          if (acc.RecordType.DeveloperName == 'Department_GS' ||
              acc.RecordType.DeveloperName == 'Department_URO' ||
              acc.RecordType.DeveloperName == 'Department_GYN' ||
              acc.RecordType.DeveloperName == 'Department_OTH' ||
              acc.RecordType.DeveloperName == 'Department_ENT') {
            if (accFSESPid.get(acc.Parent.ParentId) != null && accFSESPid.get(acc.Parent.ParentId) != '') {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = accFSESPid.get(acc.Parent.ParentId),
                AccountId = acc.Id,
                AccountAccessLevel = 'Edit',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = 'FSE主担当'
              );
              insertFSEShareMember.add(insertMem);
            }
          }


          if (acc.RecordType.DeveloperName == 'Department_GI' ||
              acc.RecordType.DeveloperName == 'Department_BF' ||
              acc.RecordType.DeveloperName == 'Department_ET' ||
              acc.RecordType.DeveloperName == 'Department_OTH') {
            if (accFSEGIid.get(acc.Parent.ParentId) != null && accFSEGIid.get(acc.Parent.ParentId) != '') {
              AccountTeamMember insertMem = new AccountTeamMember(
                UserId = accFSEGIid.get(acc.Parent.ParentId),
                AccountId = acc.Id,
                AccountAccessLevel = 'Edit',
                OpportunityAccessLevel = 'None',
                CaseAccessLevel = 'None',
                TeamMemberRole = 'FSE主担当'
              );
              insertFSEShareMember.add(insertMem);
            }
          }
        }
      }
      /*
          HWAG-BG682M start
          更新医院权限这次放在最后，如果CPU timeout 超时失败了就不更新
          这样下次会继续处理
       */
      Integer indexIHl = 0;
      Database.SaveResult[] hpsr = Database.update(hospitalList, false);
      for (Database.SaveResult lsrChild : hpsr) {
        if (!lsrChild.isSuccess()) {
          iflog.Is_Error__c = 1;
          Database.Error emsg = lsrChild.getErrors()[0];
          iflog.ErrorLog__c += 'GI_Main__c: ' + hospitalList.get(indexIHl).GI_Main__c + ' \n'
                               + 'Accountid: ' + hospitalList.get(indexIHl).Id + '\n hosLog:' + emsg.getMessage() + '\n';
        }
        indexIHl ++;
      }
      /*
          HWAG-BG682M end
       */
      Database.SaveResult[] lsrInsertShare = Database.insert(insertShareMember, false);
      Database.SaveResult[] lsrInsertFSEShare = Database.insert(insertFSEShareMember, false);

      integer indexIIS = 0;
      integer indexIIFS = 0;
      for (Database.SaveResult lsrInsertShareChild : lsrInsertShare) {

        if ( !lsrInsertShareChild.isSuccess() ) {
          iflog.Is_Error__c = 3;
          Database.Error emsg = lsrInsertShareChild.getErrors()[0];
          iflog.ErrorLog__c += 'UserId: ' + insertShareMember.get(indexIIS).UserId + ' \n'
                               + 'Accountid: ' + insertShareMember.get(indexIIS).Accountid + '\n' +
                               +'ErrorLog:' + emsg.getMessage()  + '\n';
        } else {
          //iflog.ErrorLog__c += 'Correct ID:'+lsrInsertShareChild.getId()+'\n';
        }
        indexIIS ++ ;
      }
      for (Database.SaveResult lsrInsertFSEShareChild : lsrInsertFSEShare) {
        if ( !lsrInsertFSEShareChild.isSuccess() ) {
          iflog.Is_Error__c = 3;
          Database.Error emsg = lsrInsertFSEShareChild.getErrors()[0];
          iflog.ErrorLog__c += 'UserId: ' + insertFSEShareMember.get(indexIIFS).UserId + ' \n'
                               + 'Accountid: ' + insertFSEShareMember.get(indexIIFS).AccountId + '\n' +
                               'ErrorLog:' + emsg.getMessage() + '\n';


        } else {
          //iflog.ErrorLog__c += 'Correct ID:'+lsrInsertFSEShareChild.getId()+'\n';
        }
        indexIIFS ++ ;
      }

    }
  }

  public static void refreshMethod(List<Account> hospitalList, BatchIF_Log__c iflog) {
    iflog.Log__c += 'refreshMethod start \n';
    for (Account acc : hospitalList) {
      acc.Original_Date_Flag__c = true;
      acc.GI_Main_Employee_No__c = acc.GI_Main__r.Employee_No__c;
      acc.BF_owner_Employee_No__c = acc.BF_owner__r.Employee_No__c;
      acc.ET_owner_Employee_No__c = acc.ET_owner__r.Employee_No__c;
      acc.SP_Main_Employee_No__c = acc.SP_Main__r.Employee_No__c;
      acc.URO_owner_Employee_No__c = acc.URO_owner_ID__r.Employee_No__c;
      acc.GYN_owner_Employee_No__c = acc.GYN_owner__r.Employee_No__c;
      acc.ENT_owner_Employee_No__c = acc.ENT_owner_ID__r.Employee_No__c;
      acc.FSE_GI_Main_Leader_Employee_No__c   = acc.FSE_GI_Main_Leader__r.Employee_No__c;
      acc.FSE_SP_Main_Leader_Employee_No__c   = acc.FSE_SP_Main_Leader__r.Employee_No__c;
      acc.FSE_ENG_Main_Leader_Employee_No__c  = acc.FSE_ENG_Main_Leader__r.Employee_No__c;

    }
    //update hospitalList;
    Database.SaveResult[] hpsr = Database.update(hospitalList, false);
    for (Database.SaveResult lsrChild : hpsr) {
      if (!lsrChild.isSuccess()) {
        iflog.Is_Error__c = 1;
        Database.Error emsg = lsrChild.getErrors()[0];
        iflog.ErrorLog__c += ' Log:' + emsg + '\n';
      }
    }
    iflog.Log__c += 'refreshMethod end \n';
  }
  global void execute(Database.BatchableContext BC, List<SObject> hpList) {
    system.debug('=====iflog:' + iflog.id);
    if (refreshFlag) {
      refreshMethod(hpList, iflog);
    } else {
      List<Account> deptClassUpdateList = [select Id, RecordType.DeveloperName, Energy_LeaderStr__c, 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, Energy_LeaderStr__c, 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];

      updateFromHosToDept(hpList, deptClassUpdateList, deptUpdateList, iflog, salesdepartment);
      //updateFromHosToOppor(hpList);
      if (!String.isNotBlank(salesdepartment)) {
        updateFromHosToContact(deptUpdateList, iflog);
      }
    }
  }

  global void finish(Database.BatchableContext BC) {
    //ErrorRecord.Log__c = '\nFin';
    //if(System.Label.Log_IO_Flag == 'Fin'){
    //    ErrorRecord.Is_Error__c = 9;
    //    try{
    //    update ErrorRecord;
    //    }catch(exception oe){

    //    }
    //}else if(System.Label.Log_IO_Flag == 'Keep'){
    //    update ErrorRecord;
    //}
    system.debug('=====iflog:' + iflog.id);
    iflog.Log__c += 'AccountDailyUpdateBatch finish()\n';
    iflog.Log__c += '\nAccountDailyUpdateBatch 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;
      }
    }
    if (String.isNotBlank(salesdepartment)) {
      Database.executeBatch(new OpportunityAndContactDailyUpdateBatch(salesdepartment), 4);
    }
  }
}