class Poll < ApplicationRecord
  belongs_to :course, counter_cache: true
  belongs_to :user
  belongs_to :exercise_bank, optional: true

  # belongs_to :exercise_bank
  has_many :poll_questions,dependent: :delete_all
  has_many :poll_users, -> { where("is_delete != 1") }, :dependent => :delete_all
  has_many :users, :through => :poll_users #该文件被哪些用户提交答案过
  has_many :poll_group_settings, :dependent => :delete_all
  has_many :published_settings, -> { poll_group_published }, class_name: "PollGroupSetting"
  has_many :course_acts, class_name: 'CourseActivity', as: :course_act, dependent: :delete_all

  has_many :tidings, as: :container, dependent: :delete_all

  scope :publish_or_not, -> { where("polls_status > ? ",1)}
  scope :only_public, -> {where("is_public = ?",true)}
  scope :public_or_unset, -> { where("unified_setting = ?",true) }
  scope :poll_by_ids, lambda { |ids| where(id: ids) unless ids.blank? }
  scope :poll_by_status, lambda { |s| where(polls_status: s) unless s.blank? }
  scope :poll_group_ended, -> {where("end_time is NOT NULL AND end_time <= ?",Time.now)}

  scope :poll_search, lambda { |keywords|
    where("polls_name LIKE ?", "%#{keywords}%") unless keywords.blank?}

  validates :polls_name, length: { maximum: 60, too_long: "60 characters is the maximum allowed" }

  after_create :create_polls_list

  def create_polls_list
    str = ""
    self.course.students.find_each do |student|
      str += "," if str != ""
      str += "(#{student.user_id},#{self.id}, 0, '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
    end

    if str != ""
      sql = "insert into poll_users (user_id, poll_id, commit_status, created_at, updated_at) values" + str
      ActiveRecord::Base.connection.execute sql
    end
  end

  #获取学生视角的试卷用户
  def get_poll_exercise_users
    if unified_setting  #试卷统一设置
      poll_users
    else
      ex_group_setting_ids = published_settings.pluck(:course_group_id)
      poll_users.joins("join course_members on poll_users.user_id=course_members.user_id").
          where(course_members: {course_group_id: ex_group_setting_ids})
    end
  end

  # 根据是否统一发布获取作业的作品列表
  def all_works
    po_users = unified_setting ? poll_users :
                     poll_users.joins("join course_members on poll_users.user_id=course_members.user_id").
                             where(course_members: {course_group_id: published_settings.pluck(:course_group_id)})
  end

  # 分班权限的老师可见的作品列表
  def all_poll_users user_id
    # member = course.course_member(user_id)
    teacher_course_groups = course.teacher_course_groups.get_user_groups(user_id)
    poll_users = self.all_works
    # 有分班权限的统计管理的分班且已发布的学生情况
    if teacher_course_groups.exists?
      group_ids = teacher_course_groups.pluck(:course_group_id)
      poll_users = poll_users.joins("join course_members on poll_users.user_id=course_members.user_id").
          where(course_members: {course_group_id: group_ids})
    end
    poll_users
  end

  # # 统一设置，为当前老师有权限的分班学生，分班设置，也为当前老师有权限的分班的学生
  # def all_poll_users(user_id)
  #   poll_all_users = poll_users
  #   group_ids = poll_published_ids(user_id)
  #   if group_ids.present?
  #     poll_all_users = poll_all_users.where(user_id: course.students.where(course_group_id: group_ids).select(:user_id).pluck(:user_id).uniq)
  #   end
  #   poll_all_users
  # end

  #当前用户已发布的班级id和试卷分组已发布的班级id的交集
  def poll_published_ids(user_id)
    current_user_groups = course.teacher_course_ids(user_id)
    if unified_setting
      current_user_groups.uniq
      # if course.none_group_count > 0  #有未分班的，则发布到未发布
      #   un_group_ids = [0]
      # else
      #   un_group_ids = []
      # end
      # (current_user_groups + un_group_ids).uniq    #统一设置时，为当前用户的分班id
    else
      ex_group_setting = poll_group_settings.select(:course_group_id).pluck("course_group_id").uniq
      (ex_group_setting & current_user_groups).uniq  #当前用户有权限的已发布的分班id  #非统一设置时，为当前用户有权限的且已发布分班的id
    end
  end

  def get_poll_status(user)
    if course.is_end
      status = 4
    else
      if user.present? && user.student_of_course?(course)
        ex_time = get_poll_times(user_id,false)
        pb_time = ex_time[:publish_time]
        ed_time = ex_time[:end_time]
        if pb_time.present? && ed_time.present? && pb_time <= Time.now && ed_time > Time.now
          status = 2
        elsif ed_time.present? && ed_time <= Time.now
          status = 3
        else
          status  = 1
        end
      else
        status  = polls_status
      end
    end
    status
  end

  #获取问卷的发布时间和截止时间。teacher 为boolean,当为true时，表示的是当前为老师
  def get_poll_times(user_id,teacher)
    if unified_setting || teacher
      pb_time = publish_time
      en_time = end_time
    else
      poll_group_setting = poll_group_settings
      user_group = course.course_members.where(user_id: user_id).select(:course_group_id)
      if user_group.exists?
        user_group_id = user_group.first&.course_group_id
        user_p_group_setting = poll_group_setting.where(course_group_id: user_group_id).select(:publish_time,:end_time)
        pb_time = user_p_group_setting.first&.publish_time
        en_time = user_p_group_setting.first&.end_time
      else
        pb_time = nil
        en_time = nil
      end
    end
    {
        "publish_time":pb_time,
        "end_time":en_time
    }
  end

  #判断当前用户的答题状态
  def check_user_votes_status(user)
    poll_answer_user = poll_users.where(user_id: user.id).select(:start_at,:end_at,:commit_status)
    user_status = 2
    if poll_answer_user.exists? && (poll_answer_user.first&.start_at.present? || poll_answer_user.first&.end_at.present?)   #学生有过答题的,或者立即截止，但学生未做试卷的
      user_status = poll_answer_user.first.commit_status
    end
    user_status
  end

end
