module CommLogistics::Modules::DateUtil
  include CommLogistics::Const::Code
  include CommLogistics::Const::Error
  
  def get_target_cutoff(cutoff_type, cutoff_day_code, target_date)
    cutoff_day_code = cutoff_day_code.to_s
    #毎日締め
    if cutoff_type == MCODE_CUTOFF_DAYLY
      return target_date
    elsif cutoff_type > 0 && !cutoff_day_code.blank? 
      #週締め1回／2回
      if cutoff_type == MCODE_CUTOFF_1_WEEKLY || cutoff_type == MCODE_CUTOFF_2_WEEKLY
        day_array = cutoff_day_code.split(",")
        week_num_array = []
        day_array.each do |day|
          tmp_week_num = day.to_i - MCODE_WEEK_OFFSET_NUM #曜日番号 0:日曜日, 1:月曜日...
          if tmp_week_num >=0 && tmp_week_num < 7
            week_num_array.push(tmp_week_num)
          end
        end
        for i in 0..6 #1週間分調べて締め日を求める
          #if target_date.wday==week_num
          if week_num_array.include?(target_date.wday)
            return target_date
          end
          target_date = target_date + 1
        end
      #月1回締め, 月2回締め, 月3回締め
      elsif cutoff_type == MCODE_CUTOFF_1_MONTHLY || cutoff_type == MCODE_CUTOFF_2_MONTHLY || cutoff_type == MCODE_CUTOFF_3_MONTHLY
        day_array = cutoff_day_code.split(",") #cutoff_day_codeには"10,20,99"などの値が入っている(小さい順)
        tmp_target_date = Date.new(target_date.year, target_date.month, target_date.day)
        for i in 0..1 #当月と翌月分を調べて締め日を求める
          day_array.each do |day|
            day_num = day.to_i
            if day_num == MCODE_CUTOFF_EOM #末日
              tmp_target_date = tmp_target_date.end_of_month
            else #5日, 10日, 15日...25日
              tmp_target_date = Date.new(tmp_target_date.year, tmp_target_date.month, day_num)
            end
            if target_date <= tmp_target_date
              return tmp_target_date
            end
          end
          tmp_target_date = tmp_target_date >> 1
        end
      end
    elsif cutoff_type == MCODE_CUTOFF_NONE
      return nil
    end
    return target_date
  end
end