# encoding: utf-8
class SubjectsController < ApplicationController
  layout 'base_subject'
  before_filter :require_login, :except => [:show]
  before_filter :check_authentication, :except => [:show]
  before_filter :find_subject, :except => [:index, :new, :create, :create_subject, :new_subject, :append_to_stage, :send_to_course]

  include ApplicationHelper
  include SubjectsHelper

  def index
    @tech_system = Repertoire.where(nil).order("updated_at asc")
    @order = params[:order] || "publish_time"
    @select = params[:select]
    @search = params[:search]
    # 为了本地版部署
    # if @order == "myshixun_count" && !request.host.include?("educoder")
    #   @order = "status = 2"
    # end
    if @select.blank?
      if @order == "myshixun_count"
        @subjects = Subject.find_by_sql("SELECT subjects.id, subjects.name, subjects.stages_count, subjects.status,
                            COUNT(myshixuns.id) AS myshixun_member_count FROM myshixuns, stage_shixuns, subjects
                            WHERE myshixuns.shixun_id = stage_shixuns.shixun_id AND stage_shixuns.subject_id = subjects.id
                            AND `subjects`.`hidden` = 0 AND `subjects`.`status` = 2 AND `subjects`.`name` like '%#{@search}%'
                            GROUP BY subjects.id ORDER BY myshixun_member_count DESC")
      elsif @order == "mine"
        subject_ids = StageShixun.where(:shixun_id => User.current.myshixuns.map(&:shixun_id)).map(&:subject_id) + User.current.subject_members.map(&:subject_id)
        @subjects = Subject.where(:id => subject_ids.uniq).where("name like '%#{@search}%'").reorder("updated_at desc")
      elsif @order == "updated_at"
        @subjects = Subject.where("hidden = 0 and name like '%#{@search}%' and status = 2").reorder("#{@order} desc")
      else
        @subjects = Subject.where("hidden = 0 and name like '%#{@search}%'").reorder("status = 2 desc, #{@order} asc")
      end
    else
      if @order == "myshixun_count"
        @subjects = Subject.find_by_sql("SELECT subjects.id, subjects.name, subjects.stages_count, subjects.status, COUNT(myshixuns.id) AS myshixun_member_count FROM myshixuns, stage_shixuns, subjects WHERE myshixuns.shixun_id = stage_shixuns.shixun_id AND stage_shixuns.subject_id = subjects.id AND `subjects`.`hidden` = 0 AND `subjects`.`status` = 2 AND `subjects`.`name` like '%#{@search}%' AND `subjects`.`repertoire_id` = #{@select} GROUP BY subjects.id ORDER BY myshixun_member_count DESC")
      elsif @order == "mine"
        subject_ids = StageShixun.where(:shixun_id => User.current.myshixuns.map(&:shixun_id)).map(&:subject_id) + User.current.subject_members.map(&:subject_id)
        @subjects = Subject.where(:id => subject_ids.uniq, :repertoire_id => @select.to_i).where("name like '%#{@search}%'").reorder("updated_at desc")
      elsif @order == "updated_at"
        @subjects = Subject.where("hidden = 0 and repertoire_id = #{@select.to_i} and name like '%#{@search}%' and status = 2").reorder("#{@order} desc")
      else
        @subjects = Subject.where("hidden = 0 and repertoire_id = #{@select.to_i} and name like '%#{@search}%'").reorder("status = 2 desc, #{@order} asc")
      end
    end

    @subjects = paginateHelper @subjects, 16
    respond_to do |format|
      format.js
      format.html { render :layout => "base_edu" }
    end
  end

  def show
    @stages = @subject.stages.includes(stage_shixuns: [{shixun: :users}])
    @is_member = User.current.member_of_subject?(@subject)
    @is_manager = User.current.manager_of_subject?(@subject)
    @admin = User.current.admin?
    @challenge_tags = ChallengeTag.where(:challenge_id => Challenge.where(:shixun_id => @subject.shixuns.where(:status => 2).pluck(:id)).pluck(:id)).pluck(:name).uniq
  end

  def new
    @subject = Subject.new
    render :layout => "base_edu"
  end

  def create
    ActiveRecord::Base.transaction do
      begin
        subject = Subject.create!(:name => params[:name], :learning_notes => params[:learning_notes], :description => params[:description], :user_id => User.current.id, :visits => 1, :status => 0)
        SubjectMember.create!(:subject_id => subject.id, :role => 1, :user_id => subject.user_id)
        redirect_to subject_path(subject)
      rescue Exception => e
        logger.error("create subject error info: #{e}")
        redirect_to new_subject_path
      end
    end
  end

  def edit
    render :layout => "base_edu"
  end

  def update
    @subject.update_attributes(:name => params[:name], :learning_notes => params[:learning_notes], :description => params[:description])
    redirect_to subject_path(@subject)
  end

  def destroy
    if @subject
      ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).destroy_all
      @subject.destroy
      respond_to do |format|
        format.js
        format.html{redirect_to subjects_path}
      end
    end
  end

  def send_to_course
    params[:shixun_ids].each do |shixun_id|
      shixun = Shixun.where(:id => shixun_id).first
      if shixun.present? && shixun.status == 2
        homework = HomeworkCommon.new(:name => shixun.name, :description => shixun.description, :anonymous_comment => 1, :homework_type => 4, :late_penalty => 5, :teacher_priority => 1, :user_id => User.current.id, :course_id => params[:course_id])

        homework_detail_manual = HomeworkDetailManual.new(:te_proportion => 1.0, :ta_proportion => 0, :comment_status => 0, :evaluation_num => 0, :absence_penalty => 0)
        homework.homework_detail_manual = homework_detail_manual

        if homework.save
          homework_detail_manual.save if homework_detail_manual
          HomeworkCommonsShixuns.create(:homework_common_id => homework.id, :shixun_id => shixun.id)
          create_shixun_homework_cha_setting homework, shixun
          create_works_list homework
        end
      end
    end
    redirect_to homework_common_index_path(:course => params[:course_id], :homework_type => 4)
  end

  def update_attr
    if params[:name]
      @subject.update_attributes(:name => params[:name])
    elsif params[:description]
      @subject.update_attributes(:description => params[:description])
    end
  end

  def new_subject
    if Course.where(:tea_id => User.current.id).count > 0
      @status = 1
      @course_lists = CourseList.where(:id => ShixunMajorCourse.where(:shixun_id => Shixun.where(:user_id => User.current.id).map(&:id)).map(&:course_list_id))
    else
      @status = 0
    end
    respond_to do |format|
      format.js
    end
  end

  def create_subject
    if params[:course_list_id]
      course = CourseList.find params[:course_list_id]
      if course
        subject = Subject.create(:name => course.name, :user_id => User.current.id, :visits => 0, :status => 0, :course_list_id => course.id)
      end
    end
    redirect_to subject_path(subject)
  end

  def choose_subject_shixun
    #course_list = @subject.course_list
    @search = params[:search]
     @type = params[:type]
    if User.current.admin?
      @shixuns = Shixun.select([:id, :name, :status, :myshixuns_count, :identifier])
      published_shixun_ids = Shixun.pluck(:id)
      tag_ids = ShixunTagRepertoire.where(:shixun_id => published_shixun_ids).pluck(:tag_repertoire_id).uniq
      @tags = TagRepertoire.select([:id, :name]).where(:id => tag_ids)
    else
      shixun_ids = ShixunMember.where(:user_id => @subject.subject_members.map(&:user_id)).pluck(:shixun_id).uniq
      tag_ids = ShixunTagRepertoire.where(:shixun_id => shixun_ids).pluck(:tag_repertoire_id).uniq
      @tags = TagRepertoire.select([:id, :name]).where(:id => tag_ids)
      @shixuns = Shixun.select([:id, :name, :status, :myshixuns_count, :identifier]).where(:id => shixun_ids)
    end
    if params[:search]
      @shixuns = @shixuns.where("name like ?", "%#{@search}%")
    end

    unless @type.nil? || @type == "" || @type == "all"
      shixun_ids = ShixunTagRepertoire.where(:tag_repertoire_id => @type).pluck(:shixun_id).uniq
      @shixuns = @shixuns.select([:id, :name, :myshixuns_count, :identifier, :status]).where(:id => shixun_ids)
    end

    @shixuns = @shixuns.reorder("created_at desc")
    @limit = 10
    @page = params['page'] || 1
    @shixuns_count = @shixuns.size
    @total_pages = (@shixuns_count / 10.0).ceil
    @shixuns = paginateHelper @shixuns, @limit
    @shixuns = @shixuns.includes(:myshixuns)
    respond_to do |format|
      format.js
      format.json {
        render json: shixun_json_data(@shixuns)
      }
    end
  end

  def append_to_stage
    @shixuns = Shixun.where(:id => params[:shixun_homework]).reorder("id desc")
  end

  def publish
    apply = ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).order("created_at desc").first
    if apply && apply.status == 0
      @status = 0
    else
      #if Shixun.where(:id => @subject.stage_shixuns.map(&:shixun_id), :status => [0, 1]).count > 0
      #  @status = 2
      #else
        @subject.update_attributes(:status => 1)
        ApplyAction.create(:container_type => "ApplySubject", :container_id => @subject.id, :user_id => User.current.id, :status => 0)
        # notes = User.current.show_name.to_s + " 申请发布课程实训:<a href='#{subject_path(@subject)}'>#{@subject.name}</a>"
        # JournalsForMessage.create(:jour_id => 1, :jour_type => 'Principal', :user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
        begin
          status = Trustie::Sms.send(mobile: '18711011226', send_type:'publish_subject' , name: '管理员')
        rescue => e
          Rails.logger.error "发送验证码出错: #{e}"
        end
        @status = 1
     # end
    end
  end

  def cancel_publish
    apply = ApplyAction.where(:container_type => "ApplySubject", :container_id => @subject.id).order("created_at desc").first
    if apply && apply.status == 0
      apply.update_attributes(:status => 3)
      apply.tidings.destroy_all
    end
    @subject.update_attributes(:status => 0)
    redirect_to subject_path(@subject)
  end

  def cancel_has_publish
    @subject.update_attributes(:status => 0)
    redirect_to subject_path(@subject)
  end


  def add_collaborators
    if !params[:search].nil?
      member_ids = "(" + @subject.subject_members.map(&:user_id).join(',') +  ")"
      condition = "%#{params[:search].strip}%".gsub(" ","")
      @users = User.where("id not in #{member_ids} and status = 1 and LOWER(concat(lastname, firstname, login, mail)) LIKE '#{condition}'").includes(:user_extensions)
    end
  end

  def add_subject_members
    unless params[:membership][:user_ids].blank?
      memberships = params[:membership][:user_ids]
      memberships.each do |member|
        user = User.find(member)
        SubjectMember.create!(:user_id => member, :subject_id => @subject.id, :role => 2)
      end
    end
  end

  def delete_member
    member = @subject.subject_members.where(:user_id => params[:mem_id]).first
    member.destroy if member
  end

  def statistics
    @learn_count = @subject.subject_users
    shixun_ids = @subject.stage_shixuns.pluck(:shixun_id)
    homework_common_id = HomeworkCommonsShixuns.where(:shixun_id => shixun_ids).pluck(:homework_common_id).uniq
    homework_common_id = homework_common_id.blank? ? -1 : homework_common_id.join(",")
    # 受用课堂(已经发布的实训(在此路径中的实训)作业的个数)
    homework_common_id = HomeworkDetailManual.where("homework_common_id in(#{homework_common_id}) and comment_status > 0").pluck(:homework_common_id)
    course_ids = HomeworkCommon.where(:id => homework_common_id).pluck(:course_id).uniq
    @course_count = course_ids.count
    course_ids = course_ids.blank? ? -1 : course_ids.join(",")
    # 受用院校
    user_ids = Myshixun.where(:shixun_id => shixun_ids).pluck(:user_id).uniq
    school_ids = UserExtensions.where(:user_id => user_ids).pluck(:school_id).uniq
    @schools_count = school_ids.count

    # type 1: 采用课堂情况+章节使用情况 2:实训使用详情 + 实训学习统计 3: 院校学习情况
    if params[:type].to_i == 3
      @schools = School.select([:id, :name]).where(:id => school_ids)
      @schools =
          @schools.map do |s|
            users = UserExtensions.where(:school_id => s.id, :user_id => user_ids).pluck(:user_id)
            student_count = users.count
            pass_count = Myshixun.where(:user_id => users, :status => 1).pluck(:user_id).uniq.count
            unpass_count = student_count - pass_count
            ss = s.attributes.dup.merge({student_count: student_count, pass_count: pass_count, unpass_count: unpass_count}).to_json
            JSON.parse(ss)
          end
      @schools = @schools.sort{|x,y| y['student_count'] <=> x['student_count']}.first(10)

    elsif params[:type].to_i == 2
      @stages = @subject.stages.select([:id, :position]).includes(stage_shixuns: [{shixun: {myshixuns: {user: :user_extensions}}}])
    else
      # 采用课堂情况
      courses = Course.where("is_delete = 0 and id in (#{course_ids}) and school_id is not null")
      school_ids = courses.map(&:school_id).uniq
      @schools = School.select([:id, :name]).where(:id => school_ids)
      @schools =
          @schools.map do |s|
            school_courses = courses.where(:school_id => s.id)
            course_count = school_courses.count
            course_student_ids = []
            school_courses.each do |c|
              course_student_ids += c.student.map(&:student_id)
            end
            student_count = course_student_ids.uniq.size
            homework_count = HomeworkCommon.find_by_sql("select count(*) cnt from homework_commons hc join courses c on hc.course_id = c.id
                                             where c.school_id = #{s.id} and hc.id in(#{homework_common_id.join(",")})").first.try(:cnt)
            ss = s.attributes.dup.merge({course_count: course_count, student_count: student_count,homework_count: homework_count}).to_json
            JSON.parse(ss)
          end
      @schools = @schools.sort{|x,y| y['homework_count'] <=> x['homework_count']}

      @schools = paginateHelper @schools, 10
      # TODO: 这个可以异步加载,让页面刷新完成后再加载图形数据
      # 章节使用情况
      @stage_user_info = []
      sum = 0 #总数
      @subject.stages.includes(:stage_shixuns).each do |stage|
        shixun_ids = stage.stage_shixuns.pluck(:shixun_id)
        if shixun_ids.present?
          homework_common_id = HomeworkCommonsShixuns.where(:shixun_id => shixun_ids).pluck(:homework_common_id).uniq
          if homework_common_id.present?
            publish_homework  = HomeworkDetailManual.where("homework_common_id in(#{homework_common_id.join(",")}) and comment_status > 0").pluck(:homework_common_id)
            use_count = publish_homework.present? ? HomeworkCommon.find_by_sql("select count(*) cnt from homework_commons hc join courses c on hc.course_id = c.id
                                              where hc.id in(#{publish_homework.join(",")}) and c.school_id is not null").first.try(:cnt) : 0
            sum += use_count
          else
            sum += 0
            use_count = 0
          end
          @stage_user_info << use_count
        else
          sum += 0
          @stage_user_info << 0
        end
      end
      # 章节占整体的百分数
      @stage_user_info = @stage_user_info.map{|x| sum ==0 ? 0 : (x * 100 / sum.to_f).round}
      @data = []
      @data_info = []
      @stage_user_info.each_with_index do |s, index|
        @data << "第#{index + 1}章"
        @data_info << { value: s, name:"第#{index + 1}章"}
      end
    end

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


  private
  # Find subject of id params[:id]
  def find_subject
    @subject = Subject.find_by_id(params[:id])
    render_404 if @subject.nil?
  rescue ActiveRecord::RecordNotFound
    render_404
  end
end