#encoding utf-8
class PollController < ApplicationController
  before_filter :find_poll_and_course, :only => [:edit,:update,:destroy,:show,:statistics_result,:create_poll_question,:commit_poll,:commit_answer,:publish_poll,:publish_notice,:end_notice,:cancel_publish,:poll_result,
                                                 :close_poll,:export_poll,:save_poll,:update_question_num, :student_poll_list, :poll_setting, :set_public, :add_to_exercise_bank]
  before_filter :find_container, :only => [:new,:create, :index]
  # before_filter :is_logged, :only => [:index, :show, :poll_result,:new,:create,:edit,:update,:destroy,:publish_poll,:cancel_publish,:publish_notice,:close_poll,:export_poll,:commit_answer,:commit_poll,:statistics_result,:save_poll,:set_public]
  before_filter :is_member_of_course, :only => [:show,:poll_result]
  before_filter :is_course_teacher, :only => [:new,:create,:edit,:update,:destroy,:publish_poll,:cancel_publish,:publish_notice,:close_poll,:export_poll,:save_poll,:set_public]
  before_filter :require_login, :only => [:student_poll_list, :show]
  include PollHelper
  include ApplicationHelper

  def index
    if @course.is_public == 0 && !(User.current.member_of_course?(@course)||User.current.admin?)
      render_403
      return
    end
    @is_teacher = User.current.allowed_to?(:as_teacher,@course)

    if @is_teacher
      polls = @course.polls.order("IF(ISNULL(publish_time),0,1), publish_time DESC, created_at DESC")
    elsif User.current.member_of_course?(@course)  # 课堂成员显示为发布的和已发布的
      member = @course.members.where(:user_id => User.current.id).first
      if member.try(:course_group_id).to_i == 0
        polls = @course.polls.where("publish_time <= '#{Time.now}' and unified_setting = 1").order("IF(ISNULL(publish_time),0,1),publish_time DESC, created_at DESC")
      else  # 已分班的成员
        not_poll_ids = @course.poll_group_settings.where("course_group_id = #{member.try(:course_group_id)} and (publish_time > '#{Time.now}' or publish_time is null)")
        not_poll_ids = not_poll_ids.blank? ? "(-1)" : "(" + not_poll_ids.map(&:poll_id).join(",") + ")"  # 已分班,但是成员不再
        polls = @course.polls.where("publish_time <= '#{Time.now}' and id not in #{not_poll_ids}").order("IF(ISNULL(publish_time),0,1),publish_time DESC, created_at DESC")
      end
    else
      polls = @course.polls.where("publish_time <= '#{Time.now}'").order("IF(ISNULL(publish_time),0,1),publish_time DESC, created_at DESC")
    end
    if params[:type]
      @type = params[:type]
      polls = polls.where(:polls_status => params[:type])
    end
    @search = params[:search] ? params[:search].to_s.strip : ""
    if params[:search]
      polls = polls.where("polls_name like '%#{@search}%'")
    end
    @polls = paginateHelper polls, 15 #分页
    @left_nav_type = 6
    respond_to do |format|
      format.js
      format.html{render :layout => 'base_courses'}
    end
  end

  def show
    @is_teacher = User.current.allowed_to?(:as_teacher,@course)
=begin
    if @poll.polls_status != 2 && !(User.current.allowed_to?(:as_teacher,@course) || User.current.admin?)
      render_403
      return
    end
