# encoding: utf-8
#
# Redmine - project management software
# Copyright (C) 2006-2013  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

module WelcomeHelper

  include CoursesHelper
  include ProjectsHelper

  def get_timestamp(obj)
    if obj.respond_to? :updated_on
      :updated_on
    elsif obj.respond_to? :updated_at
      :updated_at
    elsif obj.respond_to? :created_on
      :created_on
    elsif obj.respond_to? :created_at 
      :created_at
    else
      Time.now.to_i.to_s.to_sym
    end
  end

  def cache_key_for_project(obj)
    timestamp = get_timestamp(obj)
    "welcome_index_project_ul_#{obj.class}_li_#{obj.id}_#{obj.__send__ timestamp}"
  end
  def cache_key_for_event(obj)
    timestamp = get_timestamp(obj)
    "welcome_index_event_ul_#{obj.class}_li_#{obj.id}_#{obj.__send__ timestamp}"
  end
  def cache_key_for_topic(obj)
    timestamp = get_timestamp(obj)
    "welcome_index_topic_ul_#{obj.class}_li_#{obj.id}_#{obj.__send__ timestamp}"
  end

  def welcome_join_in_course(project, user)
    if(user.logged? && 
        !(course_endTime_timeout? project) && 
        (project.course_extra.teacher.id != user.id)
      )
      join_in_course(project, user)
    end
  end

  def get_course_avatar project
    if get_avatar?(project)
      url_to_avatar(project)
    else 
      '../images/avatars/Project/course.jpg'
    end 
  end

  def get_project_avatar project
    if get_avatar?(project)
      url_to_avatar(project)
    else 
      '../images/avatars/Project/0'
    end 
  end
  # 前略·天国の首页君/Earth has been unable stop to welcomePage's.
  # sum      - 要搜索的项目数量
  # max_rate - 新项目所占所有项目的比重，10分制
  #
  # Examples
  #   
  #   find_miracle_course(10, 7)
  #   # => 前7个项目为新课程，后面三个是参与人数最多的
  #
  # Returns project&courses array
  # 原来的取课程逻辑
  def find_miracle_course_base(sum=10, max_rate=7, school_id)
    
    if User.current.user_extensions.school.nil? and school_id.nil?
      Project.active.visible.course_entities.
        joins(:course_extra).
        joins(:memberships).
        group('members.project_id').
        reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum
#    elseif school_id.nil?

    else
      if school_id.nil?
       Project.active.visible.course_entities.
          joins(:course_extra).
          joins(:memberships).
          where("#{Course.table_name}.school_id = ?", User.current.user_extensions.school.id).
          group('members.project_id').
          reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum
      else 
        if school_id == "0"
          Project.active.visible.course_entities.
            joins(:course_extra).
            joins(:memberships).
            group('members.project_id').
            reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum          
        else
        Project.active.visible.course_entities.
            joins(:course_extra).
            joins(:memberships).
            where("#{Course.table_name}.school_id = ?", school_id).
            group('members.project_id').
            reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum      
        end 
      end 
    end   
#    else
#      Project.active.visible.course_entities.
#        joins(:course_extra).
#        joins(:memberships).
#        where("#{Course.table_name}.school_id = ?", school_id).
#        group('members.project_id').
#        reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum        
#    end 
    # max = sum*(max_rate.to_f/10)
    # c1 = find_new_course(sum).to_a.dup
    # c2 = find_all_hot_course(sum).to_a.dup
    # c2 = c2 - c1
    # (c1.take(max)+c2).take(sum)
  end

  #获取课程列表
  # add by nwb
  def find_miracle_course(sum=10, max_rate=7, school_id, time,term)
    if User.current.user_extensions.nil? && User.current.user_extensions.school.nil? and school_id.nil?
      Course.active.visible.
          joins(:memberships).
          where("courses.time = #{time} and courses.term = #{term}").
          group('members.course_id').
          reorder("courses.created_at DESC, COUNT(members.course_id) DESC").take sum
    else
      if school_id.nil?
        Course.active.visible.
            joins(:memberships).
            where("#{Course.table_name}.school_id = ? and courses.time = ? and courses.term = ?", User.current.user_extensions.school.id, time, term).
            group('members.course_id').
            reorder("COUNT(members.course_id) DESC").take sum
      else
        if school_id == "0"
          Course.active.visible.
              joins(:memberships).
              where("courses.time = #{time} and courses.term = #{term}").
              group('members.course_id').
              reorder("COUNT(members.course_id) DESC").take sum
        else
          Course.active.visible.
              joins(:memberships).
              where("#{Course.table_name}.school_id = ? and courses.time = ? and courses.term = ?", school_id, time, term).
              group('members.course_id').
              reorder("COUNT(members.course_id) DESC").take sum
        end
      end
    end
