class GraduationTask < ApplicationRecord
  # task_type 1: 普通作业  2：分组作业
  # status 0：未发布  1：已发布  2：评阅中  3：交叉评阅
  # comment_status 1：随机分配  2：指导老师手动分配  3：答辩组内老师互评  4：答辩组间老师互评

  belongs_to :course, counter_cache: true
  belongs_to :user

  has_many :journals_for_messages, as: :jour, dependent: :destroy
  has_many :praise_tread, as: :praise_tread_object, dependent: :destroy
  has_many :course_acts, class_name: 'CourseActivity', as: :course_act, dependent: :destroy
  has_many :tidings, as: :container, dependent: :destroy

  has_many :attachments, as: :container, dependent: :destroy

  has_many :graduation_work_comment_assignations, dependent: :destroy
  # has_many :formal_graduation_work_comment_assignations, -> { formal }, class_name: "GraduationWorkCommentAssignation"
  # has_many :temporary_graduation_work_comment_assignations, -> { temporary }, class_name: "GraduationWorkCommentAssignation"
  # has_many :delete_graduation_work_comment_assignations, -> { temporary_delete }, class_name: "GraduationWorkCommentAssignation"
  #
  has_many :graduation_task_group_assignations, dependent: :destroy
  # has_many :formal_graduation_task_group_assignations, -> { formal }, class_name: "GraduationTaskGroupAssignation"
  # has_many :temporary_graduation_task_group_assignations, -> { temporary }, class_name: "GraduationTaskGroupAssignation"
  # has_many :delete_graduation_task_group_assignations, -> { temporary_delete }, class_name: "GraduationTaskGroupAssignation"

  has_many :graduation_works, -> { where("is_delete = 0") }
  has_many :score_graduation_works, -> { where("is_delete = 0 and work_status != 0").order("work_score desc") }, class_name: "GraduationWork"
  has_many :graduation_work_scores

  belongs_to :gtask_bank, optional: true

  validates :name, length: { maximum: 60, too_long: "不能超过60个字符" }
  validates :description, length: { maximum: 5000, too_long: "不能超过5000个字符" }

  # 未提交
  scope :unfinished, -> {where(status: 0)}
  # 按时提交
  scope :finished, -> {where(status: 1)}
  # 延迟提交
  scope :delay_finished, -> {where(status:  2)}

  #已发布的
  scope :task_published, -> {where("publish_time <= ?",Time.now)}


  def user_work user_id
    work = self.graduation_works.find_by(user_id: user_id) || GraduationWork.create!(graduation_task_id: id, user_id: user_id)
  end

  def task_type_name
    task_type == 1 ? "普通作业" : "分组作业"
  end

  # 是否有学生提交过作品
  def student_commit_works
    graduation_works.has_committed.count > 0
  end

  # 是否有学生关联了项目
  def student_relate_projects
    task_type == 2 && graduation_works.where("project_id != 0").count > 0
  end

  # 是否发布
  def published?
    self.publish_time.present? && self.publish_time < Time.now
  end

  # 答辩组互评分配
  def task_assign_group group_id
    graduation_task_group_assignations.find_by(graduation_group_id: group_id)
  end

  def create_work_list
    str = ""
    self.course.students.each do |student|
      str += "," if str != ""
      str += "(#{self.id}, #{student.user_id}, #{self.course_id}, '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
    end
    if str != ""
      sql = "insert into graduation_works (graduation_task_id, user_id, course_id, created_at, updated_at) values" + str
      ActiveRecord::Base.connection.execute sql
    end
  end

  #课程动态公共表记录
  def act_as_course_activity
    if self.course_acts.size == 0
      self.course_acts << CourseActivity.new(user_id: self.user_id, course_id: self.course_id)
    end
  end

  # 是否提交了作品
  def has_commit_work user_id
    work = self.graduation_works.find_by(user_id: user_id)
    work.present? && work.work_status != 0
  end

  # 任务已评数 user_id: 对应老师的id
  def comment_count(user_id)
    course = self.course
    # 如果有分班，则取此老师对应分班的已评数，没有分班，则取所有的
    course_group_ids = course.group_course_power(user_id)
    sql =
        if course_group_ids.count > 0
          %Q{
            SELECT count(distinct graduation_work_id) cnt FROM graduation_work_scores WHERE reviewer_role IN(1,2) AND graduation_work_id
              IN(SELECT id FROM graduation_works WHERE graduation_task_id = #{self.id} AND user_id
                 IN(SELECT user_id FROM course_members WHERE role = 4 AND course_group_id
                    IN(#{course_group_ids.join(",")})
                   )
                )
          }
        else
          %Q{
            SELECT COUNT(distinct graduation_work_id) cnt FROM graduation_works gw
              JOIN graduation_work_scores gwc ON gw.id = gwc.graduation_work_id
            WHERE reviewer_role IN(1,2) AND gw.graduation_task_id = #{self.id}
          }
        end
    GraduationWorkScore.find_by_sql(sql).first.try(:cnt).to_i
  end

  # 任务未评数
  def uncomment_count(user_id)
    user_ids = course.teacher_group_user_ids user_id
    self.graduation_works.where(user_id: user_ids).count - self.comment_count(user_id)
  end

  # 任务未提交数
  def unfinished_count user_id
    course_group_ids = course.group_course_power(user_id)
    if course_group_ids.count > 0
      sql = %Q{
                SELECT count(*) cnt FROM graduation_works gw WHERE work_status = 0 AND gw.graduation_task_id = #{self.id} AND gw.user_id
                  IN( SELECT user_id FROM course_members WHERE role = 4 AND course_group_id
                    IN(#{course_group_ids.join(",")})
                    )
              }
      GraduationWork.find_by_sql(sql).first.try(:cnt)
    else
      self.graduation_works.where(work_status: 0).count
    end
  end

  # 任务按时提交数
  def finished_count(user_id)
    course = self.course
    course_group_ids = course.group_course_power(user_id)
    if course_group_ids.count > 0
      sql = %Q{
                SELECT count(*) cnt FROM graduation_works gw WHERE work_status = 1 AND gw.graduation_task_id = #{self.id} AND gw.user_id
                  IN( SELECT user_id FROM course_members WHERE role = 4 AND course_group_id
                    IN(#{course_group_ids.join(",")})
                    )
              }
      GraduationWork.find_by_sql(sql).first.try(:cnt)
    else
      self.graduation_works.where(work_status: 1).count
    end
  end

  def delay_finished_count(user_id)
    course = self.course
    course_group_ids = course.group_course_power(user_id)
    if course_group_ids.count > 0
      sql = %Q{
                SELECT count(*) cnt FROM graduation_works gw WHERE work_status = 2 AND gw.graduation_task_id = #{self.id} AND gw.user_id
                  IN( SELECT user_id FROM course_members WHERE role = 4 AND course_group_id
                    IN(#{course_group_ids.join(",")})
                    )
              }
      GraduationWork.find_by_sql(sql).first.try(:cnt)
    else
      self.graduation_works.where(work_status: 2).count
    end
  end



  # 是否具有分组
  def have_grouping?
    self.task_type == 2
  end

end
