# encoding: utf-8
## This helper be included in applicationHelper
module CoursesHelper
=begin
1. define TeacherRoles, StudentRoles
2. define count function
3. define search by roles
4. define search member function
=end
  #TeacherRoles = [3, 4, 7, 9]
  #StudentRoles = [5, 10]
  #AllPeople = StudentRoles+TeacherRoles
  ## return people count
  
  # 返回x项目成员数量，即roles表中定义的所有成员
  def projectCount project    
    #searchCountByRoles project, AllPeople
    project.members.count
  end

  # 返回教师数量，即roles表中定义的Manager
  def teacherCount project
    searchTeacherAndAssistant(project).count
    # or
    # searchTeacherAndAssistant(project).count
  end

  # 返回学生数量，即roles表中定义的Reporter
  #def studentCount project
   # searchStudent(project).count
    # or
    # searchStudent(project).count
 # end

  # 判断用户是否是课程的管理员
  # add by nwb
  def is_course_manager?(user_id,course_id)
    @result = false
    @user_id = CourseInfo.find_by_course_id(course_id)
    if @user_id == user.id
      @result = true
    end
    return @result
  end

  # 返回课程设置界面
  def course_settings_tabs
    tabs = [{:name => 'info', :action => :edit_course, :partial => 'courses/edit', :label => :label_information_plural},
            {:name => 'members', :action => :manage_members, :partial => 'courses/settings/members', :label => :label_member_plural}
    ]
    tabs.select { |tab| User.current.allowed_to?(tab[:action], @course) }

  end

  #是否启动互评下拉框
  def is_evaluation_option
    type = []
    option1 = []
    option2 = []
    option1 << l(:lable_start_mutual_evaluation)
    option1 << 1
    option2 << l(:lable_close_mutual_evaluation)
    option2 << 2
    type << option1
    type << option2
  end

  # garble count 混淆数量
  # alias projectCountOrigin projectCount
  # def projectCount project    
  #   count = projectCountOrigin project
  #   garble count
  # end

  def homework_type_option
    type = []
    option1 = []
    option2 = []
    option1 << l(:label_task_submit_form_accessory)
    option1 << 1
    option2 << l(:label_task_submit_form_project)
    option2 << 2
    type << option1
    type << option2
  end

  def proportion_option
    type = []
    i = 0
    while i <= 100
      option = []
      option << i.to_s + "%"
      option << i
      type << option
      i = i + 10
    end
    type
  end


  #alias teacherCountOrigin teacherCount
  #def teacherCount project
  #  count = teacherCountOrigin project
  #  garble count
  #end

  # 注意：此方法有问题，速度慢且结果不准
 # alias studentCountOrigin studentCount
  #def studentCount course
   # count = studentCountOrigin course
    #garble count
 # end

  # 学生人数计算
  # add by nwb
  def studentCount course
    searchStudent(course).count.to_s#course.student.count
  end

  #课程成员数计算
  def memberCount course
    count = searchStudent(course).count + searchTeacherAndAssistant(course).count
    count.to_s
  end

  def eventToLanguageCourse event_type, course
    case event_type
      when "issue-note"
        l :label_issue
      when "issue"
        l :label_issue
      when "attachment"
        l :label_attachment
      when "news"
        l :label_notification
      else
        ""
    end
  end

  def garble count
    count = count.round( 1-count.to_s.size ).to_i
    return count.to_s if count.to_s.size.eql?(1)
    count.to_s << '+' 
  end

  # =====================================================================================
  # return people list
  def searchTeacherAndAssistant project
    #searchPeopleByRoles(project, TeacherRoles)
    members = []
    project.members.each do |m|
       members << m  if m && m.user && m.user.allowed_to?(:as_teacher,project)
    end
    members
  end

  def search_student_in_group(project, course_group_id)
    #searchPeopleByRoles(project, StudentRoles)
    members = []
    project.members.each do |m|
      members << m  if m && m.user && m.user.allowed_to?(:as_student,project)
    end
    members
  end
  def searchStudent project
    #searchPeopleByRoles(project, StudentRoles)
    members = []

    project.members.each do |m|
      if m && m.user && m.user.allowed_to?(:as_student,project)
        members << m

      end
    end
    members
  end

  
 
  def searchStudent_by_name  project, name
    #searchPeopleByRoles(project, StudentRoles)
    members = []
    project.members.each do |m|
      if m && m.user && m.user.allowed_to?(:as_student,project)
        username = m.user[:lastname].to_s + m.user[:firstname].to_s
        if(m.user[:login].to_s.include?(name) ||  m.user.user_extensions[:student_id].to_s.include?(name) || username.include?(name))
          members << m
        end
      end
    end
    members
  end
  def searchmember_by_name  members, name
    #searchPeopleByRoles(project, StudentRoles)
    mems = []
    if name != ""
     members.each do |m|

        username = m.user[:lastname].to_s + m.user[:firstname].to_s
        if(m.user[:login].to_s.include?(name) ||  m.user.user_extensions[:student_id].to_s.include?(name) || username.include?(name))
          mems << m
        end
      end
    else
     mems = members
   end
    mems
  end
  def searchgroupmember_by_name  members, name, group
    #searchPeopleByRoles(project, StudentRoles)
    mems = []
    if name != ""
    members.each do |m|
    if m.course_group_id == group.id
      username = m.user[:lastname].to_s + m.user[:firstname].to_s
      if(m.user[:login].to_s.include?(name) ||  m.user.user_extensions[:student_id].to_s.include?(name) || username.include?(name))
        mems << m
      end
    end
    end
    else
      mems = members
    end
    mems
  end
  def searchgroupstudent_by_name(group, project, name)
    members = []
    group.members.each do |m|
      if m && m.user && m.user.allowed_to?(:as_student,project)
        username = m.user[:lastname].to_s + m.user[:firstname].to_s
        if(m.user[:login].to_s.include?(name) ||  m.user.user_extensions[:student_id].to_s.include?(name) || username.include?(name))
          members << m
        end
      end
    end
    members
  end
  def searchStudent_by_group  group, project
    #searchPeopleByRoles(project, StudentRoles)
    members = []
    group.members.each do |m|
      members << m  if m && m.user && m.user.allowed_to?(:as_student,project)
    end
    members
  end
  # =====================================================================================

  #def searchCountByRoles project, roles_id
  #  members = searchPeopleByRoles project, roles_id
  #  members.count
  #end

  #def searchPeopleByRoles project, roles_id
  #  members = []
  #  begin
  #    members = project.members.joins(:member_roles).where("member_roles.role_id IN (:role_id)", {:role_id => roles_id})
  #  rescue Exception => e
  #    logger.error "[CoursesHelper] ===> #{e}"
  #  end
  #  members
  #end

  def sort_courses(state)
    content = ''.html_safe
    case state
      when 0

        content << content_tag('li', link_to(l(:label_sort_by_active), courses_path(:courses_sort_type => '1')))
        content << content_tag('li', link_to(l(:label_sort_by_influence), courses_path(:courses_sort_type => '2')))
        content << content_tag('li', link_to(l(:label_sort_by_time), courses_path(:courses_sort_type => '0'), :class=>"selected"), :class=>"selected")
      when 1

        content << content_tag('li', link_to(l(:label_sort_by_active), courses_path(:courses_sort_type => '1'), :class=>"selected"), :class=>"selected")
        content << content_tag('li', link_to(l(:label_sort_by_influence), courses_path(:courses_sort_type => '2')))
        content << content_tag('li', link_to(l(:label_sort_by_time), courses_path(:courses_sort_type => '0')))
      when 2
        content << content_tag('li', link_to(l(:label_sort_by_active), courses_path(:courses_sort_type => '1')))
        content << content_tag('li', link_to(l(:label_sort_by_influence), courses_path(:courses_sort_type => '2'), :class=>"selected"), :class=>"selected")
        content << content_tag('li', link_to(l(:label_sort_by_time), courses_path(:courses_sort_type => '0')))
    end
    content = content_tag('ul', content)
    content_tag('div', content, :class => "tabs")
  end

  def render_course_hierarchy(courses)
    render_course_nested_lists(courses) do |course|
      s = link_to_course(course, {}, :class => "#{course.css_classes} #{User.current.member_of_course?(course) ? 'my-course' : nil}").html_safe
      s
    end
  end

  #useless
  #def searchMembersByRole project, role_id
  #  members = []
  #  begin
  #    members = project.members.joins(:member_roles).where("member_roles.role_id = :role_id", {:role_id => role_id })
  #  rescue Exception => e
  #    logger.error "[CoursesHelper] ===> #{e}"
  #  end
  #  members
  #end

  def sort_course(state,  school_id)
    content = ''.html_safe
    case state
      when 0
        content << content_tag('li', link_to(l(:label_sort_by_time), courses_path(:course_sort_type => '0'), :school_id => school_id, :class=>"selected"), :class=>"selected")
        content << content_tag('li', link_to(l(:label_sort_by_active), courses_path(:course_sort_type => '1', :school_id => school_id)))
        content << content_tag('li', link_to(l(:label_sort_by_activity), courses_path(:course_sort_type => '3', :school_id => school_id)))

      when 1
        content << content_tag('li', link_to(l(:label_sort_by_time), courses_path(:course_sort_type => '0', :school_id => school_id)))
        content << content_tag('li', link_to(l(:label_sort_by_active), courses_path(:course_sort_type => '1', :school_id => school_id), :class=>"selected"), :class=>"selected")
        content << content_tag('li', link_to(l(:label_sort_by_activity), courses_path(:course_sort_type => '3', :school_id => school_id)))

      when 2
        content << content_tag('li', link_to(l(:label_sort_by_time), courses_path(:course_sort_type => '0', :school_id => school_id)))
        content << content_tag('li', link_to(l(:label_sort_by_active), courses_path(:course_sort_type => '1', :school_id => school_id)))
        content << content_tag('li', link_to(l(:label_sort_by_activity), courses_path(:course_sort_type => '3', :school_id => school_id)))

      #gcm
      when 3
        content << content_tag('li', link_to(l(:label_sort_by_time), courses_path(:course_sort_type => '0', :school_id => school_id)))
        content << content_tag('li', link_to(l(:label_sort_by_active), courses_path(:course_sort_type => '1', :school_id => school_id)))
        content << content_tag('li', link_to(l(:label_sort_by_activity), courses_path(:course_sort_type => '3', :school_id => school_id), :class=>"selected"), :class=>"selected")
    end
    #gcmend

    content = content_tag('ul', content)
    content_tag('div', content, :class => "tabs")
  end
  
  def findCourseTime project
    str = ""
    begin
      @course = Course.find_by_extra(@project.identifier)
      date_format = l(:zh_date)[:formats][:default]
      if @course
        str = DateTime.parse(@course.setup_time.to_s).strftime("#{date_format}").to_s unless @course.setup_time.blank?
        str <<  '-' unless  @course.setup_time.blank?
        str <<  DateTime.parse(@course.endup_time.to_s).strftime("#{date_format}").to_s unless @course.endup_time.blank?
      end
    rescue Exception => e
      logger.error  "[CoursesHelper] ===> #{e}"
    end
    str
  end

  # added by nwb
  def get_course_term course
    str = ( course.try(:time).to_s << '.' << course.try(:term).to_s )
    str[0..-4]
  end

  def members_to_user_ids members
    people = []
    members.each { |member|
      people << member.user_id
    }
    people
  end
  # 截至到2014-03-17 这个是最终的判断课程是否过期的方法
  def course_endTime_timeout? course
    end_time_str = course.try(:endup_time)
    begin
      cTime = Time.parse(end_time_str.to_s)
    rescue TypeError,ArgumentError
      cTime = Time.parse("3000-01-01")
    end
    now = Time.now

    now > cTime
  end
  def find_by_extra_from_project extra
    Course.find_by_extra(try(extra))
  end
  #判断指定用户是不是当前课程的老师
  def is_course_teacher (user,course)
    #course.members.joins(:member_roles).where("member_roles.role_id IN (:role_id) and members.user_id = #{user.id}", {:role_id => TeacherRoles}).count != 0
    user.allowed_to?(:as_teacher,course)
    #修改为根据用户是否有发布任务的权限来判断用户是否是课程的老师
    #is_teacher = false
    #@membership = user.memberships.all(:conditions => Project.visible_condition(User.current))
    #@membership.each do |membership|
    #  unless(membership.project.project_type==0)
    #    if user.allowed_to?({:controller => "projects", :action => "new_homework"}, membership.project, :global => false)
    #      is_teacher = true
    #    end
    #  end
    #end
    #is_teacher
  end
  #当前用户是不是指定课程的学生
  def is_cur_course_student course
    #course.members.joins(:member_roles).where("member_roles.role_id IN (:role_id) and members.user_id = #{User.current.id}", {:role_id => StudentRoles}).count != 0
    User.current.logged? && User.current.member_of_course?(course) && !(User.current.allowed_to?(:as_teacher,course))
    #修改：能新建占位且不能新建任务的角色判定为学生
    #is_student = false
    #@membership = User.current.memberships.all(:conditions => Project.visible_condition(User.current))
    #@membership.each do |membership|
    #  unless(membership.project.project_type==0)
    #    if !User.current.allowed_to?({:controller => "projects", :action => "new_homework"}, membership.project, :global => false) && User.current.allowed_to?({:controller => "homework_attach", :action => "new"}, membership.project, :global => false)
    #      is_student = true
    #    end
    #  end
    #end
    #is_student
  end
  #获取当前用户在指定作业下提交的作业的集合
  def cur_user_homework_for_bid bid
    bid.homeworks.where("user_id = ?",User.current)
  end

  #判断当前用户对指定作业是否已经评价过
  def has_evaluation? homework
    seem_count = homework.rates(:quality).where("rater_id = ?",User.current).count
    seem_count > 0
  end

  #获取指定作业的所有成员
  def users_for_homework homework
    homework.nil? ? [] : (homework.users + [homework.user])
  end

  #获取指定作业的最终评分
  #最终评分 = 学生评分的平均分 * 0.4 +教师评分 * 0.6
  def score_for_homework homework
    if  homework.bid.is_evaluation == 1 || homework.bid.is_evaluation == nil
      return format("%.2f",(homework.bid.proportion * 1.0 / 100) * (teacher_score_for_homework(homework).to_f) + (1 - homework.bid.proportion * 1.0 / 100) * (student_score_for_homework(homework).to_f))
    else
      return teacher_score_for_homework homework
    end
  end
  def score_for_homework_new homework
    if  teacher_score_for_homework(homework) != 0
      return teacher_score_for_homework homework
    else
      return student_score_for_homework homework
    end
  end
  #获取作业的互评得分
  def student_score_for_homework homework
    #member = searchTeacherAndAssistant(homework.bid.courses.first).first#searchPeopleByRoles(homework.bid.courses.first,TeacherRoles).first
    #if member.nil?
    #  return "0.00"
    #end
    #student_stars = homework.rates(:quality).where("rater_id <> #{member.user_id}").select("stars")
    members = searchStudent(homework.bid.courses.first)
    user_ids = []
    members.each do |user|
      user_ids << user.user_id
    end
    student_stars = homework.rates(:quality).where("rater_id in (:user_ids)",{:user_ids => user_ids}).select("stars")
    student_stars_count = 0
    student_stars.each do |star|
      student_stars_count = student_stars_count +  star.stars
    end
    return format("%.2f",student_stars_count / (student_stars.count == 0 ? 1 : student_stars.count))



  end

  #获取作业的教师评分
  #多个教师只获取一份教师评分
  def teacher_score_for_homework homework
    members = searchTeacherAndAssistant(homework.bid.courses.first)
    teacher_ids = []
    members.each do |user|
      teacher_ids << user.user_id
    end
    teacher_stars = homework.rates(:quality).where("rater_id in (:teacher_ids)",{:teacher_ids => teacher_ids}).select("stars")
    teacher_stars_count = 0
    teacher_stars.each do |star|
      teacher_stars_count = teacher_stars_count +  star.stars
    end
    return format("%.2f",teacher_stars.count > 0 ? teacher_stars_count/teacher_stars.count : 0)
  end

  #获取指定项目的得分
  def project_score project
    issue_count = project.issues.count
    issue_journal_count = project.issue_changes.count
    issue_score = issue_count * 0.2
    issue_journal_score = issue_journal_count * 0.1
    finall_issue_score = issue_score + issue_journal_score
    new_count = project.news.count
    new_score = new_count * 0.1
    finall_new_score = new_score
    document_count = project.documents.count
    file_score = document_count * 0.1
    finall_file_score = file_score
    changeset_count = project.changesets.count
    code_submit_score = changeset_count * 0.3
    finall_code_submit_score = code_submit_score
    board_message_count = 0
    project.boards.each do |board|
      board_message_count += board.messages_count
    end
    topic_score = board_message_count * 0.1
    #finall_topic_score = topic_score
    finall_project_score = finall_issue_score + finall_new_score + finall_file_score + finall_code_submit_score + topic_score
    format("%.2f",finall_project_score)
  end

  #获取指定作业的参与人员
  #返回结果：张三、李四、王五
  def homework_user_of_homework homework,is_teacher
    homework_users = ""
    homework.users.each do |user|
      homework_users = homework_users + (is_teacher ? (user.lastname + user.firstname) : user.login)
      if user != homework.users.last
        homework_users = homework_users + "、"
      end
    end
    return homework_users
  end

  def get_courses_by_tag(tag_name)
    Course.tagged_with(tag_name).order('updated_at desc')
  end

  #课程实践年份下拉框
  def course_time_option year
    type = []
    now_year = year.nil? ? Time.now.year : (Time.now.year <= year ? Time.now.year : year)
    for i in (now_year..now_year + 10)
      option = []
      option << i
      option << i
      type << option
    end
    type
  end

  #课程课时下拉框
  def course_term_option
    type = []
    option1 = []
    option1 << l(:label_spring)
    option1 << l(:label_spring)
    option2 = []
    option2 << l(:label_autumn)
    option2 << l(:label_autumn)
    type << option1
    type << option2
    type
  end

  def cur_course_term
    month = Time.now.month
    if month >= 9 || month < 3
      term = "秋季学期"
    else
      term = "春季学期"
    end
    term
  end

  def course_in_current_or_next_term course
    is_current_term = false
    is_next_term = false
    if course.time == Time.now.year && course.term == cur_course_term
      is_current_term = true
    end
    if cur_course_term == "秋季学期" && course.time == (Time.now.year + 1) && course.term == "春季学期"
      is_next_term = true
    elsif cur_course_term == "春季学期" && course.time == Time.now.year && course.term == "秋季学期"
      is_next_term = true
    end
    is_current_term || is_next_term
  end

  #获取课程动态
  def get_course_activity courses, activities
    @course_ids=activities.keys()

    days = Setting.activity_days_default.to_i
    date_to ||= Date.today + 1
    date_from = date_to - days-1.years

    #file_count
    Attachment.where(container_id: @course_ids, container_type: Course).where("created_on>?", date_from).each do |attachment|
      activities[attachment.container_id]+=1
    end

    #message_count
    Board.where(course_id: @course_ids).each do |board|
#      activities[board.course_id]+=1
      activities[board.course_id]+=board.messages.where("updated_on>?", date_from).count
    end

    #news
    News.where(course_id: @course_ids).where("created_on>?",date_from).each do |news|
      activities[news.course_id]+=1
    end

    # 动态数 + 1 ( 某某创建了该课程 )
    activities.each_pair { |key, value| activities[key] = value + 1 }
    return activities
  end

end
