#coding=utf-8

namespace :homework_publishtime do
  desc "start publish homework and end homework"

  # 作业的分班设置时间
  def homework_group_setting homework, group_id
    setting = nil
    if homework.homework_group_settings.where(course_group_id: group_id).first
      setting = homework.homework_group_settings.where(course_group_id: group_id).first
    else
      setting = homework
    end
    setting
  end

  task :publish => :environment do
    Rails.logger.info("log--------------------------------homework_publish start")
    homework_commons = HomeworkCommon.includes(:homework_detail_manual).where(homework_detail_manuals: {comment_status: 0})
                           .where("publish_time is not null and publish_time <= '#{Time.now}'")
    homework_commons.each do |homework|
      homework_detail_manual = homework.homework_detail_manual
      homework_detail_manual.update_column('comment_status', 1)
      # 统一设置的作业在这发消息，非统一设置的只给有全部分班权限的老师发
      if homework.unified_setting
        # HomeworkPublishUpdateWorkStatusJob.perform_later(nil, homework.id)
        HomeworkCommonPushNotifyJob.perform_later(homework.id, nil)
      else
        course = homework.course
        teachers = course.teachers.where.not(id: course.teacher_course_groups.select(:course_member_id))

        tid_str = ""
        teachers.find_each do |member|
          tid_str += "," if tid_str != ""
          tid_str += "(#{member.user_id}, #{homework.user_id}, #{homework.id}, 'HomeworkCommon', #{homework.id}, 'HomeworkPublish',
                      #{course.id}, 'Course', 0, 'HomeworkCommon', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}',
                      '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
        end

        if tid_str != ""
          tid_sql = "insert into tidings (user_id, trigger_user_id, container_id, container_type, parent_container_id,
                     parent_container_type, belong_container_id, belong_container_type, viewed, tiding_type, created_at,
                     updated_at) values" + tid_str
          ActiveRecord::Base.connection.execute tid_sql
        end
      end

      CourseActivity.create(user_id: homework.user_id, course_id: homework.course_id, course_act: homework) if !homework.course_act.present?
    end

    # 分组设置发布时间的作业
    homework_group_settings = HomeworkGroupSetting.where("publish_time < ? and publish_time > ?", Time.now + 300, Time.now - 300)
    homework_group_settings.each do |homework_group|
      homework = homework_group.homework_common
      if homework.present?
        # HomeworkPublishUpdateWorkStatusJob.perform_now([homework_group.id], homework.id)
        HomeworkCommonPushNotifyJob.perform_later(homework.id, [homework_group.course_group_id])
      end
    end
    Rails.logger.info("log--------------------------------homework_publish end")
  end

  task :end => :environment do
    Rails.logger.info("log--------------------------------homework_publish_end start")
    # 提交中的实训作业,截止时间大于当前时间往前推15分钟且小于等于当前时间,状态是提交中的实训作业
    homework_commons = HomeworkCommon.includes(:homework_detail_manual).where(homework_detail_manuals: {comment_status: 1})
                           .where("homework_type = 4 and end_time <= ? and end_time > ?", Time.now, Time.now - 600)
    homework_commons.each do |homework|
      # homework_challenge_settings = homework.homework_challenge_settings
      # homework.homework_detail_manual.update_column("comment_status", 2)

      if homework.allow_late
        if homework.unified_setting
          student_works = homework.student_works.where("work_status != 0")
          # none_student_works = homework.student_works.where("work_status = 0")
        else
          setting = homework.homework_group_settings.where(end_time: homework.end_time)
          unless setting.blank?
            users = homework.course.students.where(course_group_id: setting.pluck(:course_group_id))
            student_works = homework.student_works.where("work_status != 0").where(user_id: users.pluck(:user_id))
            # none_student_works = homework.student_works.where("work_status = 0 and user_id in #{user_ids}")
          end
        end

        student_works.joins(:myshixun).where("myshixuns.status != 1").update_all(late_penalty: homework.late_penalty, work_status: 2) if student_works.present?

      else
        HomeworkEndUpdateScoreJob.perform_later(homework.id)
        # HomeworksService.new.update_student_eff_score homework
      end

