#
#= sections モデル
# Authors:: Sumiyo Yamamoto
# Copyright:: Copyright (C) OrbusNeich Medical K.K.  2010.
#--
# date        name                   note
# 2010.2.26   Sumiyo Yamamoto        新規登録
#-------------------------------------------------------------------------------
#++
class Section < Comm::BaseModel::PermanentMaster
  include Comm::Const::MasterCode

  #== named_scope
  #-----------------------------------------------------------------#++
  named_scope :group, :conditions => [
    'grouping_flag_code = ?', MCODE_FLAG_ON
  ]
  
  named_scope :sales, :conditions => [
    'sales_flag_code = ?', MCODE_FLAG_ON
  ]

  def validate
    emsg = ''
    ars = Section.disp_name_is(self.disp_name).valid.id_is_not(self.id)
    
    record_num = ars.length
    if record_num > 0
       ids = ars.collect{|ar| ar.id}
       emsg << EMJ0005
       emsg << "指定の表示名の部署は既に登録されています。"
       emsg << "ID:"+ids.inspect
       raise UserOperationError, emsg
    end
  end
    
  #== グルーピングレベルの営業部署を取得（日付指定）
  # 指定された日付時点の、営業部署を取得。
  #_date_:: 日付（年月のみ有効）
  #
  # 戻り値:: 営業部署配列(ActiveRecord)
  #-----------------------------------------------------------------#++
  def self.find_sales_group_by_date(date = nil)
    results = []
    
    # 部署・ユーザー履歴を検索（登録されているのはグルーピングレベルの営業部署のみ）
    logs = SectionsUsersLog.month(date).all
    
    # 部署ID取得
    section_ids = logs.extract('section_id').uniq
    
    # 部署取得
    if section_ids.length > 0
      results = self.passign('id', section_ids).dsort.all
    end
    
    return results
  end

  #== 末梢レコード取得
  # 末梢の全部署を取得する。
  #_master_find_opt_:: マスターの検索オプション
  #
  # 戻り値:: 末梢の全部署配列(ActiveRecord)
  #-----------------------------------------------------------------#++
  def leafs(master_find_opt = nil)
    results = []
    
    # 引数が末梢だった場合
    if self.leaf_flag_code.to_i == MCODE_FLAG_ON
      results.push(self)
    # 引数が末梢ではない場合→子レコードを検索していく
    else
      childs = Section.set(master_find_opt).sassign('section_id', self.id).all
      childs.each do |child|
        results += child.leafs
      end
    end
    
    return results
  end

  #== グルーピング部署取得
  # 引数で指定された部署の、グルーピングレベルの部署を取得する。
  #
  # 戻り値:: グルーピングレベルの部署(ActiveRecord)
  #-----------------------------------------------------------------#++
  def group
    result = nil
    
    # 自身がグルーピングレベルだった場合
    if self.grouping_flag_code.to_i == MCODE_FLAG_ON
      result = self
    # 自身がグルーピングレベルではない場合→親レコードを検索していく
    else
      result = self.class.find(self.section_id).group
    end
    
    return result
  end

  #== 所属ユーザーポジション取得
  # 所属するユーザーを末端レベルまで検索し、取得する。
  #_master_find_opt_:: マスターの検索オプション
  #
  # 戻り値:: ユーザーポジション配列(ActiveRecord)
  #-----------------------------------------------------------------#++
  def user_positions(master_find_opt = nil)
    # 末梢までの部署IDを取得
    section_ids = self.leafs(master_find_opt).map {|r| r.id }
    
    # ユーザーポジションを検索
    return UserPosition.set(master_find_opt).passign('section_id', section_ids).dsort.all
  end

  #== 所属ユーザーID取得(日付指定)
  # 指定された日付時点の、所属するユーザーIDを取得する。
  #_date_:: 日付（年月のみ有効）
  #_master_find_opt_:: マスターの検索オプション
  #
  # 戻り値:: ユーザーID配列
  #-----------------------------------------------------------------#++
  def user_ids_by_date(date = nil)
    results = []
    
    # 部署・ユーザー履歴を検索
    logs = SectionsUsersLog.month(date).sassign('section_id', self.id).all
    
    # ユーザーID取得
    results = logs.extract('user_id')
    
    return results
  end

  #== 所属ユーザー取得(日付指定)
  # 指定された日付時点の、所属するユーザーを取得する。
  #_date_:: 日付（年月のみ有効）
  #_master_find_opt_:: マスターの検索オプション
  #
  # 戻り値:: ユーザーID配列
  #-----------------------------------------------------------------#++
  def users_by_date(date = nil)
    results = []
    
    ids = user_ids_by_date(date)
    
    results = User.passign('id', ids).dsort.all
    
    return results
  end
end
