#coding=utf-8
class HomeworkService
   include CoursesHelper
   include AttachmentsHelper
   include ApplicationHelper
   include WordsHelper
   include ApiHelper
   include HomeworkAttachHelper
   include CoursesHelper
   
  # 作业详情（老师才显示启动匿评，学生不显示 ）
  # many_times 第几次（作业）
  # state=0 启动匿评
  # state=1 关闭匿评
  # state=2 匿评结束
  def show_homework params
    @bid = HomeworkCommon.find(params[:id])
    course  = @bid.course
    author = @bid.user.lastname + @bid.user.firstname
    many_times = course.homework_commons.index(@bid) + 1
    name = @bid.name
    homework_count = @bid.student_works.count  #已提交的作业数量
    #student_questions_count =  @bid.journals_for_messages.where('m_parent_id IS NULL').count
    description = @bid.description
    #if is_course_teacher(User.current, course) && @bid.open_anonymous_evaluation == 1 && @bid.homeworks.count >= 2
    state = @bid.homework_detail_manual.comment_status
    #end
    open_anonymous_evaluation = @bid.homework_type
    #jours = @bid.journals_for_messages.where('m_parent_id IS NULL').order('created_on DESC')
    {:course_name => course.name,:course_id => course.id,:id => @bid.id, :author => @bid.user,:author_real_name =>author,  :homework_times => many_times, :homework_name => name, :homework_count => homework_count,:student_questions_count => 0,
     :description => description, :homework_state => state,:open_anonymous_evaluation => open_anonymous_evaluation,:created_on => @bid.created_at,:deadline => @bid.end_time,:jours => nil}
  end
  
  # 启动作业匿评前提示信息
  def alert_homework_anonymous_comment params
    @bid = Bid.find params[:id]
    @course = @bid.courses.first
    if @bid.comment_status == 0
      @totle_size = searchStudent(@course).size
      @cur_size = @bid.homeworks.size
    elsif @bid.comment_status == 1
      @totle_size = 0
      @bid.homeworks.map { |homework| @totle_size += homework.homework_evaluations.count}
      teachers = "("
      teacher_members = searchTeacherAndAssistant(@course)
      teacher_members.each do |member|
        if member == teacher_members.last
          teachers += member.user_id.to_s + ")"
        else
          teachers += member.user_id.to_s + ","
        end
      end
      @cur_size = 0
      @bid.homeworks.map { |homework| @cur_size += homework.rates(:quality).where("seems_rateable_rates.rater_id not in #{teachers}").count}
    end
    @percent = format("%.2f",(@cur_size.to_f / ( @totle_size == 0 ? 1 : @totle_size)) * 100)
    [@bid,@totle_size,@cur_size,@percent]
  end

  # 启动匿评 操作 逻辑改变，暂不删除
  # #启动匿评
  # #statue 1:启动成功，2：启动失败，作业总数大于等于2份时才能启动匿评，3:已开启匿评，请务重复开启
  # def start_anonymous_comment params,current_user
  #   @bid = Bid.find(params[:id])
  #   @course = @bid.courses.first
  #   unless is_course_teacher(current_user,@course) || current_user.admin?
  #     @statue = 4
  #     raise '403'
  #   end
  #   if(@bid.comment_status == 0)
  #     homeworks = @bid.homeworks
  #     if(homeworks && homeworks.size >= 2)
  #       homeworks.each_with_index do |homework, index|
  #         user = homework.user
  #         n = @bid.evaluation_num
  #         n = n < homeworks.size ? n : homeworks.size - 1
  #         assigned_homeworks = get_assigned_homeworks(homeworks, n, index)
  #         assigned_homeworks.each do |h|
  #           @homework_evaluation = HomeworkEvaluation.new(user_id: user.id, homework_attach_id: h.id)
  #           @homework_evaluation.save
  #         end
  #       end
  #       @bid.update_column('comment_status', 1)
  #       @statue = 1
  #     else
  #       @statue = 2
  #     end
  #   else
  #     @statue = 3
  #   end
  #   @statue
  # end
  # #关闭匿评
  # def stop_anonymous_comment params,current_user
  #   @bid = Bid.find(params[:id])
  #   @course = @bid.courses.first
  #   unless is_course_teacher(current_user,@course) || current_user.admin?
  #     raise '403'
  #   end
  #   @bid.update_column('comment_status', 2)
  # end

  # 开启匿评
  #statue 1:启动成功，2：启动失败，作业总数大于等于2份时才能启动匿评，3:已开启匿评，请务重复开启,4:没有开启匿评的权限
   def start_anonymous_comment params,current_user
     homework = HomeworkCommon.find(params[:homework_id])
     return {:status=> 4}  unless current_user.admin? || current_user.allowed_to?(:as_teacher,Course.find(params[:course_id]))
     return {:status=>5}   if Time.parse(homework.end_time.to_s).strftime("%Y-%m-%d") >= Time.now.strftime("%Y-%m-%d")
     homework_detail_manual = homework.homework_detail_manual
     if homework_detail_manual.comment_status == 1
       student_works = homework.student_works
       if student_works && student_works.size >=2
         student_works.each_with_index do |work, index|
           user = work.user
           n = homework_detail_manual.evaluation_num
           n = n < student_works.size ? n : student_works.size - 1
           assigned_homeworks = get_assigned_homeworks(student_works, n, index)
           assigned_homeworks.each do |h|
             student_works_evaluation_distributions = StudentWorksEvaluationDistribution.new(user_id: user.id, student_work_id: h.id)
             student_works_evaluation_distributions.save
           end
         end
         homework_detail_manual.update_column('comment_status', 2)
         statue = 1
       else
         statue = 2
       end
     else
       statue = 3
     end
     {:status => statue}
   end

   def get_assigned_homeworks(student_works, n, index)
     student_works += student_works
     student_works[index + 1 .. index + n]
   end

   def stop_anonymous_comment  params,current_user
     homework = HomeworkCommon.find(params[:homework_id])
     homework_detail_manual = homework.homework_detail_manual
     homework_detail_manual.update_column('comment_status', 3)

     work_ids = "(" << homework.student_works.map(&:id).join(",") << ")"
     homework.student_works.each do |student_work|
       absence_penalty_count = student_work.user.student_works_evaluation_distributions.where("student_work_id IN #{work_ids}").count - student_work.user.student_works_scores.where("student_work_id IN #{work_ids}").count
       student_work.absence_penalty = absence_penalty_count > 0 ? absence_penalty_count * homework_detail_manual.absence_penalty : 0
       student_work.save
     end
   end
   
  # 匿评作品详情
  # attachs 该作品的所有附件
  # filename 文件名
  # filedesc 文件描述
  def anonymous_works_show(params,current_user)
    @homework = HomeworkAttach.find(params[:id])
    @bid = @homework.bid
    @course = @bid.courses.first
    if current_user.admin? || current_user.member_of_course?(@course)
      @stars_reates = @homework.rates(:quality)
      @is_teacher = is_course_teacher current_user,@course
      @has_evaluation = @stars_reates.where("rater_id = #{current_user.id} and is_teacher_score=#{@is_teacher ? 1 : 0}").first
      @m_score = @has_evaluation.nil? ? 0 : @has_evaluation.stars
      @teacher_stars = @stars_reates.where("is_teacher_score = 1") #老师评分列表
      @student_stars = @stars_reates.where("is_teacher_score = 0") #学生评分列表
      @is_anonymous_comments = @bid.comment_status == 1 && !@homework.users.include?(current_user) && @homework.user != current_user && !@is_teacher #判断是不是匿评(开启匿评，当前用户不是作业的创建者或者参与者，不是老师)
      jours = @homework.journals_for_messages.where("is_comprehensive_evaluation = 3 or is_comprehensive_evaluation is null").order("created_on DESC")#jours留言 is null条件用以兼容历史数据
      #@jour = paginateHelper jours,5 #留言
      @cur_page = params[:cur_page] || 1
      @cur_type = params[:cur_type] || 5
      teacher_stars_json_like = stars_to_json_like(@teacher_stars,true,@homework,true)
      student_stars_json_like = stars_to_json_like(@student_stars,false,@homework,(false || @is_teacher))
    else
      raise '403'
    end

    [@homework,{:is_teacher => @is_teacher,:m_score => @m_score,:jours => jours,:teacher_stars => teacher_stars_json_like,
     :student_stars => student_stars_json_like,:is_anonymous_comments => @is_anonymous_comments,:cur_type => @cur_type,:cur_page => @cur_page}]
    #name  = @homework.name
    #desc = @homework.description
    #datetime = @homework.created_at
    #files = []
    #unless @homework.attachments.empty?
    #  attachs = @homework.attachments
    #  attachs.each do |attach|
    #    filename = attach.filename
    #    filedesc = attach.description unless attach.description.blank?
    #  end
    #end

    #{:name => name, :description => desc, :datetime => format_time(datetime)}
  end
  
  #作品打分/留言
  def add_score_and_jour params,current_user
    @is_teacher,@is_anonymous_comments,@m_score = params[:is_teacher]=="true",params[:is_anonymous_comments]=="true",params[:stars_value]
    @cur_page,@cur_type = params[:cur_page] || 1,params[:cur_type] || 5
    @homework = HomeworkAttach.find(params[:homework_id])
    comment_status = @homework.bid.comment_status
    if @is_anonymous_comments && comment_status == 0
      raise '尚未开启匿评!'
    end
    if @is_anonymous_comments && ((@m_score.nil? || @m_score.blank?) || !(params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != ""))
      raise '您尚未打分或评论！'
    end
    #保存评分
    homework = @homework
    is_teacher = @is_teacher ? 1 : 0
    #保存评分@homework.rate(@m_score.to_i,User.current.id,:quality, (@is_teacher ? 1 : 0))
    if @m_score
      rate = @homework.rates(:quality).where(:rater_id => current_user.id, :is_teacher_score => is_teacher).first
      if rate
        rate.stars = @m_score
        rate.save!
      else
        @homework.rates(:quality).new(:stars => @m_score, :rater_id => current_user.id, :is_teacher_score => is_teacher).save!
      end

      if homework.is_teacher_score == 0
        if is_teacher == 1
          homework.score = @m_score
          homework.is_teacher_score = 1
        else
          sql = "SELECT AVG(stars) as stars FROM seems_rateable_rates WHERE rateable_type = 'HomeworkAttach' AND rateable_id = #{homework.id}"
          score= HomeworkAttach.find_by_sql(sql).first.stars
          homework.score = score
        end
      else
        if is_teacher == 1
          homework.score = @m_score
          homework.is_teacher_score = 1
        end
      end
      homework.save!
    end
    #保存评论
    @is_comprehensive_evaluation = @is_teacher ? 1 : (@is_anonymous_comments ? 2 : 3) #判断当前评论是老师评论？匿评？留言
    if params[:new_form] && params[:new_form][:user_message] && params[:new_form][:user_message] != ""  #有没有留言
      @homework.addjours current_user.id, params[:new_form][:user_message],0,@is_comprehensive_evaluation
    end
  end
  
  #作品留言列表
  def get_works_jours_list params
    @bid = Bid.find params[:id]
    @user = @bid.author
    @jours = @bid.journals_for_messages.where('m_parent_id IS NULL').order('created_on DESC')
    @jour = paginateHelper @jours,10
    @jour
  end
  
  # 学生匿评留言列表
  def anonymous_jour_list params
    #jours留言 is null条件用以兼容历史数据
    jours = @homework.journals_for_messages.where("is_comprehensive_evaluation = 3 or is_comprehensive_evaluation is null").order("created_on DESC")
    jours.each do |jour|
      user = jour.user
      img_url = url_to_avatar(jour.user)
      datetime = jour.created_on
      content = jour.notes
    end
    {:user => 'user', :img_url => 'img_url', :datetime => 'datetime', :content => 'content'}
  end
 
  # 匿评教师留言/回复列表
  # 图像img_url = url_to_avatar(user)
  # massage_user 留言者 
  # parent_jour被回复的留言
  def teacher_jour_list params
    @homework = HomeworkAttach.find(params[:homework_id])
    @stars_reates = @homework.rates(:quality)
    @teacher_stars = @stars_reates.where("rater_id in (#{teachers})") #老师评分列表  
    @teacher_stars.each do |ts|
      #留言参数
      jour = get_homework_review @homework,true,massage_user 
      massage_content = jour.notes unless jour.nil?  
      massage_user = ts.rater  
      massage_score = ts.stars   
      #回复参数
      anonymous_repy(jour)
    end
  end

   # 发布作业
   def create_home_work params,current_user
     @bid = Bid.new
     @bid.name = params[:work_name]
     @bid.description = params[:work_desc]
    # @bid.is_evaluation = params[:is_blind_appr]
     @bid.evaluation_num = params[:blind_appr_num]
     @bid.open_anonymous_evaluation = params[:is_blind_appr]
     @bid.reward_type = 3
     @bid.deadline = params[:work_deadline]
     @bid.budget = 0
     @bid.author_id = current_user.id
     @bid.commit = 0
     @bid.homework_type = 1
     # @bid.
     if @bid.save
       HomeworkForCourse.create(:course_id => params[:course_id], :bid_id => @bid.id)
       unless @bid.watched_by?(current_user)
         @bid.add_watcher(current_user)
       end
     end
   end
  
  # 学生匿评列表
  def student_jour_list params
    @homework = HomeworkAttach.find(params[:homework_id])
    @stars_reates = @homework.rates(:quality)
    @student_stars = @stars_reates.where("rater_id not in (#{teachers})") #学生评分列表
    @student_stars.each do |ss|
      #留言参数
      massage_user = ss.rater
      jour = get_homework_review @homework,false,massage_user    
      massage_score = ss.stars
      massage_content = jour.notes unless jour.nil?
      #回复参数
      anonymous_repy(jour)
    end
  end
  
  def anonymous_repy jour
    fetch_user_leaveWord_reply(jour).each do |fulr|
        parent_jour = JournalsForMessage.where("id = #{fulr.m_reply_id}").first
        reply_name = fulr.user.name
        parent_name = parent_jour.user.name if parent_jour
        reply_content = fulr.notes
        reply_time = fulr.created_on
      end
  end

  #我的作品列表
  def my_homework_list params,current_user
    @user = User.find(params[:user_id])
    if !current_user.admin? && !@user.active?
      raise '404'
      return
    end
    if current_user == @user || current_user.admin?
      membership = @user.coursememberships.all
    else
      membership = @user.coursememberships.all(:conditions => Course.visible_condition(current_user))
    end
    membership.sort! {|older, newer| newer.created_on <=> older.created_on }
    course_list = []
    membership.each do |mp|
      my_homeworks = []
      mp.course.homeworks.each do |bid|
        #hw = bid.homeworks.where("user_id = #{current_user.id}")
        @bid = bid
        course  = @bid.courses.first
        author = @bid.author.lastname + @bid.author.firstname
        many_times = course.homeworks.index(@bid) + 1
        name = @bid.name
        homework_count = @bid.homeworks.count  #已提交的作业数量
        student_questions_count = @bid.journals_for_messages.where('m_parent_id IS NULL').count
        description = @bid.description
                                               #if is_course_teacher(User.current, course) && @bid.open_anonymous_evaluation == 1 && @bid.homeworks.count >= 2
        state = @bid.comment_status
                                               #end
        open_anonymous_evaluation = @bid.open_anonymous_evaluation

        my_homeworks << {:course_name => course.name,:id => @bid.id, :author => @bid.author,:author_real_name =>author,  :homework_times => many_times, :homework_name => name, :homework_count => homework_count,:student_questions_count => student_questions_count,
                         :description => description, :homework_state => state,:open_anonymous_evaluation => open_anonymous_evaluation}
      end
      if mp.course.homeworks.count != 0
        course_list << {:course => mp.course,:img_url => url_to_avatar(mp.course),:my_homework => my_homeworks,:current_user_is_member => current_user.member_of_course?(mp.course),:current_user_is_teacher => is_course_teacher(current_user,mp.course)}
      end
    end
    course_list
  end
end