=begin
      student_works.each do |student_work|
        member = Member.find_by_sql("select course_group_id from members where course_id = #{homework.course_id} and
                  user_id = #{student_work.user_id}").first
        setting_time = homework_group_setting homework, member.try(:course_group_id)
        games = student_work.myshixun.games.where(:challenge_id => homework_challenge_settings.map(&:challenge_id))
        unless games.select{|game| game.status == 2}.size == games.size
          student_work.work_status = 2
          student_work.late_penalty = homework.late_penalty
          score = student_work.final_score.to_i - student_work.late_penalty
          student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f)
          student_work.cost_time = homework.allow_late ? student_work.cost_time : (Time.now.to_i - setting_time.publish_time.to_i)
          sql = "update student_works set late_penalty = #{student_work.late_penalty}, work_status = 2, work_score =
                #{student_work.work_score}, cost_time = #{student_work.cost_time} where id = #{student_work.id}"
          ActiveRecord::Base.connection.execute sql
        end
        # myshixun = student_work.myshixun
        # final_score = 0
        # homework_challenge_settings.each do |setting|
        #   game = myshixun.games.where(:challenge_id => setting.challenge_id, :status => 2).first
        #   unless game.nil?
        #     final_score += homework.homework_detail_manual.answer_open_evaluation ? setting.score : (game.final_score >= 0 ?
        # setting.score : 0)
        #   end
        # end
      end
=end
=begin
      none_student_works.each do |student_work|
        myshixun = Myshixun.where(:shixun_id => homework.homework_commons_shixuns.shixun_id, :user_id => student_work.user_id).first
        if myshixun
          student_work.update_attributes(:work_status => myshixun.is_complete? ? 1 : 2, :late_penalty => myshixun.is_complete? ? 0 :
          homework.late_penalty, :commit_time => myshixun.created_at, :update_time => myshixun.updated_at, :myshixun_id => myshixun.id)
          student_work.late_penalty = myshixun.is_complete? ? 0 : homework.late_penalty
          final_score = 0
          homework_challenge_settings.each do |setting|
            game = myshixun.games.where(:challenge_id => setting.challenge_id, :status => 2).first
            unless game.nil?
              final_score += homework.homework_detail_manual.answer_open_evaluation ? setting.score : (game.final_score >= 0 ?
              setting.score : 0)
            end
          end
          student_work.update_column("final_score", format("%.2f",final_score.to_f))
          score = student_work.final_score - student_work.late_penalty
          student_work.update_column("work_score", format("%.2f",(score < 0 ? 0 : score).to_f)) if score
        end
      end
=end
    end
    all_homework_commons = HomeworkCommon.includes(:homework_detail_manual).where(homework_detail_manuals: {comment_status: 1})
                               .where("homework_type = 4 and end_time > '#{Time.now}'")
    homework_ids = all_homework_commons.blank? ? "(-1)" : "(" + all_homework_commons.map(&:id).join(",") + ")"
    HomeworkGroupSetting.where("end_time <= ? and end_time > ? and homework_common_id in #{homework_ids}", Time.now, Time.now - 600).each do |homework_setting|
      homework = homework_setting.homework_common

      if homework.allow_late
        # homework_challenge_settings = homework.homework_challenge_settings

        users = homework.course.students.where(:course_group_id => homework_setting.course_group_id)
        student_works = homework.student_works.where("work_status != 0").where(user_id: users.pluck(:user_id))
        student_works.joins(:myshixun).where("myshixuns.status != 1").update_all(late_penalty: homework.late_penalty) if student_works.present?
      else
        # HomeworksService.new.update_student_eff_score homework  # 分班设置的不需要另外算效率分
      end

      # none_student_works = homework.student_works.where("work_status = 0 and user_id in #{user_ids}")

=begin
      student_works.each do |student_work|
        games = student_work.myshixun.games.where(:challenge_id => homework_challenge_settings.map(&:challenge_id))
        unless games.select{|game| game.status == 2}.size == games.size
          student_work.late_penalty = homework.late_penalty
          student_work.work_status = 2
          score = student_work.final_score.to_i - student_work.late_penalty
          student_work.work_score = format("%.2f",(score < 0 ? 0 : score).to_f)
          student_work.cost_time = homework.allow_late ? student_work.cost_time : (Time.now.to_i - homework_setting.publish_time.to_i)
          sql = "update student_works set late_penalty = #{student_work.late_penalty}, work_status = 2, work_score =
                #{student_work.work_score} where id = #{student_work.id}"
          ActiveRecord::Base.connection.execute sql
        end
        # myshixun = student_work.myshixun
        # final_score = 0
        # homework_challenge_settings.each do |setting|
        #   game = myshixun.games.where(:challenge_id => setting.challenge_id, :status => 2).first
        #   unless game.nil?
        #     final_score += homework.homework_detail_manual.answer_open_evaluation ? setting.score : (game.final_score >= 0 ?
        #               setting.score : 0)
        #   end
        # end
      end