=end

    unless @is_teacher
      @user = User.current
      @poll_user = PollUser.where("user_id=? and poll_id=?", User.current.id, @poll.id).first
      if @poll_user.nil?
        @poll_user = PollUser.create(:user_id => User.current.id, :poll_id => @poll.id, :start_at => Time.now, :commit_status => 0)
      elsif @poll_user.start_at.nil?
        @poll_user.update_attributes(:start_at => Time.now)
      end

      @can_edit_poll = can_edit_poll @poll, @poll_user
      @percent = get_percent(@poll,User.current)
      if !@can_edit_poll && @poll_user.commit_status == 0
        @poll_user.update_attributes(:end_at => @poll.end_time, :commit_status => 1)
      end
    else
      @user = User.find params[:user_id]
      @poll_user = PollUser.where("user_id=? and poll_id=?", params[:user_id], @poll.id).first
      @can_edit_poll = false
    end

    respond_to do |format|
      format.html {render :layout => 'base_edu'}
    end
  end

  def new
    @poll = Poll.new
    respond_to do |format|
      format.html{render :layout => 'base_edu'}
    end
  end

  def create
    if params[:poll]
      poll = Poll.new(:polls_name => params[:poll][:polls_name], :polls_description => params[:poll][:polls_description], :user_id => User.current.id, :polls_type => 'Course',
                      :course_id => params[:course_id], :show_result => 1, :polls_status => 1)
      if poll.save
        create_polls_list poll
        @poll = poll
        respond_to do |format|
          format.js
        end
      end
    end
  end

  def edit
    respond_to do |format|
      format.html{render :layout => 'base_edu'}
    end
  end

  def update
    @poll.polls_name = params[:poll][:polls_name]
    @poll.polls_description = params[:poll][:polls_description]
    if @poll.save
      respond_to do |format|
        format.js
      end
    else
      render_404
    end
  end

  def destroy
    if @poll && @poll.destroy
      redirect_to poll_index_url(:course_id => @course.id)
    end
  end

  def student_poll_list
    @order,@b_sort,@name,@group,@status = params[:order] || "end_at",params[:sort] || "desc",params[:name].to_s.strip || "", params[:poll_group], params[:poll_status]
    @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
    @member = @course.members.where(:user_id => User.current.id).first

    # 判断学生是否有权限查看(问卷未发布、问卷已发布但不是统一设置的未分班学生、分班设置的问卷未发布)
    if User.current.member_of_course?(@course) && !@is_teacher
      if @poll.publish_time.nil? || @poll.publish_time > Time.now || (!@poll.unified_setting && (@member.course_group_id == 0 ||
          @poll.poll_group_settings.where("course_group_id = #{@member.try(:course_group_id)} and (publish_time > '#{Time.now}' or publish_time is null)").count > 0))
        render_403
        return
      end
    end

    student_id = @course.student.blank? ? "(-1)" : "(" + @course.student.map{|student| student.student_id}.join(",") + ")"

    if @poll.polls_status < 2
      @poll_users_list = @poll.poll_users.where("0=1")
    elsif @poll.unified_setting
      @poll_users_list = @poll.poll_users
    else
      user_ids = @course.members.where(:course_group_id => @poll.poll_group_settings.where("publish_time < '#{Time.now}'").pluck(:course_group_id)).map(&:user_id)
      @poll_users_list = @poll.poll_users.where(:user_id => user_ids)
    end

    @group_teacher = @is_teacher && @member.present? && @member.teacher_course_groups.count > 0

    if @group || @group_teacher
      group_ids = @group || @member.teacher_course_groups.pluck(:course_group_id)
      group_students = @course.members.where(:course_group_id => group_ids).joins("join users on members.user_id = users.id").select{|m| m.roles.to_s.include?("Student")}

      if group_students.empty?
        student_in_group = '(-1)'
      else
        student_in_group = '(' + group_students.map{ |member| member.user_id }.join(',')  + ')'
      end
      @poll_users_list = @poll_users_list.where("poll_users.user_id in #{student_in_group}")
    else
      @poll_users_list = @poll_users_list.where("poll_users.user_id in #{student_id}")
    end

    if @poll_users_list.size != 0
      if @order == "student_id"
        @poll_users_list = @poll_users_list.includes(:user => {:user_extensions => []}).order("user_extensions.student_id #{@b_sort}")
      else
        @poll_users_list = @poll_users_list.includes(:user => {:user_extensions => []}).order("#{@order} #{@b_sort}")
      end
    end

    unless @status.blank?
      @poll_users_list = @poll_users_list.where(:commit_status => @status)
    end

    @poll_users_list = search_work_member @poll_users_list, @name

    @tab = params[:tab].nil? ? 1 : params[:tab].to_i
    @score = @b_sort == "desc" ? "asc" : "desc"
    @poll_count = @poll_users_list.count
    @is_new = params[:is_new] ? true : false
    @has_commit_count = @poll.poll_users.where(:commit_status => 1).count
    @no_group_count = @course.members.where(:course_group_id => 0).select{|m| m.roles.to_s.include?("Student")}.count
    @limit = 50
    @page = (params['page'] || 1).to_i
    @poll_users_list = paginateHelper @poll_users_list, @limit

    respond_to do |format|
      format.js
      format.html{render :layout => 'base_edu'}
    end
  end

  def statistics_result
    poll_questions = @poll.poll_questions
    member = @course.members.where(:user_id => User.current.id).first
    if member.present? && member.teacher_course_groups.count > 0
      group_ids =  member.teacher_course_groups.pluck(:course_group_id)
      group_students = @course.members.where(:course_group_id => group_ids).joins("join users on members.user_id = users.id").select{|m| m.roles.to_s.include?("Student")}
      @user_ids = @poll.poll_users.where(:commit_status => 1, :user_id => group_students.map(&:user_id)).map(&:user_id)
    else
      @user_ids = @poll.poll_users.where(:commit_status => 1).map(&:user_id)
    end
    @poll_questions = paginateHelper poll_questions, 10
    respond_to do |format|
      format.js
    end
  end

  def poll_setting
    if @poll.polls_status == 1 && @course.course_groups.count > 1
      @poll.unified_setting = params[:unified_setting] ? true :false
    end

    if @poll.unified_setting
      params_publish_time = params[:poll_publish_time]
      params_end_time = params[:poll_end_time]
      min_publish_time = params_publish_time
      max_end_time = params_end_time
    else
      # 获取最小发布时间和最大截止时间,赋值给homework
      params_publish_time = params[:poll_publish_time_group]
      params_end_time = params[:poll_end_time_group]
      min_publish_time = @poll.publish_time ? (format_time @poll.publish_time).to_s : ""
      max_end_time = @poll.end_time ? (format_time @poll.end_time).to_s : ""
      if params[:poll_end_time_group]
        max_end_time = ""
        params[:poll_end_time_group].each_with_index do |end_time, index|
          if end_time != ""
            if max_end_time == ""
              max_end_time = end_time
            end
            if end_time > max_end_time
              max_end_time = end_time
            end
          end
        end
      end

      if params[:poll_publish_time_group]
        params[:poll_publish_time_group].each_with_index do |publish_time, index|
          if publish_time != ""
            if min_publish_time == ""
              min_publish_time = publish_time
            end
            if publish_time < min_publish_time
              min_publish_time = publish_time
            end
          end
        end
      end
    end

    if params_publish_time && min_publish_time != ""
      @poll.publish_time = min_publish_time
      @poll.end_time = max_end_time
      if @poll.publish_time < Time.now and @poll.polls_status == 1
        @poll.polls_status = 2
        create_poll_user = 1
        if @poll.course_acts.size == 0
          @poll.course_acts << CourseActivity.new(:user_id => @poll.user_id,:course_id => @poll.course_id)
        end
      end
    elsif params_publish_time && min_publish_time == ""
      create_poll_user = 1
      @poll.polls_status = 2
      @poll.publish_time = Time.now
      @poll.end_time = Time.at(((1.month.since.to_i)/3600.0).ceil * 3600)

      if @poll.course_acts.size == 0
        @poll.course_acts << CourseActivity.new(:user_id => @poll.user_id,:course_id => @poll.course_id)
      end
    else
      @poll.end_time = max_end_time if params_end_time
    end

    # 不统一设置且分班数大于一则更新分组设置
    if !@poll.unified_setting && @course.course_groups.count > 1
      @course.course_groups.each_with_index do |group, index|
        poll_group_setting = @poll.poll_group_settings.where(:course_group_id => group.id).first
        unless poll_group_setting
          poll_group_setting = PollGroupSetting.create(:poll_id => @poll.id, :course_group_id => group.id, :course_id => @course.id)
        end
      end
      group_id = []
      @poll.poll_group_settings.where("publish_time is null or publish_time > '#{Time.now}'").joins(:course_group).reorder("CONVERT(course_groups.name USING gbk) COLLATE gbk_chinese_ci ASC").each_with_index do |setting, index|
        if params[:poll_publish_time_group] && min_publish_time != ""
          if params[:poll_publish_time_group][index] && params[:poll_publish_time_group][index] != ""
            setting.update_column(:publish_time, params[:poll_publish_time_group][index])
          end
        elsif params[:poll_publish_time_group] && min_publish_time == ""
          setting.update_column(:publish_time, Time.now)
          group_id << setting.course_group_id
        end
      end

      @poll.poll_group_settings.where("end_time is null or end_time > '#{Time.now}'").joins(:course_group).reorder("CONVERT(course_groups.name USING gbk) COLLATE gbk_chinese_ci ASC").each_with_index do |setting, index|
        if params[:poll_end_time_group] && max_end_time != ""
          if params[:poll_end_time_group][index] && params[:poll_end_time_group][index] != ""
            setting.update_column(:end_time, params[:poll_end_time_group][index])
          end
        elsif params[:poll_end_time_group] && max_end_time == ""
          setting.update_column(:end_time, Time.at(((1.month.since.to_i)/3600.0).ceil * 3600))
        end
      end
      # 统一设置则删除分组设置
    elsif @poll.unified_setting
      @poll.poll_group_settings.destroy_all
    end

    @poll.show_result = params[:show_result] ? 1 : 0
    @poll.un_anonymous = params[:un_anonymous] ? 1 : 0
    if @poll.save
      if create_poll_user.present?
        if group_id.present? && group_id.size != 0
          if group_id.size == @course.course_groups.count
            create_polls_tiding @poll, @course.student
          else
            members = @course.members.where(:course_group_id => group_id)
            create_polls_tiding @poll, members
          end
        else
          create_polls_tiding @poll, @course.student
        end
      end

      redirect_to student_poll_list_poll_path(@poll)
    end
  end
  
   def get_poll_totalcount poll_question
    @total_questions_count = poll_question.poll_votes.count
  end
  
  def get_poll_everycount  poll_answer
    @every_answer_count =  poll_answer.poll_votes.count
  end

  def update_question_num
    @poll_question = PollQuestion.find params[:ques_id]
    poll_questions = @poll.poll_questions
    if @poll_question
      if params[:opr] == 'up' && @poll_question.question_number > 1
        @before_que = poll_questions.where("question_number = #{@poll_question.question_number - 1}").first
        if @before_que && @poll_question.update_attribute('question_number', @poll_question.question_number - 1)
          @before_que.update_attribute('question_number', @before_que.question_number + 1)
        end
      elsif params[:opr] == 'down' && @poll_question.question_number < poll_questions.count
        @after_que = poll_questions.where("question_number = #{@poll_question.question_number + 1}").first
        if @after_que && @poll_question.update_attribute('question_number', @poll_question.question_number + 1)
          @after_que.update_attribute('question_number', @after_que.question_number - 1)
        end
      end
      respond_to do |format|
        format.js
      end
    end
  end

  #添加题目
  def create_poll_question
    @last_question = @poll.poll_questions.last
    question_title = params[:question_title].nil? || params[:question_title].empty? ? l(:label_enter_single_title) : params[:question_title]
    option = {
        :is_necessary => (params[:is_necessary] == "1" ? 1 : 0),
        :question_title => question_title,
        :question_type => params[:question_type] || 1,
        :question_number => @poll.poll_questions.count + 1,
        :max_choices => params[:max_choices].to_i || 0,
        :min_choices => params[:min_choices].to_i || 0
    }
    @poll_questions = @poll.poll_questions.new option
    if params[:question_answer]
      for i in 1..params[:question_answer].count
        answer = (params[:question_answer].values[i-1].nil? || params[:question_answer].values[i-1].empty?) ? l(:label_new_answer) : params[:question_answer].values[i-1]
        question_option = {
            :answer_position => i,
            :answer_text => answer
        }
        @poll_questions.poll_answers.new question_option
      end
    end
    if params[:question_other_answer]
      question_option = {
          :answer_position => params[:question_answer].count + 1,
          :answer_text => ''
      }
      @poll_questions.poll_answers.new question_option
    end
    # 如果是插入的话,那么从插入的这个id以后的question_num都将要+1
    if params[:quest_id] != "0"
      insert_poll = PollQuestion.find params[:quest_id]
      if insert_poll
        @is_insert = true
        ques_num = insert_poll.question_number
        @poll.poll_questions.where("question_number > #{ques_num}").update_all(" question_number = question_number + 1")
        @poll_question_num = ques_num
        @poll_questions.question_number = ques_num + 1
      end
    end
    if @poll_questions.save
      respond_to do |format|
        format.js
      end
    end
  end

  #修改题目
  def update_poll_question
    @poll_question = PollQuestion.find params[:poll_question]
    @poll = @poll_question.poll
    @poll_question.question_title = params[:question_title].nil? || params[:question_title].empty? ? l(:label_enter_single_title) : params[:question_title]
    @poll_question.max_choices = params[:max_choices].to_i || 0
    @poll_question.min_choices = params[:min_choices].to_i || 0
    ################处理选项
    if params[:question_answer]
      @poll_question.poll_answers.each do |answer|
        answer.destroy unless params[:question_answer].keys.include? answer.id.to_s
      end
      for i in 1..params[:question_answer].count
        question = @poll_question.poll_answers.find_by_id params[:question_answer].keys[i-1]
        answer = (params[:question_answer].values[i-1].nil? || params[:question_answer].values[i-1].empty?) ? l(:label_new_answer) : params[:question_answer].values[i-1]
        if question
          question.answer_position = i
          question.answer_text = answer
          question.save
        else
          question_option = {
              :answer_position => i,
              :answer_text => answer
          }
          @poll_question.poll_answers.new question_option
        end
      end
      if params[:question_other_answer]
        question = @poll_question.poll_answers.where("answer_text = ''").first
        unless question
          question_option = {
              :answer_position => params[:question_answer].count + 1,
              :answer_text => ''
          }
          @poll_question.poll_answers.new question_option
        end
      else
        question = @poll_question.poll_answers.where("answer_text = ''").first
        if question
          question.destroy
        end
      end
    end
    @poll_question.save
    respond_to do |format|
      format.js
    end
  end

  #删除题目
  def delete_poll_question
    @poll_question = PollQuestion.find params[:poll_question]
    @poll = @poll_question.poll
    @poll.poll_questions.where("question_number>?",@poll_question.question_number).update_all("question_number = question_number - 1")

    if @poll_question && @poll_question.destroy
      respond_to do |format|
        format.js
      end
    end
  end

  def publish_notice
    if @poll.publish_time
      @status = 1
    else
      @status = 0
    end
    if @course.course_groups.count > 1
      if @poll.unified_setting
        @groups = @course.course_groups
      else
        @groups = @course.course_groups.where(:id => @poll.poll_group_settings.where("publish_time is null or publish_time > '#{Time.now}'").map(&:course_group_id))
      end
      @all_groups = @groups
      @groups = paginateHelper @groups, 5
    end
  end

  #发布问卷
  def publish_poll
    if @poll.polls_status == 1
      if params[:group_ids]
        if @course.course_groups.where(:id => params[:group_ids].split(",")).count == @course.course_groups.count
          @poll.poll_group_settings.destroy_all
          @poll.update_attribute("unified_setting", true)
          # 发消息
          create_polls_tiding @poll, @course.student
        else
          @poll.update_attribute("unified_setting", false)
          @course.course_groups.each do |group|
            poll_group_setting = @poll.poll_group_settings.where(:course_group_id => group.id).first
            unless poll_group_setting
              PollGroupSetting.create(:poll_id => @poll.id, :course_group_id => group.id, :course_id => @course.id, :publish_time => @poll.publish_time, :end_time => @poll.end_time)
            end
          end
          @poll.poll_group_settings.where(:course_group_id => params[:group_ids].split(",")).update_all(:publish_time => Time.now)
          @poll.poll_group_settings.where(:course_group_id => params[:group_ids].split(","), :end_time => nil).update_all(:end_time => Time.at(((1.month.since.to_i)/3600.0).ceil * 3600))
          # 发消息
          members = @course.members.where(:course_group_id => params[:group_ids].split(","))
          create_polls_tiding @poll, members
        end
      else
        @poll.poll_group_settings.destroy_all
        # 发消息
        create_polls_tiding @poll, @course.student
      end

      @poll.polls_status = 2
      @poll.publish_time = Time.now
      if @poll.end_time.nil?
        @poll.end_time = Time.at(((1.month.since.to_i)/3600.0).ceil * 3600)
      elsif PollGroupSetting.where("poll_id = #{@poll.id} and end_time is not null").count > 0
        @poll.update_attribute("end_time", PollGroupSetting.where("poll_id = #{@poll.id} and end_time is not null").map(&:end_time).max)
      end
      if @poll.save
        # create_polls_list @poll

        if @poll.course_acts.size == 0
          @poll.course_acts << CourseActivity.new(:user_id => @poll.user_id,:course_id => @poll.course_id)
        end
      end
    else
      @poll.poll_group_settings.where(:course_group_id => params[:group_ids].split(",")).update_all(:publish_time => Time.now)
      @poll.poll_group_settings.where(:course_group_id => params[:group_ids].split(","), :end_time => nil).update_all(:end_time => Time.at(((1.month.since.to_i)/3600.0).ceil * 3600))
      if PollGroupSetting.where("poll_id = #{@poll.id} and end_time is not null").count > 0
        @poll.update_attribute("end_time", PollGroupSetting.where("poll_id = #{@poll.id} and end_time is not null").map(&:end_time).max)
      end
      members = @course.members.where(:course_group_id => params[:group_ids].split(","))
      create_polls_tiding @poll, members
    end
    if @poll.end_time > Time.now && @poll.polls_status > 2
      @poll.update_attribute("polls_status", 2)
    end
    redirect_to student_poll_list_poll_path(@poll)
  end

  def end_notice
    if @course.course_groups.count > 1
      unless @poll.unified_setting
        @groups = @course.course_groups.where(:id => @poll.poll_group_settings.where("publish_time < '#{Time.now}' and end_time > '#{Time.now}'").map(&:course_group_id))
        @all_groups = @groups
        @groups = paginateHelper @groups, 5
      end
    end
  end

  #关闭问卷
  def close_poll
    time = Time.now
    poll_users = @poll.poll_users.where("0=1")
    # if @poll.polls_status == 2 && @poll.end_time > Time.now
      if params[:group_ids]
        # @poll.poll_group_settings.where(:course_group_id => params[:group_id]).where("publish_time > '#{Time.now}' or publish_time is null").update_all(:publish_time => time)
        @poll.poll_group_settings.where(:course_group_id => params[:group_ids].split(",")).update_all(:end_time => time)
        poll_users = @poll.poll_users.where(:user_id => @course.members.where(:course_group_id => params[:group_ids].split(",")).map(&:user_id))
        @poll.update_attribute("end_time", PollGroupSetting.where("poll_id = #{@poll.id} and end_time is not null").map(&:end_time).max)
        if @poll.end_time > Time.now && @poll.polls_status > 2
          @poll.update_attribute("polls_status", 2)
        elsif @poll.end_time <= Time.now && @poll.polls_status == 2
          @poll.update_attribute("polls_status", 3)
        end
      elsif @poll.unified_setting
        poll_users = @poll.poll_users
        @poll.update_attributes(:polls_status => 3, :end_time => time)
      end

      poll_users.each do |poll_user|
        if poll_user.commit_status == 0 && !poll_user.start_at.nil?
          poll_user.update_attributes(:commit_status => 1, :end_at => Time.now)
        end
      end
    # end
    redirect_to student_poll_list_poll_path(@poll)
  end


  #保存问卷
  def save_poll
    @poll.show_result = params[:show_result].to_i
    if @poll.save
      respond_to do |format|
        format.js
      end
    end
  end

  #提交答案
  def commit_answer
    pq = PollQuestion.find(params[:poll_question_id])
    poll_user = PollUser.where(:poll_id => @poll.id, :user_id => User.current.id).first
    if (poll_user && poll_user.commit_status == 1) || @poll.end_time < Time.now
      render :json => {:text => "Over"}
      return
    end

    if pq.question_type == 1
      #单选题
      pv = PollVote.find_by_poll_question_id_and_user_id(params[:poll_question_id],User.current.id)
      if pv.nil?
        #尚未答该题,添加答案
        pv = PollVote.new
        pv.user_id = User.current.id
        pv.poll_question_id = params[:poll_question_id]
      end
      #修改该题对应答案
      pv.poll_answer_id = params[:poll_answer_id]
      pv.vote_text = params[:vote_text] ? params[:vote_text] : ""
      if pv.save
        #保存成功返回成功信息及当前以答题百分比
        @percent = get_percent(@poll,User.current)
        render :json => {:text => "ok" ,:percent => format("%.2f" ,@percent)}
      else
        #返回失败信息
        render :json => {:text => "failure"}
      end
    elsif pq.question_type == 2
      #多选题
      pv = PollVote.find_by_poll_answer_id_and_user_id(params[:poll_answer_id],User.current.id)
      if pv.nil?
        #尚未答该题,添加答案
        count = PollVote.where("poll_question_id = #{params[:poll_question_id].to_i} and user_id = #{User.current.id}").count
        if pq.max_choices != 0 && count >= pq.max_choices
          render :json => {:text => "over"}
        else
          pv = PollVote.new
          pv.user_id = User.current.id
          pv.poll_question_id = params[:poll_question_id]
          pv.poll_answer_id = params[:poll_answer_id]
          pv.vote_text = params[:vote_text] if params[:vote_text]
          if pv.save
            @percent = get_percent(@poll,User.current)
            render :json => {:text => "ok",:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        end
      else
        #pv不为空,则当前选项之前已被选择,再次点击则是不再选择该项,故删除该答案
        if params[:vote_text]
          pv.vote_text = params[:vote_text]
          if pv.save
            @percent = get_percent(@poll,User.current)
            render :json => {:text => "ok",:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        else
          if pv.delete
            @percent = get_percent(@poll,User.current)
            render :json => {:text => "false" ,:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        end
      end
    elsif pq.question_type == 3
      #单行文本
      pv = PollVote.find_by_poll_question_id_and_user_id(params[:poll_question_id],User.current.id)
      if pv.nil?
        #pv为空之前尚未答题,添加答案
        if params[:vote_text].nil? || params[:vote_text].blank?
          #用户提交空答案,视作不作答
          @percent = get_percent(@poll,User.current)
          render :json => {:text => "",:percent => format("%.2f" ,@percent)}
        else
          #添加答案
          pv = PollVote.new
          pv.user_id = User.current.id
          pv.poll_question_id = params[:poll_question_id]
          pv.vote_text = params[:vote_text]
          if pv.save
            @percent = get_percent(@poll,User.current)
            render :json => {:text => pv.vote_text,:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        end
      else
        #pv不为空说明用户之前已作答
        if params[:vote_text].nil? || params[:vote_text].blank?
          #用户提交空答案,视为删除答案
          if pv.delete
            @percent = get_percent(@poll,User.current)
            render :json => {:text => "",:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        else
          #用户修改答案
          pv.vote_text = params[:vote_text]
          if pv.save
            @percent = get_percent(@poll,User.current)
            render :json => {:text => pv.vote_text,:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        end
      end
    elsif pq.question_type == 4
      #多行文本题
      pv = PollVote.find_by_poll_question_id_and_poll_answer_id_and_user_id(params[:poll_question_id],params[:poll_answer_id],User.current.id)
      if pv.nil?
        #pv为空之前尚未答题,添加答案
        if params[:vote_text].nil? || params[:vote_text].blank?
          #用户提交空答案,视作不作答
          @percent = get_percent(@poll,User.current)
          render :json => {:text => "",:percent => format("%.2f" ,@percent)}
        else
          #添加答案
          pv = PollVote.new
          pv.user_id = User.current.id
          pv.poll_question_id = params[:poll_question_id]
          pv.poll_answer_id = params[:poll_answer_id]
          pv.vote_text = params[:vote_text]
          if pv.save
            @percent = get_percent(@poll,User.current)
            render :json => {:text => pv.vote_text,:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        end
      else
        #pv不为空说明用户之前已作答
        if params[:vote_text].nil? || params[:vote_text].blank?
          #用户提交空答案,视为删除答案
          if pv.delete
            @percent = get_percent(@poll,User.current)
            render :json => {:text => "",:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        else
          #用户修改答案
          pv.vote_text = params[:vote_text]
          if pv.save
            @percent = get_percent(@poll,User.current)
            render :json => {:text => pv.vote_text,:percent => format("%.2f" ,@percent)}
          else
            render :json => {:text => "failure"}
          end
        end
      end

    else
      render :json => {:text => "failure"}
    end
  end

  #提交问卷
  def commit_poll
    @uncomplete_question = get_uncomplete_question(@poll,User.current)
    if @uncomplete_question.count < 1
      pu = @poll.poll_users.where(:user_id => User.current.id).first
      pu.commit_status = 1
      pu.end_at = Time.now
      if pu.save
        @status = 0 #提交成功
        tid_str = ""
        member = @course.members.where(:user_id => User.current.id).first
        teachers = tiding_teachers @course, member
        teachers.find_each do |mem|
          tid_str += "," if tid_str != ""
          tid_str += "(#{mem.user_id}, #{User.current.id}, #{@poll.id}, 'Poll', #{@poll.id}, 'CommitPoll', #{@course.id}, 'Course', 0, 'Poll', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}', '#{Time.now.strftime('%Y-%m-%d %H:%M:%S')}')"
        end
        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
      else
        @status = 2 #未知错误
      end
    else
        @status = 1 #有未做得必答题
    end
    respond_to do |format|
      format.js
    end
  end

  def import_poll
    @poll = Poll.find(params[:to_id])
    question_num = @poll.poll_questions.select("max(question_number) question_number").first.question_number
    import_poll = Poll.find(params[:import_id])
    import_poll.poll_questions.each_with_index  do |question,index|
      option = {
          :is_necessary => question.is_necessary,
          :question_title => question.question_title,
          :question_type => question.question_type,
          :question_number => question_num + index+1
      }
      poll_questions = @poll.poll_questions.new option
      for i in 1..question.poll_answers.count
        answer = question.poll_answers[i-1][:answer_text]
        question_option = {
            :answer_position => i,
            :answer_text => answer
        }
        poll_questions.poll_answers.new question_option
      end
      @poll.poll_questions << poll_questions
    end
    if @poll.save
      @poll = Poll.find(params[:to_id])
      respond_to do |format|
        format.js
      end
    end
  end

  def cancel_publish
    ActiveRecord::Base.transaction do
      @poll.poll_users.destroy_all
      PollVote.where(:poll_question_id => @poll.poll_questions.pluck(:id)).destroy_all
      @poll.update_attributes(:polls_status => 1, :publish_time => nil, :end_time => nil, :unified_setting => 1)
      @poll.poll_group_settings.destroy_all
      @poll.course_acts.destroy_all
      @poll.tidings.destroy_all
      create_polls_list @poll
    end
    redirect_to student_poll_list_poll_path(@poll)
  end

  #显示某个学生某份问卷的填写结果
  def poll_result
    @poll_questions = @poll.poll_questions
    @left_nav_type = 7
    respond_to do |format|
      format.html{render :layout => 'base_courses'}
    end
  end

  def set_public
    if User.current.admin? || User.current.allowed_to?(:as_teacher, @course)
      @poll.update_attributes(:is_public => true)
    end
  end

  def add_to_exercise_bank
    exercise_bank = User.current.exercise_banks.where(:container_id => @poll.id, :container_type => "Poll").first
    if exercise_bank.present?
      exercise_bank.update_attributes(:name => @poll.polls_name, :description => @poll.polls_description, :course_list_id => @poll.course.try(:course_list_id))

      question_bank = QuestionBank.where(:container_id => exercise_bank.id, :container_type => exercise_bank.container_type).first
      question_bank.update_attributes(:name => exercise_bank.name, :course_list_id => exercise_bank.course_list_id) if question_bank.present?
      exercise_bank.exercise_bank_questions.destroy_all
    else
      exercise_bank = ExerciseBank.new(:name => @poll.polls_name, :description => @poll.polls_description, :user_id => User.current.id, :is_public => 0,
                                       :course_list_id => @poll.course.try(:course_list_id), :container_id => @poll.id, :container_type => "Poll", :quotes => 1)
      if exercise_bank.save
        QuestionBank.create(:name => exercise_bank.name, :container_id => exercise_bank.id, :container_type => exercise_bank.container_type, :quotes => exercise_bank.quotes,
                            :user_id => exercise_bank.user_id, :is_public => exercise_bank.is_public, :course_list_id => exercise_bank.course_list_id)
      end
    end

    @poll.poll_questions.each do |q|
      option = {
          :question_title => q[:question_title],
          :question_type => q[:question_type] || 1,
          :is_necessary => q[:is_necessary],
          :question_number => q[:question_number],
          :max_choices => q[:max_choices],
          :min_choices => q[:min_choices]
      }
      exercise_bank_question = exercise_bank.exercise_bank_questions.new option

      for i in 1..q.poll_answers.count
        choice_option = {
            :choice_position => i,
            :choice_text => q.poll_answers[i-1][:answer_text]
        }
        exercise_bank_question.exercise_bank_choices.new choice_option
      end
    end
    exercise_bank.save
  end

  #导出问卷
  def export_poll
    poll_questions = @poll.poll_questions
    respond_to do |format|
      format.xls {
        send_data(poll_to_xls(poll_questions), :type => "text/excel;charset=utf-8; header=present",
                  :filename => filename_for_content_disposition("#{@poll.polls_name}.xls") )
      }
    end
  end

  # 将题库的问卷导出来
  def other_poll
    @search = params[:search] ? params[:search].to_s.strip.downcase : ""
    if(params[:type].blank? || params[:type] == "1") #我的题库
      @polls = User.current.exercise_banks.where(:container_type => "Poll")
    elsif params[:type] == "2" #公共题库
      @polls = ExerciseBank.where(:container_type => "Poll", :is_public => true)
    end
    @type = params[:type] || "1"
    if @search.present?
      course_list_ids = CourseList.where("name like '%#{@search}%'").map(&:id)
      course_list_ids = course_list_ids.length == 0 ? "(-1)" : "("+ course_list_ids.join(",") +")"
      @polls = @polls.where("name like '%#{@search}%' or course_list_id in #{course_list_ids}").reorder("created_at desc")
    else
      @polls = @polls.reorder("created_at desc")
    end
    @course_id = params[:course_id]
    @polls = paginateHelper @polls,8
    @page = params[:page].nil? ? 1 : params['page'].to_i
    poll_count = @polls.count
    @total_pages = (poll_count / 8.0).ceil
    respond_to do |format|
      format.js
    end
  end

  # 将问卷导入本课程
  def import_other_poll
    course_id = params[:course_id]
    course = Course.find(course_id)
    if params[:poll_id]
      poll = ExerciseBank.find(params[:poll_id])
      @poll = quote_poll_bank poll, course
      if @poll
        redirect_to student_poll_list_poll_path(@poll, :tab => 4)
      end
    end
  end

  private
  def remove_invalid_poll(course)
    polls = Poll.where("polls_type = 'Course' and course_id = #{course.id} and polls_name = ''")
    unless polls.empty?
      polls.each do |poll|
        if poll.poll_questions.empty?
          poll.destroy
        end
      end
    end
  end

  def find_poll_and_course
    @poll = Poll.find params[:id]
    @course = Course.find @poll.course_id
  rescue Exception => e
    render_404
  end

  def find_container
    @course = Course.find params[:course_id]
  rescue Exception => e
    render_404
  end

  def is_logged
    redirect_to signin_path unless User.current.logged?
  end

  def is_member_of_course
    render_403 unless(@course && (User.current.member_of_course?(@course) || User.current.admin?))
  end

  def is_course_teacher
    @is_teacher = User.current.allowed_to?(:as_teacher,@course)
    render_403 unless(@course && @is_teacher)
  end

  #获取未完成的题目
  def get_uncomplete_question poll,user
    necessary_questions = poll.poll_questions.where("#{PollQuestion.table_name}.is_necessary = 1")
    uncomplete_question = []
    necessary_questions.each do |question|
      answers = get_user_answer(question,user)
      if question.question_type != 4
        if answers.nil? || answers.count < 1
          uncomplete_question << question
        end
      else
        if answers.nil? || answers.count < question.poll_answers.count
          uncomplete_question << question
        end
      end
      # if answers.nil? || answers.count < 1
      #   uncomplete_question << question
      # end
    end
    uncomplete_question
  end

  #获取用户对某个问题的答案
  def get_user_answer(question,user)
    user_answer = question.poll_votes.where("#{PollVote.table_name}.user_id = #{user.id}")
    user_answer
  end

  def get_complete_question(poll,user)
    questions = poll.poll_questions.includes(:poll_votes)
    complete_question = []
    questions.each do |question|
      answers = question.poll_votes.select{|e| e.user_id == user.id}
      if !(answers.empty? || answers.count < 1)
        complete_question << question
      end
      # if question.question_type != 4
      #   if !(answers.nil? || answers.count < 1)
      #     complete_question << question
      #   end
      # else
        
      # end
    end
    complete_question
  end

  def get_percent poll,user
    if poll.poll_questions.count == 0
      return 0
    else
      complete_count = get_complete_question(poll,user).count
      all_count = poll.poll_questions.where("question_type != 4").count
      # poll.poll_questions.where("question_type = 4").each do |pq|
      #   all_count += pq.poll_answers.count
      # end
      return (complete_count.to_f / all_count.to_f)*100
    end
  end

  #PollUser记录用户是否已提交问卷有对应的记录则已提交,没有则新建一个
  def get_poll_user poll_id,user_id
    pu = PollUser.find_by_poll_id_and_user_id(poll_id,user_id)
    if pu.nil?
      pu = PollUser.new
    end
    pu
  end

  #将poll中题目转换为Excel
  def poll_to_xls poll_questions
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "poll"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    count_row = 0
    member = @course.members.where(:user_id => User.current.id).first
    if member.present? && member.teacher_course_groups.count > 0
      group_ids =  member.teacher_course_groups.pluck(:course_group_id)
      group_students = @course.members.where(:course_group_id => group_ids).joins("join users on members.user_id = users.id").select{|m| m.roles.to_s.include?("Student")}
      poll_users = @poll.poll_users.where(:commit_status => 1, :user_id => group_students.map(&:user_id))
    else
      poll_users = @poll.poll_users.where(:commit_status => 1)
    end

    poll_questions.each do |poll_question|
      if poll_question.question_type == 1 || poll_question.question_type == 2
        sheet1.row(count_row).default_format = blue
        sheet1[count_row,0]= l(:label_poll_question_num,:num => poll_question.question_number)
        sheet1[count_row + 1,0] = l(:label_poll_subtotal)
        sheet1[count_row + 2,0] = l(:label_poll_proportion)
        poll_question.poll_answers.each_with_index do |poll_answer,i|
          sheet1[count_row, i + 1] = poll_answer.answer_text == "" ? l(:label_poll_other) : poll_answer.answer_text.gsub(/<\/?.*?>/,"").gsub(/&nbsp;/," ")
          sheet1[count_row + 1, i + 1] = poll_answer.poll_votes.where(:user_id => poll_users.map(&:user_id)).count
          sheet1[count_row + 2, i + 1] = statistics_result_percentage(poll_answer.poll_votes.where(:user_id => poll_users.map(&:user_id)).count, total_answer(poll_question.id, poll_users.map(&:user_id))).to_s + "%"
        end
        sheet1[count_row + 3,0] = l(:label_poll_valid_commit)
        sheet1[count_row + 3,1] = total_answer(poll_question.id, poll_users.map(&:user_id))
        count_row += 5
      else
        sheet1.row(count_row).default_format = blue
        sheet1[count_row,0] = l(:label_poll_question_num,:num => poll_question.question_number)
        sheet1[count_row,1] = poll_question.question_title
        count_row += 1
        if poll_question.question_type == 3
          poll_question.poll_votes.where(:user_id => poll_users.map(&:user_id)).each do |poll_vote|
            sheet1[count_row,0] = poll_vote.vote_text.gsub(/<\/?.*?>/,"").gsub(/&nbsp;/," ")
            count_row += 1
          end
          count_row += 1
        else
          count = 0
          poll_question.poll_answers.reorder("answer_position asc").each_with_index do |poll_answer,i|
            sheet1.row(count_row).default_format = blue
            sheet1[count_row, i] = poll_answer.answer_text.gsub(/<\/?.*?>/,"").gsub(/&nbsp;/," ")
            count = poll_question.poll_votes.where(:poll_answer_id => poll_answer.id, :user_id => poll_users.map(&:user_id)).count > count ? poll_question.poll_votes.where(:poll_answer_id => poll_answer.id, :user_id => poll_users.map(&:user_id)).count : count
            poll_question.poll_votes.where(:poll_answer_id => poll_answer.id, :user_id => poll_users.map(&:user_id)).each_with_index do |poll_vote, j|
              sheet1[count_row + j + 1,i] = poll_vote.vote_text.gsub(/<\/?.*?>/,"").gsub(/&nbsp;/," ")
            end
          end
          count_row = count_row + count + 2
        end
      end
    end

    sheet1.row(count_row).default_format = blue
    sheet1[count_row ,0] = l(:label_bidding_number)
    if @poll.un_anonymous
      sheet1[count_row, 1] = l(:label_bidding_user_studentname)
      current_index = 2
    else
      current_index = 1
    end
    poll_questions.each do |poll_question|
      if poll_question.question_type == 4
        poll_question.poll_answers.reorder("answer_position asc").each do |ans|
          sheet1[count_row ,current_index] = poll_question.question_title + "(#{ans.answer_text})"
          current_index += 1
        end
      else
        sheet1[count_row ,current_index] = poll_question.question_title
        current_index += 1
      end
    end
    count_row += 1
    poll_users.reorder("end_at desc").each_with_index do |poll_user, index|
      user = poll_user.user
      sheet1[count_row ,0] = index + 1
      if @poll.un_anonymous
        sheet1[count_row, 1] = user.show_real_name
        current_index = 2
      else
        current_index = 1
      end
      poll_questions.each_with_index do |poll_question, i|
        if poll_question.question_type == 1 || poll_question.question_type == 2
          sheet1[count_row ,current_index] = user.poll_votes.where(:poll_question_id => poll_question.id).map{|poll_vote| (poll_vote.poll_answer.answer_text != "" ? poll_vote.poll_answer.answer_text.gsub(/<\/?.*?>/,"").gsub(/&nbsp;/," ") : l(:label_other_answer) + " (" + poll_vote.vote_text.to_s + ") ") if poll_vote.poll_answer}.join(";")
          current_index += 1
        elsif poll_question.question_type == 3
          sheet1[count_row ,current_index] = user.poll_votes.where(:poll_question_id => poll_question.id).map{|poll_vote| poll_vote.vote_text.gsub(/<\/?.*?>/,"").gsub(/&nbsp;/," ")}.join(";")
          current_index += 1
        else
          poll_question.poll_answers.reorder("answer_position asc").each do |ans|
            poll_vote = user.poll_votes.where(:poll_question_id => poll_question.id, :poll_answer_id => ans.id).first
            sheet1[count_row ,current_index] = poll_vote.nil? ? "" : poll_vote.vote_text
            current_index += 1
          end
        end
      end
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end
end