#    else
#      Project.active.visible.course_entities.
#        joins(:course_extra).
#        joins(:memberships).
#        where("#{Course.table_name}.school_id = ?", school_id).
#        group('members.project_id').
#        reorder("courses.time DESC, COUNT(members.project_id) DESC").take sum
#    end
# max = sum*(max_rate.to_f/10)
# c1 = find_new_course(sum).to_a.dup
# c2 = find_all_hot_course(sum).to_a.dup
# c2 = c2 - c1
# (c1.take(max)+c2).take(sum)
  end

  #查找所有学校按每个学校开设课程数量降序排序
  #page 分页查询开始条数的编号,从0开始
  #limit 分页查询的数量
  def find_maxmin_course_school page,limit
    School.find_by_sql("SELECT *,(SELECT COUNT(*) FROM courses WHERE school_id = schools.id) AS a
      FROM schools
      ORDER BY a DESC LIMIT #{page},#{limit}")
    #School.where(" id IN (SELECT school_id FROM courses GROUP BY school_id)").limit limit;
    #School.order("#{School.course_count}").limit(limit).all
    #@school = School.all.sort
    #@school.each do |s|
    #  s.courses.count
    #end
    #result = []
    #@school = School.all.to_ary
    #i = 1
    #for i in  i < School.count
    #  j = i - 1
    #  for j in j > 0
    #    if @school[j].courses.count >
    #  end
    #end
  end

  def find_miracle_project(sum, max_rate,order)
    #max = sum*(max_rate.to_f/10)
    #c1 = find_new_project(sum).to_a.dup
    #c2 = find_all_hot_project(sum).to_a.dup
    #(c2.take(sum-max)+c1.take(max)).take(sum)
    find_all_hot_project(sum,order).to_a.dup
  end
  
  def find_new_course limit=15
    Project.visible.joins(:course_extra).where("#{Project.table_name}.project_type = ? ", 1).order("courses.time DESC, #{Project.table_name}.created_on DESC").limit(limit).all
  end
  
  def find_new_project limit=15
    Project.visible.where("#{Project.table_name}.project_type = ? ", 0).order("#{Project.table_name}.updated_on DESC, #{Project.table_name}.created_on DESC").limit(limit).all
  end


  def find_all_hot_project limit=15,order
    sort_project_by_hot limit,order
  end

  def find_all_hot_course limit=15
    sort_course_by_hot limit
  end

  # modif by nwb
  def find_all_new_hot_course limit = 9 ,school_id = nil, year_now, course_term
    #sort_project_by_hot_rails 1, 'course_ac_para DESC', limit
    #time_now = Time.new.strftime("%Y")
    #if school_id
    #courses = Course.includes(:school, :members).visible.joins(:course_status).where("#{Course.table_name}.created_at like '%#{time_now}%' and #{Course.table_name}.school_id <>
    #   ?", school_id).order("course_ac_para DESC").limit(limit).all
    #else
    #  courses = Course.includes(:school, :members).visible.joins(:course_status).where("#{Course.table_name}.created_at like '%#{time_now}%' and #{Course.table_name}.school_id is not NULL
    #   ").order("course_ac_para DESC").limit(limit).all
    # end
    school_id.nil? ?
        courses = Course.includes(:school, :members).visible.
            joins(:memberships).
            where("courses.time = ? and courses.term = ?  and courses.school_id is not NULL", year_now, course_term).
            group('members.course_id').
            reorder("COUNT(members.course_id) DESC").limit(limit).all
    :
        courses = Course.includes(:school, :members).visible.
            joins(:memberships).
            where("courses.time = ? and courses.term = ? and courses.school_id <>  ?",year_now, course_term, school_id).
            group('members.course_id').
            reorder("COUNT(members.course_id) DESC").limit(limit).all
    courses
  end

  def find_all_hot_bid
    sort_bid_by_hot
  end

  def find_all_hot_contest limit=10
    Contest.reorder("created_on DESC").all.take limit
    # mix_bid = []
    # mix_bid += Contest.reorder("created_on DESC").take(limit).to_a
    # mix_bid += Bid.visible.where('reward_type = ?', 2).reorder('bids.created_on desc').take(limit).to_a
    # mix_bid.sort do |older, newer|
      # newer.created_on - older.created_on
    # end
    # mix_bid.take limit
  end

  def find_all_hot_softapplication limit=10
    Softapplication.reorder("created_at DESC").all.take limit
  end  

  def cal_memos_count event
    return nil if event.parent_id
    event.replies_count
  rescue NoMethodError
    nil
  end
  
  def cal_issues_count event
    event.journals.count
  rescue NoMethodError
    nil
  end
  
  def topic_last_time topic
    return topic.event_datetime if ( !(topic.methods.to_s =~ %r[last_reply]) || topic.last_reply.nil? )
    topic.last_reply.event_datetime
  end
  

  def time_tag_welcome time
    text = distance_of_time_in_words(Time.now, time)
    content_tag('span', text, :title => format_time(time))
  end

  def show_grade project
    grade = 0
    begin
      #ActiveRecord::Base.connection.execute("CALL sp_project_status_cursor();")#执行存储过程速度慢
      grade = project.project_status.grade if project && project.project_status
    rescue Exception => e
      logger.error "Logger.Error [WelcomeHelper] ===> #{e}"
    end
     "项目评分：".html_safe << grade.to_s
  end
  
  def show_user_content event
    str = '&nbsp;'.html_safe
    case event.event_type
    when 'news'
      str << content_tag("span", l('user.active.published')) <<
        content_tag("span", find_all_event_type(event)) << 
        ':&nbsp;'.html_safe << 
        link_to(strip_tags(event.event_description).gsub(/&nbsp;/,''), event.event_url, {:title => event.event_description})
    when 'issue', 'message' , 'bid' , 'wiki-page' , 'document'
      str << content_tag("span", l('user.active.published')) <<
             content_tag("span", find_all_event_type(event)) << 
             ':&nbsp;'.html_safe << 
             link_to(event.event_title, event.event_url, {:title => event.event_title})
    when 'reply' ,'Reply', 'Memo'
      str << content_tag("span", l('user.active.published')) <<
        content_tag("span", find_all_event_type(event)) <<
        ':&nbsp;'.html_safe << 
        link_to(strip_tags(event.event_description).gsub(/&nbsp;/,''), event.event_url, {:title => event.event_description})
    when 'attachment'
      str << content_tag('span', l('user.active.uploaded')) <<
        content_tag('span', find_all_event_type(event)) << 
        ':&nbsp;'.html_safe << 
        link_to(event.event_title, event.event_url, {:title => event.event_title}) <<
        link_to(('&nbsp;['.html_safe+l(:label_downloads_list).to_s << ']'), project_files_path(event.container.project), :class => "attachments_list_color")
    else
      str << content_tag("span",  l('user.active.updated')) <<
        content_tag("span", find_all_event_type(event)) << 
        ':&nbsp;'.html_safe << link_to(event.event_title, event.event_url, {:title => event.event_title})
    end
    str
  rescue Exception => e
    str << content_tag("span", l('user.active.unknow'))
  end
  
  def show_event_reply event
    str = l(:field_active_reply)
    case event.event_type
    when 'news'
      str << link_to( event.comments.count, news_path(event)) << ")"
    when "issue"
      str << link_to(cal_issues_count(event), issue_path(event)) << ")"
    when "Memo"
      str << link_to(cal_memos_count(event), forum_memo_path(event.forum_id,event.id)) << ")"
    else
      str = ""
    end
    str.html_safe
  end

  def find_new_forum_topics limit=7
    # Memo.where('memos.parent_id IS NULL').reorder('memos.created_at DESC').limit(limit)
    # activity = Redmine::Activity::Fetcher.new(nil)
    # activity.scope=['memos']
    # activity.events_welcome(nil, nil, {:limit => limit})

    resultSet = Memo.where('memos.parent_id IS NULL').includes(:last_reply).order('COALESCE (last_replies_memos.created_at, memos.created_at) DESC').limit(limit)
    # resultSet += Message.where('messages.parent_id IS NULL').includes(:last_reply).order('COALESCE (last_replies_messages.created_on, messages.created_on) DESC').limit(limit)
    
    # resultSet = Memo.includes(:children).where('parent_id IS NULL').order('updated_at DESC').limit(limit)
    # resultSet += Message.includes(:children).where('parent_id IS NULL').order('updated_on DESC').limit(limit)
    # resultSet.sort! {|x,y| y.event_datetime <=> x.event_datetime}
    # resultSet = resultSet.to_a
    # for i in 0..(resultSet.size-1)
      # resultSet[i] = resultSet[i].children.last if resultSet[i].children.count > 0
    # end
    # resultSet.take(limit)
  end

  private

  def sort_project_by_hot limit=15,order
    #'grade DESC'
    sort_project_by_hot_rails 0,order , limit
  end

  def sort_course_by_hot limit=15
    sort_project_by_hot_rails 1, 'course_ac_para DESC', limit
  end

  def sort_bid_by_hot
    sort_bid_by_hot_rails 1
  end

  def sort_contest_by_hot
    sort_bid_by_hot_rails 2
  end
#new added by linchun  
  def sort_contest_by_time 
    sort_bid_by_time 2
  end

  #取得所有活动
  def   find_all_activities limit=6
    # users = []
    # activities = Activity.find_by_sql("select distinct user_id from activities order by id DESC limit #{limit}" )
    # activities.each { |activity|
    # 	users << activity.user_id
    # }
    # user_objs = User.find_by_sql("SELECT * FROM users WHERE (users.id IN #{"(" << users.join(',') << ")"} )")
    activity = Redmine::Activity::Fetcher.new(nil)
    has = { # TODO: 待完成
      "show_issues" => true,
      "show_files" => true,
      "show_documents" => true,
      "show_messages" => true,
      "show_news" => true,
      "show_bids" => true,
      "show_contest" => true
    }
    activity.scope_select{|t| ['changesets', 'documents', 'memos', 'messages', 'journals_for_messages', 'bids', 'news', 'contestnotification'].include?(t) ?
        nil : 'You may think you know what the following code does, may be. but why don"t you close this file and go play with something else, Now?' }
    activity.events_welcome(nil, nil, {:limit => limit, :types => 'welcome'})
  end

  #取得论坛数据
  def find_hot_forum_topics limit=9
    ## 以下语句会内链接自身查询出最后一条回复时间，没有回复的帖子不会显示
    # Memo.find_by_sql("
    #   SELECT memos.*, reply.created_at AS last_reply_date FROM memos AS memos 
    #     INNER JOIN memos
    #     AS reply ON memos.last_reply_id=reply.id
    #   WHERE memos.parent_id IS NULL
    #   ORDER BY memos.replies_count DESC, memos.created_at DESC
    #   LIMIT #{limit}")

    #Memo.order('replies_count DESC').where('replies_count <> 0').limit(limit)
    
    resultSet = Memo.order('replies_count DESC, created_at DESC').where('parent_id IS NULL').limit(limit)
    resultSet += Message.order('replies_count DESC, created_on DESC').where('parent_id IS NULL').limit(limit)
    resultSet.sort! {|x,y| (y.replies_count <=> x.replies_count).nonzero? || (y.event_datetime <=> x.event_datetime)}
    resultSet.take(limit)
  end

  def find_my_projects
    my_projects = User.current.memberships.all(conditions: "projects.project_type = 0")
  end

  def sort_project_by_hot_rails project_type=0, order_by='score DESC', limit=15
    # Project.find_by_sql("
			# SELECT p.id, p.name, p.description, p.identifier, t.project_id
			# FROM projects AS p LEFT OUTER JOIN (
				# SELECT project_id,grade FROM project_statuses
				# WHERE project_type = #{project_type} ORDER BY #{order_by} LIMIT #{limit} ) AS t ON p.id = t.project_id ")
    Project.visible.joins(:project_status).joins("LEFT JOIN #{ProjectScore.table_name} ON #{Project.table_name}.id = #{ProjectScore.table_name}.project_id").where("#{Project.table_name}.project_type = ?", project_type).order(order_by).limit(limit).all
  end

  def sort_bid_by_hot_rails reward_type, limit = 10
    Bid.visible.where('reward_type = ?', reward_type).reorder('bids.commit desc').limit(limit)
  end
  
  def sort_bid_by_time reward_type, limit = 10
    Bid.visible.where('reward_type = ?', reward_type).reorder('bids.created_on desc').limit(limit)
  end
  
  def find_all_event_type event
    case event.event_type
    when 'news'
      l(:field_user_active_news)
    when 'issue'
      l(:field_user_active_issue)
    when 'attachment'
      l(:field_user_active_attachment)
    when 'message'
      l(:field_user_active_message)
    when 'Reply','reply'
      l(:field_user_active_reply)
    when 'bid'
      l(:field_user_active_bid)
    when 'Memo'
      l(:field_user_active_memo)
    when 'document'
      l(:field_user_active_document)
    when 'changeset'
      l(:field_user_active_changeset)
    when 'issue-note'
      l(:field_user_active_issue_note)
    else
    event.event_type
    end
  end
  
  def newbie_send_path
    create_new_forum_path '新手讨论'
  end
  def suggestion_send_path
    create_new_forum_path '网站建议'
  end

  private

  def create_new_forum_path name
    # 没有论坛则返回'#' 不能发帖
    # 否则到指定论坛里发帖
    # 没有找到置顶论坛就跑默认第一个论坛发帖
    forum_relation = create_find_undefine_forum name
    backUrl = '#'
    backUrl = new_forum_memo_path(Forum.first) if Forum.count > 0
    backUrl = new_forum_memo_path(forum_relation.first) if !forum_relation.empty?
    return backUrl
  end
  def create_find_undefine_forum name
    Forum.where("name LIKE \'%#{name}%\'")
  end
end