=end
=begin
      none_student_works.each do |student_work|
        myshixun = Myshixun.where(:shixun_id => homework.homework_commons_shixuns.shixun_id, :user_id => student_work.user_id).first
        if myshixun
          student_work.update_attributes(:work_status => myshixun.is_complete? ? 1 : 2, :late_penalty => myshixun.is_complete? ? 0 : homework.late_penalty, :commit_time => myshixun.created_at, :update_time => myshixun.updated_at, :myshixun_id => myshixun.id)
          student_work.late_penalty = myshixun.is_complete? ? 0 : homework.late_penalty
          final_score = 0
          homework_challenge_settings.each do |setting|
            game = myshixun.games.where(:challenge_id => setting.challenge_id, :status => 2).first
            unless game.nil?
              final_score += homework.homework_detail_manual.answer_open_evaluation ? setting.score : (game.final_score >= 0 ? setting.score : 0)
            end
          end
          student_work.update_column("final_score", format("%.2f",final_score.to_f))
          score = student_work.final_score - student_work.late_penalty
          student_work.update_column("work_score", format("%.2f",(score < 0 ? 0 : score).to_f)) if score
        end
      end
=end
    end
    Rails.logger.info("log--------------------------------homework_publish_end end")
  end

  task :archive => :environment do
    Rails.logger.info("log--------------------------------homework_archive start")
    homework_commons = HomeworkCommon.joins(:homework_detail_manual).where("homework_type = 4 and allow_late = 1 and
                          late_time <= ? and late_time > ? and homework_detail_manuals.comment_status != 6", Time.now, Time.now - 600)
    homework_commons.each do |homework|
      # HomeworksService.new.update_student_eff_score homework
      HomeworkEndUpdateScoreJob.perform_later(homework.id)

=begin
      homework_detail_manual = homework.homework_detail_manual
      homework_detail_manual.update_column('comment_status', 6)
      if homework.homework_type == 4 && homework.allow_late
        homework_challenge_settings = homework.homework_challenge_settings

        homework.student_works.where("work_status != 0").each do |student_work|
          myshixun = student_work.myshixun
          final_score = 0
          homework_challenge_settings.each do |setting|
            game = myshixun.games.where(:challenge_id => setting.challenge_id, :status => 2).first
            unless game.nil?
              final_score += homework.homework_detail_manual.answer_open_evaluation ? setting.score : (game.final_score >= 0 ? setting.score : 0)
            end
          end
          student_work.update_column("final_score", format("%.2f",final_score.to_f))
          score = student_work.final_score - student_work.late_penalty
          student_work.update_column("work_score", format("%.2f",(score < 0 ? 0 : score).to_f))
        end

        homework.student_works.where("work_status = 0").each do |student_work|
          myshixun = Myshixun.where(:shixun_id => homework.homework_commons_shixuns.shixun_id, :user_id => student_work.user_id).first
          if myshixun
            student_work.update_attributes(:work_status => 2, :late_penalty => homework.late_penalty, :commit_time => myshixun.created_at, :update_time => myshixun.updated_at, :myshixun_id => myshixun.id)
            student_work.late_penalty = homework.late_penalty
            final_score = 0
            homework_challenge_settings.each do |setting|
              game = myshixun.games.where(:challenge_id => setting.challenge_id, :status => 2).first
              unless game.nil?
                final_score += homework.homework_detail_manual.answer_open_evaluation ? setting.score : (game.final_score >= 0 ? setting.score : 0)
              end
            end
            student_work.update_column("final_score", format("%.2f",final_score.to_f))
            score = student_work.final_score - student_work.late_penalty
            student_work.update_column("work_score", format("%.2f",(score < 0 ? 0 : score).to_f)) if score
          end
        end
      end
=end
    end
    Rails.logger.info("log--------------------------------homework_archive end")
  end
end