#encoding: utf-8
# Redmine - project management software
# Copyright (C) 2006-2013  Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

class UsersController < ApplicationController

  layout :setting_layout
  #Added by young
  before_filter :auth_login1, :only => [:show, :user_activities, :user_newfeedback]
  before_filter :logged_user_by_apptoken, :only => [:show, :user_newfeedback]
  menu_item :activity
  menu_item :user_information, :only => :info
  menu_item :user_course, :only => :user_courses
  menu_item :user_homework, :only => :user_homeworks
  menu_item :student_homework, :only => :student_homeworks
  menu_item :user_project, :only => [:user_projects, :watch_projects]
  menu_item :requirement_focus, :only => :watch_contests
  menu_item :user_newfeedback, :only => :user_newfeedback
  menu_item :user_messages, :only => :user_messages


  #
  before_filter :can_show_course, :only => [:user_courses, :user_homeworks]
  before_filter :check_authentication, :except => [:name_update, :realname_update, :update_user_pro, :update_user_location, :send_message_to_administrator, :show_or_hide_realname]

  before_filter :find_user, :only => [:user_fanslist, :user_watchlist, :show, :edit, :update, :destroy, :edit_membership, :user_courses, :unsolved_issues_list, :unfinished_homework_list, :user_manage_homeworks,
                                      :unfinished_poll_list, :user_homeworks, :student_homeworks, :destroy_membership, :user_activities, :user_projects, :user_newfeedback, :user_comments, :update_message_viewed,
                                      :anonymous_evaluation_list, :unfinished_test_list, :watch_contests, :info, :watch_projects, :show_score, :topic_score_index, :project_score_index, :user_receive_homeworks,
                                      :unapproval_applied_list, :activity_score_index, :influence_score_index, :score_index, :show_new_score, :topic_new_score_index, :project_new_score_index,
                                      :activity_new_score_index, :influence_new_score_index, :score_new_index, :user_projects_index, :user_resource, :user_contestlist, :user_manage_issues, :user_receive_issues,
                                      :user_courses4show, :user_projects4show, :user_contests4show, :user_course_activities, :user_project_activities, :user_feedback4show, :user_visitorlist, :user_messages, :edit_brief_introduction,
                                      :user_import_homeworks, :user_search_homeworks, :user_import_resource, :user_system_messages, :choose_user_course, :user_courselist, :user_projectlist, :sort_syllabus_list,
                                      :sort_project_list, :my_homeworks, :manage_or_receive_homeworks, :search_m_r_homeworks, :cancel_or_collect, :expand_courses, :homepage, :user_issues, :course_community, :project_community, :contest_community,
                                      :shixuns, :user_show_course_list, :ele_switch, :user_wathlist_and_fanslist, :growth_record, :user_grade, :user_experience, :reward_credit, :name_update, :realname_update, :user_tidings, :private_messages,
                                      :attendance, :update_user_pro, :update_user_location, :show_or_hide_realname, :user_info, :message_pop, :send_message, :message_detail, :delete_message, :reply_message]
  before_filter :auth_user_extension, only: :show
  before_filter :show_system_message, :only => [:show]
  #before_filter :rest_user_score, only: :show
  #before_filter :select_entry, only: :user_projects
  accept_api_auth :index, :show, :create, :update, :destroy, :tag_save, :tag_saveEx

  #william
  before_filter :require_login, :only => [:tag_save, :tag_saveEx]
  #before_filter :refresh_changests, :only =>[:user_activities,:user_courses,:user_projects,:user_newfeedback]

  #visitor
  before_filter :recorded_visitor, :only => [:show, :user_fanslist, :user_watchlist, :user_visitorlist]

  helper :sort
  helper :attachments
  include SortHelper
  include ApplicationHelper
  helper :custom_fields
  include CustomFieldsHelper
  include AvatarHelper
  include WordsHelper
  include GitlabHelper
  include UserScoreHelper
  include ActionView::Helpers::NumberHelper
  include ActionView::Helpers::TextHelper

  include PollHelper
  helper :user_score
  helper :journals

  # added by liuping 关注

  helper :watchers
  helper :activities

  ### added by william
  include ActsAsTaggableOn::TagsHelper

  #  fq
  helper :words
  helper :project_score
  helper :issues
  include UsersHelper
  require 'iconv'
  # 获取我的任务
  # order 排序条件
  # subject 主题:搜索用(注意:搜索和列表调用同一方法,通过参数或者remote区分)
  def user_issues
    @type = params[:type] unless params[:type].nil?
    @subject = params[:subject]
    # author_id = params[:author_id]
    params[:assigned_to_id].to_i == 0 ? @assigned_to = nil : @assigned_to = params[:assigned_to_id].to_i
    params[:author_id].to_i == 0 ? author_id = nil : author_id = params[:author_id].to_i
    params[:project_id].to_i == 0 ? @project_id = nil : @project_id = params[:project_id]
    if @project_id.nil?
      if @assigned_to.nil?
        if author_id.nil?
          @issues = Issue.where("(author_id =? or assigned_to_id =? ) and subject like ?",
                                @user.id, @user.id, "%#{@subject}%").order('updated_on desc')
        else
          @issues = Issue.where("author_id =?  and subject like ?",
                                author_id, "%#{@subject}%").order('updated_on desc')
        end
      else
        @issues = Issue.where("assigned_to_id =? and subject like ?", @assigned_to, "%#{@subject}%").order('updated_on desc')
      end

    else
      if @assigned_to.nil?
        if author_id.nil?
          @issues = Issue.where("(author_id =? or assigned_to_id =? ) and project_id=? and subject like ?",
                                (author_id ? author_id : @user.id), @user.id, @project_id, "%#{@subject}%").order('updated_on desc')
        else
          @issues = Issue.where("author_id =? and project_id=? and subject like ?",
                                author_id, @project_id, "%#{@subject}%").order('updated_on desc')
        end
      else
        @issues = Issue.where("assigned_to_id =? and project_id=? and subject like ?",
                              @assigned_to, @project_id, "%#{@subject}%").order('updated_on desc')
      end
    end
    @issues_filter = Issue.where("author_id =? or assigned_to_id =?", (author_id ? author_id : @user.id), @user).order('updated_on desc')
    @issues_assigned_count = Issue.where("assigned_to_id =? and subject like ?", @user.id, "%#{@subject}%").count
    @issues_author_count = Issue.where("author_id =? and subject like ?", @user.id, "%#{@subject}%").count
    @issue_open_count = Issue.where(" (author_id =? or assigned_to_id =?) and status_id in (1,2,3,4,6)", (author_id ? author_id : @user.id), @user).count
    @issue_close_count = Issue.where("(author_id =? or assigned_to_id =?) and status_id = 5", (author_id ? author_id : @user.id), @user.id).count

    # 导出excel的issues
    @excel_issues = @issues

    @issue_count = @issues.count
    @limit = 10
    @is_remote = true
    @issue_pages = Paginator.new @issue_count, @limit, params['page'] || 1
    @offset ||= @issue_pages.offset
    @issues = paginateHelper @issues, @limit

    respond_to do |format|
      format.html {render :layout => 'static_base'}
      format.xls {
        filename = "我的_#{l(:label_issue_list_xls)}.xls"
        send_data(issue_list_xls(@excel_issues), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
      format.api
      format.js
    end
  end

  # 超级管理员与实训管理员公用
  def modify_script
    render_403 unless User.current.admin?
    @mirror = MirrorRepository.find(params[:mirror_id])
    if params[:mirror_script_id]
      @mirror_script = MirrorScript.where(:id => params[:mirror_script_id]).first
    else
      @mirror_script = @mirror.mirror_scripts.first
    end
    respond_to do |format|
      format.html {render :layout => "base_edu"}
      format.js
    end
  end

  def update_script
    render_403 unless User.current.admin?
    script = MirrorScript.where(:script_type => params[:script_type]).first
    if script
      script.update_attributes(:description => params[:description], :script => params[:script])
    else
      script = MirrorScript.create(:mirror_repository_id => params[:mirror_id], :script => params[:script], :script_type => params[:script_type], :description => params[:description])
    end
    redirect_to modify_script_users_path(:mirror_id => params[:mirror_id], :mirror_script_id => script.id)
  end

  def delete_script
    render_403 unless User.current.admin?
    script = MirrorScript.where(:id => params[:mirror_script_id]).first
    script.delete
    redirect_to modify_script_users_path(:mirror_id => params[:mirror_id])
  end

  # 我发布的issue
  def user_manage_issues
    @manage_issues = "我发布的Issue"
    # 排序(默认以更新时间降序)
    order = "updated_on desc"
    if params[:reorder_release_time]
      order = "created_on #{params[:reorder_release_time]}"
    elsif params[:reorder_turnover_time]
      order = "updated_on #{params[:reorder_turnover_time]}"
    end

    @subject = params[:subject]
    params[:assigned_to_id].to_i == 0 ? @assigned_to = nil : @assigned_to = params[:assigned_to_id].to_i
    params[:author_id].to_i == 0 ? author_id = nil : author_id = params[:author_id].to_i
    params[:project_id].to_i == 0 ? @project_id = nil : @project_id = params[:project_id]
    if @project_id.nil?
      @issues = Issue.where("author_id =?  and subject like ?",
                            @user.id, "%#{@subject}%").order(order)
    else
      @issues = Issue.where("author_id =? and project_id=? and subject like ?",
                            @user.id, @project_id, "%#{@subject}%").order(order)
    end
    @issues_filter = Issue.where("author_id =?", @user.id)
    @issue_open_count = @issues_filter.where(:status_id => [1, 2, 3, 4, 6]).count
    @issue_close_count = @issues_filter.where(:status_id => 5).count
    # @issue_open_count = Issue.where(:author_id => @user.id, :status_id => [1, 2, 3, 4, 6]).count
    # @issue_close_count = Issue.where(:author_id => @user.id, :status_id => 5).count

    # 导出excel的issues
    @excel_issues = @issues
    @issue_count = @issues.count
    @limit = 10
    @is_remote = true
    @issue_pages = Paginator.new @issue_count, @limit, params['page'] || 1
    @offset ||= @issue_pages.offset
    @issues = paginateHelper @issues, @limit
    # @issues.limit(@issue_pages.per_page).offset(@issue_pages.offset).reorder(order).all
    respond_to do |format|
      format.html {render :layout => 'static_base'}
      format.xls {
        filename = "我发布的#{l(:label_issue_list_xls)}.xls"
        send_data(issue_list_xls(@excel_issues), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
      format.api
      format.js
    end
  end

  # 消息
  def user_tidings
    if User.current == @user || User.current.admin?
      @onclick_time = User.current.onclick_time.onclick_time
      User.current.onclick_time.update_attribute(:onclick_time, Time.now)
      @tids = @user.tidings
      if params[:type]
        case params[:type]
          when "course"
            type_list = ["HomeworkCommon", "Exercise", "Poll", "GraduationTask", "GraduationTopic"]
          when "project"
            type_list = ["Project"]
          when "apply"
            type_list = ["Apply"]
          when "system"
            type_list = ["System"]
          when "interactive"
            type_list = ["Comment", "Mentioned", "Praise", "Fan"]
        end
        @tids = @tids.where(:tiding_type => type_list)
      else
        @new_tids_count = @tids.where("created_at > '#{@onclick_time}'").count
        @new_mess_count = @user.private_messages.where("status = 0").group(:target_id).length
      end
      limit = 10
      @page = params['page'] || 1
      @tids = paginateHelper @tids, limit
      respond_to do |format|
        format.js
        format.html {render :layout => "base_edu_user"}
      end
    else
      render_403
    end
  end

  # 私信
  def private_messages
    if User.current == @user || User.current.admin?
      @onclick_time = User.current.onclick_time.onclick_time
      User.current.onclick_time.update_attribute(:onclick_time, Time.now)
      @messages = PrivateMessage.find_by_sql("SELECT ui.* FROM (SELECT * FROM private_messages WHERE STATUS != 2 AND user_id = #{@user.id} ORDER BY id DESC) ui GROUP BY ui.target_id ORDER BY ui.send_time DESC")

      @new_tids_count = @user.tidings.where("created_at > '#{@onclick_time}'").count
      @new_mess_count = 0
      limit = 10
      @page = params['page'] || 1
      @messages = paginateHelper @messages, limit
      respond_to do |format|
        format.js
        format.html {render :layout => "base_edu_user"}
      end
    else
      render_403
    end
  end

  def message_pop
    if params[:search] && params[:search].strip != ""
      @users = User.where("id != #{@user.id} and status = 1 and LOWER(concat(lastname, firstname, nickname)) LIKE '%#{params[:search]}%'").includes(:user_extensions)
      @user_type = 1
    else
      @users = User.where(:id => @user.private_messages.map(&:target_id)).includes(:user_extensions)
      @user_type = 2
    end
    respond_to do |format|
      format.js
    end
  end

  def send_message
    if params[:target_id] && params[:content]
      PrivateMessage.create(:user_id => @user.id, :target_id => params[:target_id], :sender_id => @user.id, :receiver_id => params[:target_id], :content => params[:content], :send_time => Time.now, :status => 1)
      PrivateMessage.create(:user_id => params[:target_id], :target_id => @user.id, :sender_id => @user.id, :receiver_id => params[:target_id], :content => params[:content], :send_time => Time.now, :status => 0)
    end
    redirect_to message_detail_user_path(@user, :user_id => params[:target_id])
  end

  def message_detail
    if User.current == @user || User.current.admin?
      @target_user = User.where(:id => params[:user_id]).includes(:user_extensions).first
      if @target_user.present?
        @message_list = @user.private_messages.where(:target_id => params[:user_id], :status => [0, 1]).order("send_time asc")
        @user.private_messages.where(:target_id => params[:user_id], :status => 0).update_all(:status => 1)
        @onclick_time = User.current.onclick_time.onclick_time
        User.current.onclick_time.update_attribute(:onclick_time, Time.now)
        @new_tids_count = @user.tidings.where("created_at > '#{@onclick_time}'").count
        @new_mess_count = 0
        @messages = PrivateMessage.find_by_sql("SELECT ui.* FROM (SELECT * FROM private_messages WHERE STATUS != 2 AND user_id = #{@user.id} ORDER BY id DESC) ui GROUP BY ui.target_id ORDER BY ui.send_time DESC")
        respond_to do |format|
          format.html {render :layout => "base_edu_user"}
        end
      else
        render_404
      end
    else
      render_403
    end
  end

  def reply_message
    if params[:target_id] && params[:content]
      PrivateMessage.create(:user_id => @user.id, :target_id => params[:target_id], :sender_id => @user.id, :receiver_id => params[:target_id], :content => params[:content], :send_time => Time.now, :status => 1)
      PrivateMessage.create(:user_id => params[:target_id], :target_id => @user.id, :sender_id => @user.id, :receiver_id => params[:target_id], :content => params[:content], :send_time => Time.now, :status => 0)
    end
    @target_user = User.where(:id => params[:target_id]).includes(:user_extensions).first
    @message_list = @user.private_messages.where(:target_id => params[:target_id], :status => [0, 1]).order("send_time asc")
    @messages = PrivateMessage.find_by_sql("SELECT ui.* FROM (SELECT * FROM private_messages WHERE STATUS != 2 AND user_id = #{@user.id} ORDER BY id DESC) ui GROUP BY ui.target_id ORDER BY ui.send_time DESC")
  end

  def delete_message
    @message = PrivateMessage.where(:id => params[:mess_id]).first
    @message.update_attribute("status", 2) if @message.present?
    @target_user = User.where(:id => @message.target_id).includes(:user_extensions).first
    @messages = PrivateMessage.find_by_sql("SELECT ui.* FROM (SELECT * FROM private_messages WHERE STATUS != 2 AND user_id = #{@user.id} ORDER BY id DESC) ui GROUP BY ui.target_id ORDER BY ui.send_time DESC")
  end

  # 我收到的issue
  def user_receive_issues
    @receive_issues = "我收到的Issue"
    # 排序(默认以更新时间降序)
    order = "updated_on desc"
    if params[:reorder_release_time]
      order = "created_on #{params[:reorder_release_time]}"
    elsif params[:reorder_turnover_time]
      order = "updated_on #{params[:reorder_turnover_time]}"
    end

    @subject = params[:subject]
    params[:assigned_to_id].to_i == 0 ? @assigned_to = nil : @assigned_to = params[:assigned_to_id].to_i
    params[:author_id].to_i == 0 ? author_id = nil : author_id = params[:author_id].to_i
    params[:project_id].to_i == 0 ? @project_id = nil : @project_id = params[:project_id]
    if @project_id.nil?
      @issues = Issue.where("assigned_to_id =?  and subject like ?",
                            @user.id, "%#{@subject}%").order(order)
    else
      @issues = Issue.where("assigned_to_id =? and project_id=? and subject like ?",
                            @user.id, @project_id, "%#{@subject}%").order(order)
    end
    @issues_filter = Issue.where("assigned_to_id =?", @user.id)
    @issue_open_count = @issues_filter.where(:status_id => [1, 2, 3, 4, 6]).count
    @issue_close_count = @issues_filter.where(:status_id => 5).count

    # 导出excel的issues
    @excel_issues = @issues
    @issue_count = @issues.count
    @limit = 10
    @is_remote = true
    @issue_pages = Paginator.new @issue_count, @limit, params['page'] || 1
    @offset ||= @issue_pages.offset
    @issues = paginateHelper @issues, @limit
    # @issues.limit(@issue_pages.per_page).offset(@issue_pages.offset).reorder(order).all
    respond_to do |format|
      format.html {render :layout => 'static_base'}
      format.xls {
        filename = "我收到的#{l(:label_issue_list_xls)}.xls"
        send_data(issue_list_xls(@excel_issues), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
      format.api
      format.js
    end
  end

  #展开所有回复
  def show_all_replies
    case params[:type]
      when 'JournalsForMessage'
        @comment = JournalsForMessage.find params[:comment].to_i
      when 'Message', 'is_project_message'
        @comment = Message.find params[:comment].to_i
      when 'BlogComment'
        @comment = BlogComment.find params[:comment].to_i
      when 'OrgDocumentComment'
        @comment = OrgDocumentComment.find params[:comment].to_i
      when 'Comment'
        @comment = Comment.find params[:comment].to_i
      when 'Journal', 'is_project_issue'
        @comment = Journal.find params[:comment].to_i
      when 'Memo'
        @comment = Memo.find params[:comment].to_i
      when 'Discuss'
        @comment = Discuss.find params[:comment].to_i
    end
    @user_activity_id = params[:user_activity_id]
    @parent_id = params[:parent_id] if params[:parent_id]
  end


  # 实训用户图片显示
  # 中间层克隆的代码挂在到educo
  # der的files目录下,所以只用去找目录下的图片即可
  # params: workspace_path 中间挂载目录的路径
  #        answer_path 用户评测生成图片的路径;answer_picture 标准答案的路径;
  # 类型type: image; qrcode二维码; html网页
  def picture_show
    @type = "image"
    if params[:game_id].present?
      conv = Iconv.new("GBK", "utf-8")
      game = Game.find(params[:game_id])
      @game_challenge = game.challenge
      type = @game_challenge.show_type
      workspace_path = game.try(:picture_path)
      @answer_path = "#{Rails.root}/#{workspace_path}/#{@game_challenge.expect_picture_path}"
      @user_path = "#{Rails.root}/#{workspace_path}/#{@game_challenge.picture_path}"
      @original_path = "#{Rails.root}/#{workspace_path}/#{@game_challenge.original_picture_path}"

      @answer_picture = @game_challenge.expect_picture_path.nil? ? [] : get_dir_filename(@answer_path, type, game.id)
      @answer_picture = @answer_picture.sort {|x, y| conv.iconv(x) <=> conv.iconv(y)} if @answer_picture.present?

      @user_picture = @game_challenge.picture_path.nil? ? [] : get_dir_filename(@user_path, type, game.id)
      @user_picture = @user_picture.sort {|x, y| conv.iconv(x) <=> conv.iconv(y)}
      if @game_challenge.original_picture_path.blank?
        @orignal_picture = nil
      else
        @orignal_picture = @game_challenge.original_picture_path.nil? ? [] : get_dir_filename(@original_path, type, game.id)
        @orignal_picture = @orignal_picture.sort {|x, y| conv.iconv(x) <=> conv.iconv(y)}
      end
      respond_to do |format|
        format.js
      end
    end
  end

  def attachment_show
    file_name = params[:file_name]
    path = params[:path]
    send_file "#{path}/#{file_name}", :filename => "#{file_name}",
              :type => 'game',
              :disposition => 'attachment' #inline can open in browser
  end

  def html_show
    @contents = File.read("#{params[:path]}")
    respond_to do |format|
      format.html {render :layout => false}
    end
  end

  #二级回复
  def reply_to
    @is_project = params[:is_project]

    case params[:type]
      when 'HomeworkCommon', 'Work', 'GraduationTopic', 'GraduationTask'
        @reply = JournalsForMessage.find params[:reply_id]
        @type = params[:type]
        if params[:user_activity_id]
          @user_activity_id = params[:user_activity_id]
        else
          @user_activity_id = -1
        end
      when 'JournalsForMessage'
        @reply = JournalsForMessage.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'JournalsForMessage'
      when 'Message'
        @reply = Message.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'Message'
      when 'BlogComment'
        @reply = BlogComment.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'BlogComment'
      when 'OrgDocumentComment'
        @reply = OrgDocumentComment.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'OrgDocumentComment'
      when 'News'
        @reply = Comment.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'News'
      when 'Issue'
        @reply = Journal.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'Issue'
      when 'Training_task'
        @reply = Journal.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'Training_task'
      when 'Syllabus'
        @reply = JournalsForMessage.find params[:reply_id]
        @type = 'Syllabus'
      when 'Memo'
        @reply = Memo.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'Memo'
      when 'Challenge'
        @reply = Discuss.find params[:reply_id]
        @user_activity_id = params[:user_activity_id]
        @activity_id = params[:activity_id]
        @type = 'Challenge'
    end
    respond_to do |format|
      format.js
    end
  end

  #叠层回复框中的回复
  def reply_to_comment
    @type = params[:type]
    @reply = get_reply_by_type @type, params[:reply_id]
    @parent_id = params[:parent_id] if params[:parent_id]
    @user_activity_id = params[:user_activity_id]
    @is_project = params[:is_project] if params[:is_project]
    respond_to do |format|
      format.js
    end
  end

  #多级回复
  def reply_detail
    @type = params[:type]
    reply = get_reply_by_type @type, params[:reply_id]
    if @type == 'JournalsForMessage'
      if reply.jour_type == "HomeworkCommon" || reply.jour_type == "Work" || reply.jour_type == "Syllabus" || reply.jour_type == "GraduationTopic" || reply.jour_type == "GraduationTask"
        @type = reply.jour_type
      end
    end
    @user_activity_id = params[:user_activity_id]
    case @type
      when 'HomeworkCommon'
        @root = HomeworkCommon.find reply.jour_id
        @homework = @root
        options = {:notes => params[:reply_message], :reply_id => reply.user_id, :user_id => User.current.id, :m_parent_id => params[:reply_id].to_i, :m_reply_id => params[:reply_id].to_i, :root_id => reply.root_id}
        comment = HomeworkCommon.add_homework_jour(User.current, params[:reply_message], reply.jour_id, reply.root_id, options)
        @root.update_column('updated_at', Time.now)
        @is_teacher = User.current.allowed_to?(:as_teacher, @root.course) || User.current.admin?
      when 'GraduationTopic', 'GraduationTask'
        if @type == 'GraduationTopic'
          @root = GraduationTopic.find reply.jour_id
        elsif @type == 'GraduationTask'
          @root = GraduationTask.find reply.jour_id
        end
        comment = @root.journals_for_messages.build(:user_id => User.current.id, :notes => params[:reply_message], :reply_id => reply.user_id, :root_id => reply.root_id, :m_parent_id => params[:reply_id].to_i, :m_reply_id => params[:reply_id].to_i)
        if comment.save
          @root.update_column('updated_at', Time.now)
        end
      when 'Work'
        @root = Work.find reply.jour_id
        options = {:notes => params[:reply_message], :reply_id => reply.user_id, :user_id => User.current.id, :m_parent_id => params[:reply_id].to_i, :m_reply_id => params[:reply_id].to_i, :root_id => reply.root_id}
        comment = Work.add_work_jour(User.current, params[:reply_message], reply.jour_id, reply.root_id, options)
        @root.update_column('updated_at', Time.now)
        @is_teacher = User.current.admin_of_contest?(@root.contest) || User.current.admin?
      when 'JournalsForMessage'
        options = {:user_id => User.current.id,
                   :status => true,
                   :m_parent_id => params[:reply_id],
                   :m_reply_id => params[:reply_id],
                   :reply_id => reply.user.id,
                   :notes => params[:reply_message],
                   :root_id => reply.root_id,
                   :is_readed => false}
        @root = reply.root
        comment = add_reply_adapter(@root, options)
        @root.update_attribute(:updated_on, Time.now)
      when 'Message'
        @root = reply.root
        comment = Message.new
        comment.author = User.current
        comment.board = reply.board
        comment.content = params[:reply_message]
        comment.subject = "RE: #{@root.subject}"
        comment.reply_id = params[:reply_id]
        comment.root_id = reply.root_id
        reply.children << comment
        @is_project = params[:is_project] if params[:is_project]

        redirect_to message_replies_board_message_path(@root, :board_id => @root.board_id, :user_activity_id => params[:user_activity_id])
        return
      when 'BlogComment'
        @root = reply.root
        comment = BlogComment.new
        comment.author = User.current
        comment.blog = reply.blog
        comment.title = "RE: #{@root.title}"
        comment.content = params[:reply_message]
        comment.reply_id = params[:reply_id]
        comment.root_id = reply.root_id
        reply.children << comment
        # 评论后,给回复人发消息(如果是本人就不发)
        if comment.author.id != BlogComment.find(comment.reply_id).author_id
          BlogMessage.create(:user_id => BlogComment.find(comment.reply_id).author_id,
                             :blog_message_id => comment.id,
                             :blog_id => comment.blog_id,
                             :blog_message_type => "BlogComment",
                             :content => comment.content,
                             :user_operator_id => comment.author.id
          )
        end
      when 'OrgDocumentComment'
        @root = reply.root
        comment = OrgDocumentComment.new(:creator_id => User.current.id, :reply_id => params[:reply_id])
        comment.title = "RE:#{@root.title}"
        comment.content = params[:reply_message]
        comment.root_id = reply.root_id
        reply.children << comment
      when 'News', 'Comment'
        @root = News.find reply.commented_id
        comment = @root.comments.build(:author_id => User.current.id, :reply_id => params[:reply_id], :comments => params[:reply_message], :parent_id => reply.id)
        comment.save
      when 'Issue', 'Journal'
        @root = reply.issue
        comment = @root.journals.build(:user_id => User.current.id, :reply_id => params[:reply_id], :notes => params[:reply_message], :parent_id => reply.id)
        comment.save
        @is_project = params[:is_project] if params[:is_project]
      when 'TrainingTask'
        @root = reply.training_task
        comment = @root.journals.build(:user_id => User.current.id, :reply_id => params[:reply_id], :notes => params[:reply_message], :parent_id => reply.id)
        comment.save
        @is_project = params[:is_project] if params[:is_project]
      when 'Syllabus'
        @root = Syllabus.find reply.jour_id
        options = {:notes => params[:reply_message], :reply_id => reply.user_id, :user_id => User.current.id, :m_parent_id => params[:reply_id].to_i, :m_reply_id => params[:reply_id].to_i, :root_id => reply.root_id}
        comment = Syllabus.add_syllabus_jour(User.current, params[:reply_message], reply.jour_id, reply.root_id, options)
        @root.update_column('updated_at', Time.now)
        @count = @root.journals_for_messages.count
        @comments = @root.journals_for_messages.reorder("created_on desc").limit(3)
      when 'Memo'
        @root = reply.root
        comment = Memo.new
        comment.author = User.current
        comment.forum = reply.forum
        comment.content = params[:reply_message]
        comment.subject = "#{@root.subject}"
        comment.root_id = reply.root_id
        reply.children << comment
      when 'Challenge'
        @game_challenge = Challenge.where(:id => reply.challenge_id).first
        @root = reply.root
        comment = Discuss.new
        comment.user_id = User.current.id
        comment.content = params[:reply_message]
        comment.root_id = reply.root_id
        comment.challenge_id = reply.challenge_id
        comment.dis_type = "Shixun"
        comment.dis_id = @game_challenge.shixun.try(:id)
        comment.praise_count = 0
        reply.children << comment
        #@discusses = @game_challenge.shixun.discusses.reorder("created_at desc")
        redirect_to shixun_discuss_shixun_path(@game_challenge.shixun, :challenge_id => @game_challenge.id)
        return

    end
    update_course_activity(@root.class.to_s, @root.id)
    respond_to do |format|
      format.js
    end
  end

  def reward_credit
    unless User.current.admin?
      render_403
      return
    end
    container_id = params[:container_id]
    container_type = params[:container_type]
    @score = params[:score]

    Grade.create(:user_id => @user.id, :container_id => container_id, :container_type => container_type, :score => @score)
    @user.update_column(:grade, (@score.to_i + @user.grade.to_i))
    case container_type
      when 'Memo'
        @container = Memo.find(container_id)
        @score = @score.to_i + @container.reward.to_i
        @container.update_attribute(:reward, @score)
      when 'Discusses'
        @container = Discuss.find(container_id)
        @score = @score.to_i + @container.reward.to_i
        @container.update_attribute(:reward, @score)
    end
    respond_to do |format|
      format.js
    end
  end

  def reward_grade
    logger.info("#########################################")
    if User.current.admin?
      reward_user = User.find params[:user_id]
      Grade.create(:user_id => reward_user.id, :container_id => User.current.id, :container_type => params[:container_type], :score => params[:score])
      reward_user.update_column(:grade, (params[:score].to_i + reward_user.grade.to_i))
      @status = true
    else
      @status = false
    end
  end


  def refresh_changests
    if !(@user.nil?) && !(@user.memberships.nil?)
      @user.memberships.each do |member|
        unless member.project.nil?
          member.project.repository.fetch_changesets if Setting.autofetch_changesets?
        end
      end
    end
  end

  # 更新issue状态
  def user_act_issue_assign_to

  end

  #未读消息弹窗
  def user_messages_unviewed
    @message_alls = []
    messages = MessageAll.where("user_id =?", User.current.id).includes(:message).order("created_at desc")
    onclick_time = User.current.onclick_time.onclick_time
    messages.each do |message_all|
      # 未读的消息存放在数组
      mess = message_all.message
      if (message_all.message_type != "SystemMessage" && !mess.nil? && (mess.viewed == 0 || !mess.viewed)) || (message_all.message_type == "SystemMessage" && !mess.nil? && mess.created_at > onclick_time)
        unless (message_all.message_type == 'CourseMessage' && mess && mess.course && mess.course.is_delete == 1)
          @message_alls << mess
        end
        break if @message_alls.length == 10
      end
    end
  end

  # 用户消息
  # 说明: homework 发布作业;message:讨论区; news:新闻; poll:问卷;works_reviewers:作品评阅;works_reply:作品回复,exercise:课程测验
  # issue:问题;journal:缺陷状态更新; forum:公共贴吧: user_feedback: 用户留言; new_reply:新闻回复(comment)
=begin
  def user_messages
    if !User.current.logged?
      redirect_to signin_url
      return
    elsif @user != User.current && !User.current.admin?
      return render_403
    end
    # 初始化/更新 点击按钮时间, 24小时内显示系统消息
    update_onclick_time
    # 全部设为已读
    # if params[:viewed] == "all"
    #  update_message_viewed(@user)
    # end
    # @new_message_count = forge_querys.count + forum_querys.count + course_querys.count + user_querys.count
    courses = @user.courses.where("is_delete = 1")
    course_ids = courses.empty? ? "(-1)" : "(" + courses.map{|course| course.id}.join(",") + ")"
    case params[:type]
      when nil
        # 系统消息为管理员发送,我的消息中包含有系统消息
        @message_alls = []
        messages = MessageAll.where(:user_id => @user.id).includes(:message).order("created_at desc")
        messages.each do |message_all|
          mess = message_all.message
          unless (message_all.message_type == 'CourseMessage' && mess && mess.course && mess.course.is_delete == 1)
            @message_alls << mess
          end
        end
      when 'unviewed'
        @message_alls = []
        messages = MessageAll.where("message_alls.user_id =?", @user.id).includes(:message).order("created_at desc")
        messages.each do |message_all|
          # 在点击或者刷新消息列表后未读的消息存放在数组
          mess = message_all.message
          if message_all.message_type != "SystemMessage"&& !mess.nil? && (mess.viewed == 0 || !mess.viewed)
            unless (message_all.message_type == 'CourseMessage' && mess && mess.course  && mess.course.is_delete == 1)
              @message_alls << mess
            end
          end
        end
      #课程相关消息
      when 'homework'
        @message_alls = CourseMessage.where("course_message_type in ('HomeworkCommon','StudentWorksScore','JournalsForMessage','StudentWork','Exercise') and user_id =? and course_id NOT IN #{course_ids}",  @user.id).order("created_at desc")
      when 'course_message'
        @message_alls = CourseMessage.where("course_message_type =? and user_id =? and course_id NOT IN #{course_ids}", "Message", @user.id).order("created_at desc")
      when 'course_news'
        # 课程通知包含发布的通知和回复的通知
        @message_alls = CourseMessage.where("course_message_type in ('News', 'Comment') and user_id =? and course_id NOT IN #{course_ids}", @user.id).order("created_at desc")
      when 'poll'
        @message_alls = CourseMessage.where("course_message_type =? and user_id =? and course_id NOT IN #{course_ids}", "Poll", @user.id).order("created_at desc")
      #项目相关消息
      when 'issue'
        @message_alls = ForgeMessage.where("forge_message_type in ('Issue', 'Journal') and user_id =?" , @user.id).order("created_at desc")
      when 'forge_message'
        @message_alls = ForgeMessage.where("forge_message_type =? and user_id =?", "Message", @user.id).order("created_at desc")
      when 'forge_news'
        @message_alls = ForgeMessage.where("forge_message_type in (?,?) and user_id =?", "News", "Comment", @user.id).order("created_at desc")
      when 'apply'
        @message_alls = ForgeMessage.where("forge_message_type in ('ProjectInvite', 'AppliedProject', 'JoinProject', 'RemoveFromProject') and user_id =?", @user.id).order("created_at desc")
      #贴吧消息
      when 'forum'
        @message_alls = MemoMessage.where("memo_type =? and user_id =?", "Memo", @user.id).order("created_at desc")
      #用户留言
      when 'user_feedback'
        @message_alls = UserFeedbackMessage.where("journals_for_message_type =? and user_id =?", "JournalsForMessage", @user.id).order("created_at desc")
      else
        render_404
        return
    end

    @message_alls = paginateHelper @message_alls, 25
    respond_to do |format|
      format.js
      format.html{render :layout=>'new_base_user'}
    end
  end
=end

  # 初始化/更新 点击按钮时间
  def update_onclick_time
    # 记录当前点击按钮的时间
    # 考虑到用户未退出刷新消息页面
    message_time = OnclickTime.where("user_id =?", User.current).first
    if message_time.nil?
      message_new_time = OnclickTime.new
      message_new_time.user_id = User.current.id
      message_new_time.onclick_time = Time.now
      message_new_time.save
    else
      message_time.update_attributes(:onclick_time => Time.now)
    end
  end

  # 消息设置为已读
  def update_message_viewed
    if User.current.id == @user.id
      course_querys = CourseMessage.where("user_id =? and viewed =?", @user.id, 0)
      forge_querys = ForgeMessage.where("user_id =? and viewed =?", @user.id, 0)
      user_querys = UserFeedbackMessage.where("user_id =? and viewed =?", @user.id, 0)
      forum_querys = MemoMessage.where("user_id =? and viewed =?", @user.id, 0)
      org_querys = OrgMessage.where("user_id=? and viewed=0", @user.id)
      at_querys = AtMessage.where("user_id=? and viewed=0", @user.id)
      contest_querys = ContestMessage.where(:user_id => @user.id, :viewed => 0)
      blog_querys = BlogMessage.where(:user_id => @user.id, :viewed => 0)
      applied_querys = AppliedMessage.where("user_id=? and viewed =?", @user.id, 0)
      course_querys.update_all(:viewed => true) unless course_querys.nil?
      forge_querys.update_all(:viewed => true) unless forge_querys.nil?
      user_querys.update_all(:viewed => true) unless user_querys.nil?
      forum_querys.update_all(:viewed => true) unless forum_querys.nil?
      org_querys.update_all(:viewed => true) unless org_querys.nil?
      at_querys.update_all(:viewed => true) unless at_querys.nil?
      contest_querys.update_all(:viewed => true) unless contest_querys.nil?
      blog_querys.update_all(:viewed => true) unless blog_querys.nil?
      applied_querys.update_all(:viewed => true) unless applied_querys.nil?
    end
    redirect_to user_path(@user)
  end

  # 系统消息
  def user_system_messages
    @sytem_messages = SystemMessage.order("created_at desc").all
    @sytem_messages = paginateHelper @sytem_messages, 10
    respond_to do |format|
      format.html {render :layout => 'new_base_user'}
    end
  end

  def user_projects_index
    if User.current.admin?
      memberships = @user.memberships.all(conditions: "projects.project_type = #{Project::ProjectType_project}").first
    else
      cond = Project.visible_condition(User.current) + " AND projects.project_type <> 1"
      memberships = @user.memberships.all(:conditions => cond).first
    end
    watch_projects = Project.joins(:watchers).where("project_type <>? and watchable_type = ? and `watchers`.user_id = ?", '1', 'Project', @user.id).first
    if memberships.nil? && watch_projects
      redirect_to(:watch_projects_user) and return
    else
      redirect_to(:user_projects_user) and return
    end
  end

  #added by young
  def user_projects
    unless User.current.admin?
      if !@user.active? #|| (@user != User.current  && @memberships.empty? && events.empty?)
        render_404
        return
      end
    end
    projects = @user.projects.visible.select("projects.*,(SELECT MAX(created_at)  FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc")
    if (params[:status] == '1')
      projects = projects.where("projects.user_id = ?", @user.id)
    elsif (params[:status] == '2')
      projects = projects.where("projects.user_id <> ?", @user.id)
    end
    @list = paginateHelper projects, 10
    @params = params[:status]
    respond_to do |format|
      format.html {render :layout => 'base_users_new'}
      format.api
    end
  end

  # params: index 1 课程 / 2 实训
  #         search 搜索关键字
  def search_shixuns_or_courses
    @index = params[:index].to_i
    @search = params[:search].try(:strip)
    @limit = 16
    if 1 == @index
      # @shixuns_result = Shixun.where(:status => [2,3]).where("name like ?", "%#{@search}%").reorder("created_at desc")
      @shixuns_result = Shixun.where("name like ? and hidden=0", "%#{@search}%").reorder("myshixuns_count desc")
      @shixuns_result_count = @shixuns_result.count
      @shixun_pages = Paginator.new @shixuns_result_count, @limit, params['page'] || 1
      @offset ||= @shixun_pages.offset
      @shixuns_result = paginateHelper @shixuns_result, @limit
    elsif @index == 2
      @course_result = Course.where("is_end = 0 and is_delete = 0 and name like '%#{@search}%'").order("created_at desc")
      @course_result_count = @course_result.count
      @course_result_pages = Paginator.new @course_result_count, @limit, params['page'] || 1
      @offset ||= @course_result_pages.offset
      @course_result = paginateHelper @course_result, @limit
    else
      @user_result = User.find_by_sql("select * from users where concat(lastname,firstname) like '%#{@search}%'")
      @user_result_count = @user_result.count
      @user_pages = Paginator.new @user_result_count, @limit, params['page'] || 1
      @offset ||= @user_pages.offset
      @user_result = paginateHelper @user_result, @limit
    end
    
    respond_to do |format|
      format.html {render :layout => 'base_edu'}
    end
  end

  # 我发布的实训
  def shixuns
    @mail = User.current.mail.blank?
    @my_shixun = true
    filter = params[:filter]
    if filter == "shixun_cooperative"
      # 合作者的实训id
      id = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id} and role = 2").map(&:shixun_id)
      if @user == User.current
        @shixuns = Shixun.where(:id => id).order("updated_at desc")
      else
        @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
      end
    elsif filter == "shixun_create"
      if @user == User.current
        @shixuns = Shixun.where(:user_id => @user).order("updated_at desc")
      else
        @shixuns = Shixun.where(:user_id => @user).visible.order("updated_at desc")
      end
    elsif filter == "shixun_challenge"
      # 已挑战过
      id = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
      if @user == User.current
        @shixuns = Shixun.where(:id => id).order("updated_at desc")
      else
        @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
      end
    elsif
      # 合作者及创建者
    ids = Shixun.find_by_sql("select shixun_id from shixun_members where user_id=#{@user.id}")
      # 已挑战过
      ids2 = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
      ids = ids.map {|shixun| shixun.shixun_id} unless ids.blank?
      ids2 = ids2.map {|shixun| shixun.id} unless ids2.blank?
      id = ids + ids2
      id = id.uniq
      if @user == User.current
        @shixuns = Shixun.where(:id => id).order("updated_at desc")
      else
        @shixuns = Shixun.where(:id => id).visible.order("updated_at desc")
      end
    end
    @shixuns_count = @shixuns.count
    @limit = 10
    @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
    @offset ||= @shixun_pages.offset
    @shixuns = paginateHelper @shixuns, @limit
    respond_to do |format|
      format.html {render :layout => 'base_edu'}
      format.js
    end
  end

  def my_join_shixuns
    # 我参入的
    ids = Shixun.find_by_sql("select id from shixun_members where role=2 and user_id=#{@user.id}")
    ids2 = Shixun.find_by_sql("select id from shixuns where id in (select shixun_id from myshixuns where user_id = #{@user.id})")
    ids = ids.map {|shixun| shixun.id} unless ids.blank?
    ids2 = ids2.map {|shixun| shixun.id} unless ids2.blank?
    id = ids + ids2
    id = id.uniq
    @shixuns = Shixun.where(:id => id)
    @shixuns_count = @shixuns.count
    @limit = 10
    @shixun_pages = Paginator.new @shixuns_count, @limit, params['page'] || 1
    @offset ||= @shixun_pages.offset
    @shixuns = paginateHelper @shixuns, @limit
    respond_to do |format|
      format.html {render :layout => 'base_edu'}
    end
  end

  #处理加入课程成为教辅教师的请求
  #status 1 同意 2 拒绝
  def dealwith_apply_request
    @msg = CourseMessage.find(params[:msg_id])
    #CourseMessage content存的是role  7教辅  9 教师
    apply_user = User.find(@msg.course_message_id)
    ids = @msg.content.split(",") #  [@msg.content] msg content保存的是申请的职位角色
=begin
    integer_ids = []
    ids.each do |role_id|
      integer_ids << role_id.to_i
    end
=end
    case params[:agree]
      when 'Y'
        if apply_user.member_of_course?(Course.find(@msg.course_id))
          #将角色改为老师或者教辅
          member = Course.find(@msg.course_id).members.where(:user_id => apply_user.id).first
          member.role_ids = member.role_ids + ids
=begin
          #删除为学生的记录
          unless member.role_ids.include?(10)
            joined = StudentsForCourse.where('student_id = ? and course_id = ?', member.user_id, @msg.course_id)
            joined.each do |join|
              join.delete
            end
          end
=end

          # member.course_group_id = 0
          member.save
          # CourseMessage.create(:user_id => @msg.course_message_id, :course_id => @msg.course_id, :viewed => false,:course_message_id=>User.current.id,:content=>@msg.content,:course_message_type=>'CourseRequestDealResult',:status=>1)
          @msg.update_attributes(:status => 1, :viewed => 1, :apply_user_id => User.current.id)

        else
          members = []
          members << Member.new(:role_ids => ids, :user_id => @msg.course_message_id)
          Course.find(@msg.course_id).members << members
          # CourseMessage.create(:user_id => @msg.course_message_id, :course_id => @msg.course_id, :viewed => false,:course_message_id=>User.current.id,:content=>@msg.content,:course_message_type=>'CourseRequestDealResult',:status=>1)
          @msg.update_attributes(:status => 1, :viewed => 1, :apply_user_id => User.current.id)

=begin
          if integer_ids.include?(9)
            cs = CoursesService.new
            c = Course.find(@msg.course_id)
            #cs.send_wechat_join_class_notice apply_user,c,9,0
          else
            cs = CoursesService.new
            c = Course.find(@msg.course_id)
            #cs.send_wechat_join_class_notice apply_user,c,7,0
          end
=end
        end
        user_role = ids.include?(7) ? '7' : '9'
        Tiding.create(:user_id => @msg.course_message_id, :trigger_user_id => User.current.id, :container_id => @msg.course_id, :container_type => "DealCourse", :belong_container_id => @msg.course_id, :belong_container_type => "Course", :status => 1, :extra => user_role, :tiding_type => "System")
        Tiding.where(:trigger_user_id => @msg.course_message_id, :container_id => @msg.course_id, :container_type => 'JoinCourse', :status => 0).update_all(:status => 1)

=begin
        apply_user = User.find @msg.course_message_id
        notes = User.current.show_real_name.to_s + " 批准#{apply_user.show_real_name}以#{integer_ids.include?(7) ? '教辅' : '教师'}的身份加入班级:<a target='_blank' href='#{members_course_path(c)}'>#{c.name}</a>"
        c.course_teachers.each do |mem|
          user = mem.user
          if user != User.current
            user.journals_for_messages << JournalsForMessage.new(:user_id => User.current.id, :notes => notes, :private => 1, :reply_id => 0)
          end
        end
=end

      when 'N'
        # CourseMessage.create(:user_id => @msg.course_message_id, :course_id => @msg.course_id, :viewed => false,:course_message_id=>User.current.id,:content=>@msg.content,:course_message_type=>'CourseRequestDealResult',:status=>2)
        @msg.update_attributes(:status => 2, :viewed => 1, :apply_user_id => User.current.id)

        user_role = ids.include?(7) ? '7' : '9'
        Tiding.create(:user_id => @msg.course_message_id, :trigger_user_id => User.current.id, :container_id => @msg.course_id, :container_type => "DealCourse", :belong_container_id => @msg.course_id, :belong_container_type => "Course", :status => 2, :extra => user_role, :tiding_type => "System")
        Tiding.where(:trigger_user_id => @msg.course_message_id, :container_id => @msg.course_id, :container_type => 'JoinCourse', :status => 0).update_all(:status => 1)

=begin
        if integer_ids.include?(9)
          cs = CoursesService.new
          c = Course.find(@msg.course_id)
          cs.send_wechat_join_class_notice apply_user,c,9,1
        else
          cs = CoursesService.new
          c = Course.find(@msg.course_id)
          cs.send_wechat_join_class_notice apply_user,c,7,1
        end
=end

    end
    respond_to do |format|
      format.js
      format.html {redirect_to teachers_course_path(@msg.course_id)}
    end
  end

  # 处理资源引用请求
  # status
  def deal_with_apply_resource
    @msg = CourseMessage.find(params[:msg_id])
    ar = ApplyResource.where("id = ?", @msg.course_message_id).first
    unless ar.nil?
      case params[:agree]
        when 'Y'
          ar.update_column('status', 2)
          @msg.update_attributes(:apply_result => 1, :viewed => 1)
          ar.course_messages << CourseMessage.new(:user_id => ar.user_id, :course_id => -1, :viewed => false, :apply_result => 2, :status => 1)
        when 'N'
          ar.update_column('status', 3)
          @msg.update_attributes(:apply_result => 2, :viewed => 1)
          ar.course_messages << CourseMessage.new(:user_id => ar.user_id, :course_id => -1, :viewed => false, :apply_result => 3, :status => 1)
      end
    end
    respond_to do |format|
      format.js
    end
  end

  #处理引用作业的请求
  #status 1 同意 2 拒绝
  def dealwith_apply_homework
    @msg = CourseMessage.find(params[:msg_id])
    ah = ApplyHomework.where("user_id = ? and homework_common_id = ?", @msg.apply_user_id, @msg.course_message_id)
    case params[:agree]
      when 'Y'
        unless ah.empty?
          ah.first.update_column('status', 2)
          CourseMessage.create(:user_id => @msg.apply_user_id, :course_id => @msg.course_id, :viewed => false, :course_message_id => @msg.course_message_id, :content => @msg.content, :course_message_type => 'HomeworkCommon', :status => 6, :apply_result => 1)
          @msg.update_attributes(:apply_result => 1, :viewed => 1)
        end
      when 'N'
        unless ah.empty?
          ah.first.update_column('status', 3)
          CourseMessage.create(:user_id => @msg.apply_user_id, :course_id => @msg.course_id, :viewed => false, :course_message_id => @msg.course_message_id, :content => @msg.content, :course_message_type => 'HomeworkCommon', :status => 6, :apply_result => 2)
          @msg.update_attributes(:apply_result => 2, :viewed => 1)
        end
    end
    respond_to do |format|
      format.js
    end
  end

  # added by bai
  def show_score

  end

  def show_new_score
    render :layout => 'users_base'
  end

  # end

  ##added by fq
  def watch_bids
    # cond = 'bids.reward_type <> 1'
    # @bids = Bid.watched_by(@user).where('reward_type = ?', 1) # added by huang
    # @offset, @limit = api_offset_and_limit({:limit => 10})
    # @bid_count = @bids.count
    # @bid_pages = Paginator.new @bid_count, @limit, params['page']
    # @offset ||= @bid_pages.reverse_offset
    # unless @offset == 0
    #   @bid = @bids.offset(@offset).limit(@limit).all.reverse
    # else
    #   limit = @bid_count % @limit
    #   @bid = @bids.offset(@offset).limit(limit).all.reverse
    # end
    #
    # respond_to do |format|
    #   format.html {
    #     render :layout => 'base_users'
    #   }
    #   format.api
    # end
  end

  #new add by linchun
  def watch_contests
    @bids = Contest.watched_by(@user)
    @offset, @limit = api_offset_and_limit({:limit => 10})
    @contest_count = @contests.count
    @contest_pages = Paginator.new @contest_count, @limit, params['page']
    @offset ||= @contest_pages.reverse_offset
    unless @offset == 0
      @contest = @contests.offset(@offset).limit(@limit).all.reverse
    else
      limit = @bid_count % @limit
      @contest = @contests.offset(@offset).limit(limit).all.reverse
    end

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

  #  added by fq
  def user_activities
    redirect_to user_url(@user, type: params[:type], page: params[:page])
    return
    # useless abort.
    @watcher = User.watched_by_id(@user)
    events = []
    for user in @watcher
      events << Redmine::Activity::Fetcher.new(User.current, :author => @user).events(nil, nil, :limit => 30)
    end


    @events_by_day = events.group_by(&:event_date)

    unless User.current.admin?
      if !@user.active? || (@user != User.current && @memberships.empty? && events.empty?)
        render_404
        return
      end
    end

    respond_to do |format|
      format.html
      format.api
    end
  end

  # end

  # 资源分享请求弹框
  def apply_resource
    @attachment = Attachment.find params[:attachment_id]
    respond_to do |format|
      format.js
    end
  end

  #引用作业请求弹框
  def apply_homework
    if User.current.logged?
      @homework = HomeworkCommon.find params[:homework_id]
      @state = 2
    else
      @state = 1
    end
    respond_to do |format|
      format.js
    end
  end

  # 申请引用资源
  def apply_for_resource
    if User.current.logged?
      @attachment = Attachment.where("id =?", params[:attachment_id].to_i).first
      unless @attachment.nil?
        ar = ApplyResource.where("user_id = ? and attachment_id = ?", User.current.id, params[:attacment_id].to_i)
        if ar.empty?
          ApplyResource.create(:user_id => params[:id].to_i, :attachment_id => params[:attachment_id].to_i, :status => true, :container_id => @attachment.container_id, :container_type => @attachment.container_type, :content => params[:content], :apply_user_id => @attachment.author_id)
          @state = 2
        else
          @state = 3
        end
      end
    else
      @state = 1
    end
    respond_to do |format|
      format.js
    end
  end

  #申请引用非公开作业
  def apply_for_homework
    if User.current.logged?
      homework = HomeworkCommon.find params[:homework_id]
      unless homework.nil?
        ah = ApplyHomework.where("user_id = ? and homework_common_id = ?", User.current.id, params[:homework_id].to_i)
        if ah.empty?
          ApplyHomework.create(:user_id => params[:id].to_i, :homework_common_id => params[:homework_id].to_i, :status => 1)
          # Mailer.run.apply_for_homework_request(homework, User.current)
          CourseMessage.create(:user_id => homework.user_id, :course_id => homework.course.id, :viewed => false, :course_message_id => params[:homework_id].to_i, :course_message_type => 'HomeworkCommon', :status => 5, :apply_user_id => params[:id].to_i, :content => params[:content])
          @state = 2
          @ah = ApplyHomework.where("user_id = ? and homework_common_id = ?", params[:id].to_i, params[:homework_id].to_i).first
          @homework = homework
        else
          @state = 3
        end
      end
    else
      @state = 1
    end
    respond_to do |format|
      format.js
    end
  end

  #用户作业列表
  def user_homeworks
    @order, @b_sort = params[:order] || "created_at", params[:sort] || "desc"
    @user = User.current
    @r_sort = @b_sort == "desc" ? "asc" : "desc"
    if (params[:type].blank? || params[:type] == "1") #我的题库
      # courses = @user.courses.where("is_delete = 1")
      # course_ids = courses.empty? ? "(-1)" : "(" + courses.map{|course| course.id}.join(",") + ")"
      # @homeworks = HomeworkCommon.where("user_id = #{@user.id} and course_id not in #{course_ids}").order("#{@order} #{@b_sort}")
      @homeworks = @user.homework_banks.order("#{@order} #{@b_sort}")
    elsif params[:type] == "2" #公共题库
      # visible_course = Course.where("is_delete = 0")
      # visible_course_ids = visible_course.empty? ? "(-1)" : "(" + visible_course.map{|course| course.id}.join(",") + ")"
      # @homeworks = HomeworkCommon.where("course_id in #{visible_course_ids} and publish_time <= '#{Date.today}'").order("#{@order} #{@b_sort}")
      @homeworks = HomeworkBank.where(:is_public => true).order("#{@order} #{@b_sort}")
    end
    @type = params[:type] ? params[:type] : '1'
    @limit = 10
    @is_remote = true
    @hw_count = @homeworks.count
    @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
    @offset ||= @hw_pages.offset
    @homeworks = paginateHelper @homeworks, 10
    respond_to do |format|
      format.js
      format.html {render :layout => 'static_base'}
    end
  end

  def student_homeworks
    if User.current == @user
      @page = params[:page] ? params[:page].to_i + 1 : 0
      user_course_ids = @user.courses.empty? ? "(-1)" : "(" + @user.courses.visible.map {|course| course.id}.join(",") + ")"

      #判断当前用户在当前课程的身份
      visibleCourse = @user.courses.empty? ? [] : @user.courses.where("is_delete = 0").visible
      homework_ids = []
      visibleCourse.each do |course|
        homeworks = HomeworkCommon.where("course_id = #{course.id} and publish_time <= '#{Time.now}'")
        homework_ids << homeworks.pluck(:id) unless homeworks.empty?
      end
      visible_homework_ids = homework_ids.size == 0 ? "(-1)" : "(" + homework_ids.join(",") + ")"
      @homework_commons = HomeworkCommon.where("id in #{visible_homework_ids}").order("created_at desc").limit(10).offset(@page * 10)
      @is_teacher = User.current.user_extensions && User.current.user_extensions.identity == 0 && User.current.allowed_to?(:add_course, nil, :global => true)
      @is_in_course = params[:is_in_course].to_i || 0
      respond_to do |format|
        format.js
        format.html {render :layout => 'new_base_user'}
      end
    else
      render_403
    end
  end

  def choose_user_course
    #homework = HomeworkCommon.find params[:homework].to_i
    # if homework.user != User.current && homework.course.is_public == 0 && !User.current.allowed_to?(:as_teacher,homework.course)
    #   ah = ApplyHomework.where("user_id = ? and homework_common_id = ?", User.current.id, params[:send_id].to_i)
    #   if ah.empty?
    #     @status = 2
    #   elsif ah.first.status != 2
    #     @status = ah.first.status
    #   end
    # end
    if !params[:search].nil?
      search = "%#{params[:search].to_s.strip.downcase}%"
      @course = @user.courses.where("is_delete = 0 and (#{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p)", :p => search).select {|course| @user.allowed_to?(:as_teacher, course)}
    else
      @course = @user.courses.where("is_delete = 0").select {|course| @user.allowed_to?(:as_teacher, course)}
    end
    @search = params[:search]
    #这里仅仅是传递需要发送的资源id
    @send_id = params[:homework]
    respond_to do |format|
      format.js
    end
  end

  def send_homework_to_course
    homework = HomeworkBank.find params[:send_id].to_i
    course_ids = params[:course_ids]
    course_ids.each do |course_id|
      course = Course.find course_id.to_i
      quote_homework_bank homework, course
    end
    @homework = homework
    respond_to do |format|
      format.js
    end
  end

  #导入作业
  def user_import_homeworks
    @user = User.current
    @select_course = params[:select_course]
    @homework_type = params[:homework_type].to_i
    search = params[:search].to_s.strip.downcase
    if (params[:type].blank? || params[:type] == "1") #我的题库
      @homeworks = @user.homework_banks.where(:homework_type => @homework_type)
    elsif params[:type] == "2" #公共题库
      @homeworks = HomeworkBank.where(:is_public => true, :homework_type => @homework_type)
    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(",") +")"
      @homeworks = @homeworks.where("name like '%#{search}%' or course_list_id in #{course_list_ids}").reorder("created_at desc")
    else
      @homeworks = @homeworks.reorder("created_at desc")
    end
    @limit = 8
    @page = params[:page].nil? ? 1 : params['page'].to_i
    @is_remote = true
    @hw_count = @homeworks.count
    @total_pages = (@hw_count / 8.0).ceil
    @homeworks_pages = Paginator.new @hw_count, @limit, @page
    @homeworks = paginateHelper @homeworks, @limit
    respond_to do |format|
      format.js
      format.json {
        render json: homework_bank_json_data(@homeworks)
      }
    end
  end

  def user_homework_type
    @user = User.current
    if (params[:type].blank? || params[:type] == "1") #我的题库
      @homeworks = @user.homework_banks
    elsif params[:type] == "2" #公共题库
      @homeworks = HomeworkBank.where(:is_public => true)
    end
    @homeworks = @homeworks.reorder("created_at desc")
    @type = params[:type] ? params[:type] : '1'
    @limit = 10
    @is_remote = true
    @hw_count = @homeworks.count
    @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
    @offset ||= @hw_pages.offset
    @homeworks = paginateHelper @homeworks, @limit
    respond_to do |format|
      format.js
    end
  end

  def show_homework_detail
    @homework = HomeworkBank.find params[:homework].to_i
    # if homework.course.is_public == 0 && !User.current.allowed_to?(:as_teacher,homework.course) && User.current != homework.user
    #   ah = ApplyHomework.where("user_id = ? and homework_common_id = ?", User.current.id, params[:homework].to_i)
    #   if ah.empty?
    #     @status = 2
    #     @homework = nil
    #   elsif ah.first.status != 2
    #     @status = ah.first.status
    #     @homework = nil
    #   elsif ah.first.status == 2
    #     @homework = homework
    #   end
    # else
    #   @homework = homework
    # end
    @is_import = params[:is_import]
    respond_to do |format|
      format.js
    end
  end

  #用户主页过滤作业
  def user_search_homeworks
    @order, @b_sort = params[:order] || "created_at", params[:sort] || "desc"
    @r_sort = @b_sort == "desc" ? "asc" : "desc"
    @user = User.current
    search = params[:name].to_s.strip.downcase
    type_ids = (params[:property] == "" || params[:property].nil? || params[:property] == "0") ? "(1, 2, 3)" : "(" + params[:property] + ")"
    if (params[:type].blank? || params[:type] == "1") #我的题库
      #courses = @user.courses.where("is_delete = 1")
      #course_ids = courses.empty? ? "(-1)" : "(" + courses.map{|course| course.id}.join(",") + ")"
      @homeworks = @user.homework_banks.where("name like '%#{search}%' and homework_type in #{type_ids}").order("#{@order} #{@b_sort}")
      # if @order == "course_name"
      #   sql = "SELECT homework_commons.* FROM homework_commons INNER JOIN courses ON homework_commons.course_id = courses.id where homework_commons.course_id not in #{course_ids} and homework_commons.user_id = #{@user.id} and homework_type in #{type_ids} and (homework_commons.name like '%#{search}%') order by CONVERT (courses.name USING gbk) COLLATE gbk_chinese_ci #{@b_sort}"
      #   @homeworks = HomeworkCommon.find_by_sql(sql)
      # elsif @order == "user_name"
      #   @homeworks = HomeworkCommon.where("user_id = #{@user.id} and course_id not in #{course_ids} and (name like '%#{search}%') and homework_type in #{type_ids}").joins(:user).order("CONVERT (lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, CONVERT (firstname USING gbk) COLLATE gbk_chinese_ci #{@b_sort},login #{@b_sort}")
      # else
      #   @homeworks = HomeworkCommon.where("user_id = #{@user.id} and course_id not in #{course_ids} and (name like '%#{search}%') and homework_type in #{type_ids}").order("#{@order} #{@b_sort}")
      # end
    elsif params[:type] == "2" #题库
      #visible_course = Course.where("is_public = 1 && is_delete = 0")
      #visible_course_ids = visible_course.empty? ? "(-1)" : "(" + visible_course.map{|course| course.id}.join(",") + ")"
      all_homeworks = HomeworkBank.where(:is_public => true)
      all_user_ids = all_homeworks.map {|hw| hw.user_id}
      user_str_ids = search_user_by_name all_user_ids, search
      user_ids = user_str_ids.empty? ? "(-1)" : "(" + user_str_ids.join(",") + ")"
      @homeworks = HomeworkBank.where("is_public = 1 and (name like '%#{search}%' or user_id in #{user_ids}) and homework_type in #{type_ids}").order("#{@order} #{@b_sort}")
      # if @order == "course_name"
      #   sql = "SELECT homework_commons.* FROM homework_commons INNER JOIN courses ON homework_commons.course_id = courses.id where homework_type in #{type_ids} and course_id in #{visible_course_ids} and publish_time <= '#{Date.today}' and (homework_commons.name like '%#{search}%' or homework_commons.user_id in #{user_ids}) order by CONVERT (courses.name USING gbk) COLLATE gbk_chinese_ci #{@b_sort}"
      #   @homeworks = HomeworkCommon.find_by_sql(sql)
      # elsif @order == "user_name"
      #   @homeworks = HomeworkCommon.where("course_id in #{visible_course_ids} and publish_time <= '#{Date.today}' and homework_type in #{type_ids} and (name like '%#{search}%' or user_id in #{user_ids})").joins(:user).order("CONVERT (lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, CONVERT (firstname USING gbk) COLLATE gbk_chinese_ci #{@b_sort},login #{@b_sort}")
      # else
      #   @homeworks = HomeworkCommon.where("course_id in #{visible_course_ids} and publish_time <= '#{Date.today}' and homework_type in #{type_ids} and (name like '%#{search}%' or user_id in #{user_ids})").order("#{@order} #{@b_sort}")
      # end
    elsif params[:type] == "3" #申请题库
      apply_homeworks = ApplyHomework.where("user_id = ?", @user.id)
      homework_ids = apply_homeworks.empty? ? "(-1)" : "(" + apply_homeworks.map {|ah| ah.homework_common_id}.join(",") + ")"
      none_visible_course = Course.where("is_delete = 1")
      none_visible_course_ids = none_visible_course.empty? ? "(-1)" : "(" + none_visible_course.map {|course| course.id}.join(",") + ")"
      if @order == "course_name"
        sql = "SELECT homework_commons.* FROM homework_commons INNER JOIN courses ON homework_commons.course_id = courses.id where courses.is_delete = 0 and homework_commons.id in #{homework_ids} and homework_type in #{type_ids} and publish_time <= '#{Time.now}' and (homework_commons.name like '%#{search}%') order by CONVERT (courses.name USING gbk) COLLATE gbk_chinese_ci #{@b_sort}"
        @homeworks = HomeworkCommon.find_by_sql(sql)
      elsif @order == "user_name"
        @homeworks = HomeworkCommon.where("homework_commons.id in #{homework_ids} and course_id not in #{none_visible_course_ids} and (name like '%#{search}%') and homework_type in #{type_ids}").joins(:user).order("CONVERT (lastname USING gbk) COLLATE gbk_chinese_ci #{@b_sort}, CONVERT (firstname USING gbk) COLLATE gbk_chinese_ci #{@b_sort},login #{@b_sort}")
      else
        @homeworks = HomeworkCommon.where("id in #{homework_ids} and (name like '%#{search}%') and course_id not in #{none_visible_course_ids} and homework_type in #{type_ids}").order("#{@order} #{@b_sort}")
      end
    end
=begin
    if params[:property] && params[:property] == "1"
      @homeworks = @homeworks.where("homework_type = 1")
    elsif params[:property] && params[:property] == "2"
      @homeworks = @homeworks.where("homework_type = 2")
    elsif params[:property] && params[:property] == "3"
      @homeworks = @homeworks.where("homework_type = 3")
    end
=end
    @type = params[:type]
    @limit = params[:is_import].to_i == 1 ? 15 : 10
    @is_remote = true
    @hw_count = @homeworks.count
    @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
    @offset ||= @hw_pages.offset
    @homeworks = paginateHelper @homeworks, @limit
    @is_import = params[:is_import]
    @property = params[:property]
    @search = search
    respond_to do |format|
      format.js
    end
  end

  #检查改作业是否可以选用
  def check_homework
    resultObj = {status: 2}
    homework_bank = HomeworkBank.find params[:homework]
    if homework_bank.homework_common_id && HomeworkCommon.find(homework_bank.homework_common_id)
      homework = HomeworkCommon.find(homework_bank.homework_common_id)
      student_ids = homework.course.student.empty? ? [] : homework.course.student.map {|student| student.student_id}.join(',')
      if student_ids.include?(User.current.id.to_s)
        resultObj[:status] = 1
      else
        resultObj[:status] = 0
      end
    else
      resultObj[:status] = 0
    end
    render :json => resultObj
  end

  #导入作业,确定按钮
  def user_select_homework
    if params[:checkMenu]
      homework = HomeworkBank.find_by_id params[:checkMenu]
      @select_course = Course.find params[:select_course]
      if homework && @select_course
        @homework = quote_homework_bank homework, @select_course
      end
    end
    respond_to do |format|
      format.js
    end
  end

  def new_user_commit_homework
    if User.current.logged?
      @user = User.current
      @homework = HomeworkCommon.find(params[:homework_id])
      @is_test = params[:is_test] == 'true'
      @student_work = StudentWork.where(homework_common_id: @homework.id, user_id: User.current.id, is_test: @is_test).first
      if @student_work.nil?
        @student_work = StudentWork.new
      end
      @course = @homework.course
      @left_nav_type = 3
      respond_to do |format|
        format.js
        format.html {render :layout => 'base_courses'}
      end
    else
      render_403
    end
  end

  #修改编程作业
  def edit_user_commit_homework
    if User.current.logged?

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

  def user_commit_homework
    homework = HomeworkCommon.find(params[:homework])
    student_work = StudentWork.where(homework_common_id: homework.id, user_id: User.current.id).first
    if student_work

      # 提交作品时,计算是否迟交
      if homework.end_time < Time.now
        student_work.late_penalty = homework.late_penalty
        student_work.work_status = 2
        # 缺评扣分
        if homework.homework_detail_manual.no_anon_penalty == 0 && homework.homework_detail_manual.comment_status == 3 && homework.anonymous_comment == 0
          work_ids = "(" + homework.student_works.has_committed.map(&:id).join(",") + ")"
          all_dis_eva = StudentWorksEvaluationDistribution.where("student_work_id IN #{work_ids}")
          has_sw_count = all_dis_eva.select("distinct user_id").count
          anon_count = all_dis_eva.count / has_sw_count
          student_work.absence_penalty = homework.homework_detail_manual.absence_penalty * anon_count
        end
      else
        student_work.late_penalty = 0
        student_work.work_status = 1
      end

      student_work.commit_time = Time.now
      student_work.save
      send_message_to_teacher(student_work)
      homework.update_column(:updated_at, Time.now)
      update_course_activity(homework.class, homework.id)
      update_user_activity(homework.class, homework.id)
      update_org_activity(homework.class, homework.id)

      flash[:notice] = l(:notice_successful_create)
      redirect_to student_work_index_url(:homework => params[:homework], :tab => 2)
    else
      render_403
    end
  end

  def user_new_homework
    if User.current.logged?
      if params[:homework_common]
        homework = HomeworkCommon.new
        homework.name = params[:homework_common][:name]
        homework.description = params[:homework_common][:description]
        # homework.end_time = params[:homework_common][:end_time] || Time.now
        # if params[:homework_common][:publish_time] == ""
        #   homework.publish_time = Time.now
        # else
        #   homework.publish_time = params[:homework_common][:publish_time]
        # end
        homework.anonymous_comment = params[:homework_common][:anonymous_comment] ? params[:homework_common][:anonymous_comment].to_i : 1
        homework.homework_type = params[:homework_type].to_i || 1
        homework.late_penalty = 0
        homework.teacher_priority = 1
        homework.user_id = User.current.id
        homework.course_id = params[:course_id]

        homework.save_attachments(params[:attachments])
        render_attachment_warning_if_needed(homework)

        homework_detail_manual = HomeworkDetailManual.new
        if homework.anonymous_comment == 1
          homework_detail_manual.ta_proportion = homework.homework_type == 2 ? 0.4 : 1.0
        else
          homework_detail_manual.ta_proportion = homework.homework_type == 2 ? 0.3 : 0.6
        end
        if params[:homework_common][:end_time] == ""
          homework_detail_manual.comment_status = 0
        else
          homework.end_time = params[:homework_common][:end_time]
          if params[:homework_common][:publish_time] == ""
            homework.publish_time = Time.now
          else
            homework.publish_time = params[:homework_common][:publish_time]
          end

          if homework.publish_time > Time.now
            homework_detail_manual.comment_status = 0
          else
            homework_detail_manual.comment_status = 1

            #更新CourseHomeworkStatistics中每个学生的未交作品数
            homework.course.student.each do |student|
              course_statistics = CourseHomeworkStatistics.find_by_course_id_and_user_id(homework.course_id, student.student_id)
              course_statistics.update_attribute('un_commit_work_num', course_statistics.un_commit_work_num + 1) if course_statistics
            end
          end
        end

        homework_detail_manual.evaluation_start = (homework.end_time + 7 * 24 * 60 * 60).strftime("%Y-%m-%d") if homework.end_time
        homework_detail_manual.evaluation_end = homework_detail_manual.evaluation_start + 7 if homework.end_time
        homework_detail_manual.evaluation_num = params[:evaluation_num] || 3
        homework_detail_manual.absence_penalty = 0
        homework.homework_detail_manual = homework_detail_manual

        #编程作业相关属性
        if homework.homework_type == 2
          homework_detail_programing = HomeworkDetailPrograming.new
          homework.homework_detail_programing = homework_detail_programing
          if homework.anonymous_comment == 1
            homework_detail_programing.ta_proportion = 0.6
          else
            homework_detail_programing.ta_proportion = 0.5
          end
          homework_detail_programing.language = params[:language_type].to_i

          sample_inputs = params[:sample][:input]
          if Array === sample_inputs
            sample_inputs.each_with_index do |val, i|
              homework.homework_samples << HomeworkSample.new(
                  input: val,
                  output: params[:sample][:output][i]
              )
            end
          end

          inputs = params[:program][:input]
          if Array === inputs
            inputs.each_with_index do |val, i|
              homework.homework_tests << HomeworkTest.new(
                  input: val,
                  output: params[:program][:output][i]
              )
            end
          end
        end

        #分组作业
        if homework.homework_type == 3
          homework_detail_group = HomeworkDetailGroup.new
          homework.homework_detail_group = homework_detail_group
          homework_detail_group.min_num = params[:min_num].to_i
          homework_detail_group.max_num = params[:max_num].to_i
          homework_detail_group.base_on_project = params[:base_on_project].to_i
        end

        if homework.save
          homework_detail_manual.save if homework_detail_manual
          homework_detail_programing.save if homework_detail_programing
          homework_detail_group.save if homework_detail_group

          if homework.homework_type != 3 && homework_detail_manual.comment_status == 1
            create_works_list homework
          end

          if params[:quotes] && !params[:quotes].blank?
            quotes_homework = HomeworkBank.find params[:quotes].to_i
            quotes_homework.update_column(:quotes, quotes_homework.quotes + 1)
            homework.update_attributes(:homework_bank_id => quotes_homework.id)
          end

          if params[:add_to_bank]
            homework_bank = add_to_homework_bank_f homework
            homework_bank.save
            homework.update_attributes(:homework_bank_id => homework_bank.id)
          end
          redirect_to homework_common_index_path(:course => homework.course_id)
        end
      end
    else
      render_403
    end
  end

  #用户从资源库导入资源到作业
  def user_import_resource
    @user = User.current
    user_course_ids = @user.courses.map {|c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
    @attachments = Attachment.where("(author_id = #{@user.id} and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) " +
                                        "or (container_type = 'Course'  and container_id in (#{user_course_ids.empty? ? '0' : user_course_ids.join(',')}))").order("created_on desc")
    @type = params[:type]
    @homework_id = params[:homework_id]
    @limit = 7
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    @seleted_resources = session[:seleted_resource_ids].nil? ? [] : session[:seleted_resource_ids]
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 7
    respond_to do |format|
      format.js
    end
  end

  #引入资源列表根据类型过滤
  def user_resource_type
    user_course_ids = User.current.courses.map {|c| c.is_delete == 0 && c.id}
    user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id}
    # user_org_ids = User.current.organizations.map {|o| o.id}
    if (params[:type].blank? || params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      if params[:status] == "2"
        @attachments = get_course_resources(User.current.id, user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources(User.current.id, user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources(User.current.id, @order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources(User.current.id, @order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_my_resources(User.current.id, user_course_ids, user_project_ids, @order, @score)
      end
    elsif params[:type] == "6" # 公共资源
      if params[:status] == "2"
        @attachments = get_course_resources_public(user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources_public(user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_public(@order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_public(@order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
      end
    end
    @type = params[:type]
    @limit = 7
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    @seleted_resources = session[:seleted_resource_ids].nil? ? [] : session[:seleted_resource_ids]
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 7
    respond_to do |format|
      format.js
    end
  end


  #引入资源列表根据关键词过滤
  def user_ref_resource_search
    @resource_id = params[:mul_id]
    @resource_type = params[:mul_type]
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    @user = User.current
    @switch_search = params[:search].nil? ? " " : params[:search]
    search = "%#{@switch_search.strip.downcase}%"
    # 别人的资源库是没有权限去看的
    if (params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      user_course_ids = User.current.courses.map {|c| c.is_delete == 0 && c.id}
      user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id}
      # user_org_ids = User.current.organizations.map {|o| o.id}
      @attachments = get_my_resources_search(User.current.id, user_course_ids, user_project_ids, @order, @score, search)
    elsif (params[:type].blank? || params[:type] == "6") # 公共资源
      # 公共资源库:所有公开资源或者我上传的私有资源
      @attachments = get_public_resources_search(user_course_ids, user_project_ids, @order, @score, search)
    end
    @type = params[:type]
    @limit = 7
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    @seleted_resources = session[:seleted_resource_ids].nil? ? [] : session[:seleted_resource_ids]
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 7
    respond_to do |format|
      format.js
    end
  end

  #将资源批量引入
  def import_resources_to_homework
    @attachments = []
    unless session[:seleted_resource_ids].nil? || session[:seleted_resource_ids].blank?
      session[:seleted_resource_ids].each do |id|
        atta = Attachment.find(id)
        att_copy = atta.copy
        att_copy.container_id = nil
        att_copy.container_type = nil
        att_copy.author_id = User.current.id
        att_copy.copy_from = atta.id
        att_copy.save
        @attachments << att_copy
      end
    end
    session[:seleted_resource_ids] = [] #保存后清空
    respond_to do |format|
      format.js
    end
  end

  # ajax 用session保存选择的资源id
  def store_selected_resource
    session[:seleted_resource_ids] = [] if session[:seleted_resource_ids].nil?
    if params[:save] == 'y'
      session[:seleted_resource_ids] << params[:res_id]
    else
      session[:seleted_resource_ids].delete(params[:res_id])
    end
    render :nothing => true
  end


  include CoursesHelper

  def user_courses

    unless User.current.admin?
      if !@user.active?
        render_404
        return
      end
    end
    courses = @user.courses.visible.select("courses.*,(SELECT MAX(created_at)  FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc")
    if (params[:status] == '1')
      courses = courses.where("endup_time >= ? or endup_time is null or endup_time=''", Time.now)
    elsif (params[:status] == '2')
      courses = courses.where("endup_time < ?", Time.now)
    end
    @list = paginateHelper courses, 10
    @params = params[:status]
    render :layout => 'base_users_new'
  end

  # modified by fq
  def user_newfeedback
    unless User.current.logged?
      redirect_to signin_url
      return
    end
    update_onclick_time
    # 自己访问自己的页面才更新消息状态
    UserFeedbackMessage.where("user_id =? and viewed =? and journals_for_message_type =? ", User.current.id, 0, "JournalsForMessage").update_all(:viewed => true)
    # end
    @page = params[:page] ? params[:page].to_i + 1 : 0
    if params[:type].present?
      case params[:type]
        when "public"
          jours = JournalsForMessage.where('m_parent_id IS NULL and (user_id = ? or jour_id = ?) and private = 0 and jour_type = "Principal"', @user.id, @user.id).order('updated_on DESC')
        when "private"
          jours = JournalsForMessage.where('m_parent_id IS NULL and (user_id = ? or jour_id = ?) and private = 1 and jour_type = "Principal"', @user.id, @user.id).order('updated_on DESC')
        else
          jours = JournalsForMessage.where('m_parent_id IS NULL and (user_id = ? or jour_id = ?) and jour_type = "Principal"', @user.id, @user.id).order('updated_on DESC')
      end
    else
      jours = JournalsForMessage.where('m_parent_id IS NULL and (user_id = ? or jour_id = ?) and jour_type = "Principal"', @user.id, @user.id).order('updated_on DESC')
    end
    @jour_count = jours.count
    @jour = jours.limit(10).offset(@page * 10)
    @type = params[:type]
    @state = false
    render :layout => 'edu_new_base_user'
  end

  #给某人留言
  def feedBackTo


  end

  def user_comments

  end

  #end
  def index

    @status = params[:status] || 1
    sort_init 'login', 'asc'
    sort_update %w(login firstname lastname mail admin created_on last_login_on)

    case params[:format]
      when 'xml', 'json'
        @offset, @limit = api_offset_and_limit({:limit => 15})
      else
        @limit = 15
    end

    # retrieve all users
    # 先内连一下statuses 保证排序之后数量一致
    scope = User.visible.
        joins("INNER JOIN user_statuses ON users.id = user_statuses.user_id")

    # unknow
    scope = scope.in_group(params[:group_id]) if params[:group_id].present?

    # pagination
    @user_count = scope.count
    @user_pages = Paginator.new @user_count, @limit, params['page']

    # users classify
    case params[:user_sort_type]
      when '0'
        # 创建时间排序
        @s_type = 0
        @users = scope.reorder('users.created_on DESC')
      when '1'
        # 活跃度排序, 就是所谓的得分情况
        @s_type = 1
        @users = scope.
            joins("LEFT JOIN option_numbers ON users.id = option_numbers.user_id and option_numbers.score_type = 1").
            reorder('option_numbers.total_score DESC')
      when '2'
        # 粉丝数排序
        @s_type = 2
        @users = scope.
            #joins("INNER JOIN user_statuses ON users.id = user_statuses.user_id").
            reorder('user_statuses.watchers_count DESC')

      else
        # 默认活跃度排序
        @s_type = 1
        @users = scope.
            joins("LEFT JOIN option_numbers ON users.id = option_numbers.user_id and option_numbers.score_type = 1").
            reorder('option_numbers.total_score DESC')
    end

    # limit and offset
    @users = @users.limit(@user_pages.per_page).offset(@user_pages.offset)

    @user_base_tag = params[:id] ? 'base_users' : 'users_base'
    respond_to do |format|
      format.html {
        @groups = Group.all.sort
        User.current.admin? ? (render :layout => @user_base_tag) : (render_404)
      }
      format.api
    end
  end

  def search
    sort_init 'login', 'asc'
    sort_update %w(login firstname lastname mail admin created_on last_login_on)
    (redirect_to user_url, :notice => l(:label_sumbit_empty); return) if params[:name].blank?
    case params[:format]
      when 'xml', 'json'
        @offset, @limit = api_offset_and_limit({:limit => 15})
      else
        @limit = 15 #per_page_option
    end
    #
    #@status = params[:status] || 1
    #has = {
    #  "show_changesets" => true
    #}
    #   scope = User.logged.status(@status)
    #   @search_by = params[:search_by] ? params[:search_by][:id] : 0
    #   scope = scope.like(params[:name],@search_by) if params[:name].present?
    @search_by = params[:search_by] ? params[:search_by] : 0

    us = UsersService.new
    scope = us.search_user params
    @user_count = scope.count
    @user_pages = Paginator.new @user_count, @limit, params['page']
    @user_base_tag = params[:id] ? 'base_users' : 'users_base'
    @offset ||= @user_pages.reverse_offset
    unless @offset == 0
      @users = scope.offset(@offset).limit(@limit).all.reverse
    else
      limit = @user_count % @limit
      if limit == 0
        limit = @limit
      end
      @users = scope.offset(@offset).limit(limit).all.reverse
    end
    @name = params[:name]
    @type = 'users'
    respond_to do |format|
      format.html {
        @groups = Group.all.sort
        render :layout => @user_base_tag
      }
      format.api
    end
  end

  #显示更多用户课程
  def user_courses4show
    @page = params[:page].to_i + 1
    @courses = @user.favorite_courses.visible.where("is_delete =?", 0).select("courses.*,(SELECT MAX(updated_at)  FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").limit(10).offset(@page * 10)
    @all_count = @user.favorite_courses.visible.where("is_delete =?", 0).count
  end

  #显示更多用户项目
  def user_projects4show
    @page = params[:page].to_i + 1
    @projects = @user.favorite_projects.visible.select("projects.*,(SELECT MAX(updated_at)  FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc").limit(10).offset(@page * 10)
    @all_count = @user.favorite_projects.visible.count
  end

  # 竞赛社区左侧列表展开
  def user_contests4show
    @page = params[:page].to_i + 1
    @courses = @user.favorite_contests.visible.where("is_delete =?", 0).select("contests.*,(SELECT MAX(updated_at)  FROM `contest_activities` WHERE contest_activities.contest_id = contests.id) AS a").order("a desc").limit(10).offset(@page * 10)
    @all_count = @user.favorite_contests.visible.where("is_delete =?", 0).count
  end

  def user_course_activities
    lastid = nil
    if params[:lastid] != nil && !params[:lastid].empty?
      lastid = params[:lastid];
    end

    user_ids = []
    if @user == User.current
      watcher = User.watched_by(@user)
      watcher.push(User.current)
      user_ids = watcher.map {|x| x.id}
    else
      user_ids << @user.id
    end

    query = Activity.joins("join courses c on c.id=#{Activity.table_name}.activity_container_id and #{Activity.table_name}.activity_container_type='Course'")
    query = query.where("#{Activity.table_name}.user_id in (?)", user_ids)
    if User.current != @user #看别人
      if @user.user_extensions != nil && @user.user_extensions.identity == 0 #看老师
        query = query.joins("join members m on c.id=m.course_id and m.user_id = #{@user.id}")
        query = query.joins("join member_roles r on m.id = r.member_id")
        query = query.where("r.role_id in(3,7,9)")
      end
      query = query.where("c.is_public=1")
    end
    if (lastid != nil)
      query = query.where("#{Activity.table_name}.id < ?", lastid)
    end
    query = query.order("#{Activity.table_name}.id desc")
    @list = query_activities(query)

    render :layout => nil
  end

  def user_project_activities
    lastid = nil
    if params[:lastid] != nil && !params[:lastid].empty?
      lastid = params[:lastid];
    end

    user_ids = []
    if @user == User.current
      watcher = User.watched_by(@user)
      watcher.push(User.current)
      user_ids = watcher.map {|x| x.id}
    else
      user_ids << @user.id
    end

    query = Activity.joins("join projects c on c.id=#{Activity.table_name}.activity_container_id and #{Activity.table_name}.activity_container_type='Project'")
    query = query.where(user_id: user_ids)
    if User.current != @user #看别人
      query = query.where("c.is_public=1")
    end
    if (lastid != nil)
      query = query.where("#{Activity.table_name}.id < ?", lastid)
    end
    query = query.order("#{Activity.table_name}.id desc")
    @list = query_activities(query)

    render :action => 'user_course_activities', :layout => nil
  end

  #首页-》我的作业
  def my_homeworks
    tea_courses = @user.courses.visible.not_deleted.select {|course| @user.has_teacher_role(course)}
    tea_course_ids = tea_courses.empty? ? "(-1)" : "(" + tea_courses.map {|course| course.id}.join(',') + ")"
    @manage_homeworks = HomeworkCommon.where("course_id in #{tea_course_ids}").order("created_at desc").limit(5)
    stu_courses = @user.courses.visible.not_deleted.select {|course| @user.has_student_role(course)}
    stu_course_ids = stu_courses.empty? ? "(-1)" : "(" + stu_courses.map {|course| course.id}.join(',') + ")"
    @receive_homeworks = HomeworkCommon.where("course_id in #{stu_course_ids} and publish_time <= '#{Time.now}'").order("created_at desc").limit(5)
    if (@manage_homeworks.empty? && @receive_homeworks.empty?) || (@receive_homeworks.empty?) || (!@manage_homeworks.empty? && !@receive_homeworks.empty? && @manage_homeworks.first.created_at > @receive_homeworks.first.created_at)
      @manage_pre = true
    else
      @manage_pre = false
    end
    respond_to do |format|
      format.js
      format.html {render :layout => 'static_base'}
    end
  end

  # 用户发布的作业
  def user_manage_homeworks
    @manage_homeworks = "我发布的作业"
    @order, @b_sort, @type = params[:order] || "created_at", params[:sort] || "desc", 1
    @r_sort = @b_sort == "desc" ? "asc" : "desc"
    @type = @type.to_i
    tea_courses = @user.courses.visible.not_deleted.select {|course| @user.has_teacher_role(course)}
    tea_course_ids = tea_courses.empty? ? "(-1)" : "(" + tea_courses.map {|course| course.id}.join(',') + ")"
    @homeworks = HomeworkCommon.where("course_id in #{tea_course_ids}").order("#{@order} #{@b_sort}")
    if params[:property]
      all_homework_ids = @homeworks.empty? ? "(-1)" : "(" + @homeworks.map {|h| h.id}.join(",") + ")"
      if params[:property] == "1"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 1")
      elsif params[:property] == "2"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 2")
      elsif params[:property] == "3"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 3")
      end
    end
    @limit = 10
    @is_remote = true
    @hw_count = @homeworks.count
    @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
    @offset ||= @hw_pages.offset
    @homeworks = paginateHelper @homeworks, @limit
    @search = ""
    @property = params[:property]
    respond_to do |format|
      format.js
      format.html {render :layout => 'static_base'}
    end
  end

  # 用户收到的作业
  def user_receive_homeworks
    @receive_homeworks = "我收到的作业"
    @order, @b_sort, @type = params[:order] || "created_at", params[:sort] || "desc", 2
    @r_sort = @b_sort == "desc" ? "asc" : "desc"
    @type = @type.to_i
    stu_courses = @user.courses.visible.not_deleted.select {|course| @user.has_student_role(course)}
    stu_course_ids = stu_courses.empty? ? "(-1)" : "(" + stu_courses.map {|course| course.id}.join(',') + ")"
    @homeworks = HomeworkCommon.where("course_id in #{stu_course_ids} and publish_time <= '#{Time.now}'").order("#{@order} #{@b_sort}")
    if params[:property]
      all_homework_ids = @homeworks.empty? ? "(-1)" : "(" + @homeworks.map {|h| h.id}.join(",") + ")"
      if params[:property] == "1"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 1")
      elsif params[:property] == "2"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 2")
      elsif params[:property] == "3"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 3")
      end
    end
    @limit = 10
    @is_remote = true
    @hw_count = @homeworks.count
    @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
    @offset ||= @hw_pages.offset
    @homeworks = paginateHelper @homeworks, @limit
    @search = ""
    @property = params[:property]
    respond_to do |format|
      format.js
      format.html {render :layout => 'static_base'}
    end
  end

  #我管理/收到的作业
  def manage_or_receive_homeworks
    @order, @b_sort, @type = params[:order] || "created_at", params[:sort] || "desc", params[:type] || 1
    @r_sort = @b_sort == "desc" ? "asc" : "desc"
    @type = @type.to_i
    if @type == 1
      tea_courses = @user.courses.visible.not_deleted.select {|course| @user.has_teacher_role(course)}
      tea_course_ids = tea_courses.empty? ? "(-1)" : "(" + tea_courses.map {|course| course.id}.join(',') + ")"
      @homeworks = HomeworkCommon.where("course_id in #{tea_course_ids}").order("#{@order} #{@b_sort}")
    else
      stu_courses = @user.courses.visible.not_deleted.select {|course| @user.has_student_role(course)}
      stu_course_ids = stu_courses.empty? ? "(-1)" : "(" + stu_courses.map {|course| course.id}.join(',') + ")"
      @homeworks = HomeworkCommon.where("course_id in #{stu_course_ids} and publish_time <= '#{Time.now}'").order("#{@order} #{@b_sort}")
    end
    if params[:property]
      all_homework_ids = @homeworks.empty? ? "(-1)" : "(" + @homeworks.map {|h| h.id}.join(",") + ")"
      if params[:property] == "1"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 1 order by created_at desc")
      elsif params[:property] == "2"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 2 order by created_at desc")
      elsif params[:property] == "3"
        @homeworks = HomeworkCommon.find_by_sql("select * from homework_commons where id in #{all_homework_ids} and homework_type = 3 order by created_at desc")
      end
    end
    @limit = 10
    @is_remote = true
    @hw_count = @homeworks.count
    @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
    @offset ||= @hw_pages.offset
    @homeworks = paginateHelper @homeworks, @limit
    @search = ""
    @property = params[:property]
    respond_to do |format|
      format.js
      format.html {render :layout => 'static_base'}
    end
  end

  #搜索作业
  def search_m_r_homeworks
    @order, @b_sort, @type = params[:order] || "created_at", params[:sort] || "desc", params[:type].to_i || 1
    @r_sort = @b_sort == "desc" ? "asc" : "desc"
    search = params[:name].to_s.strip.downcase
    type_ids = (params[:property] == "" || params[:property].nil? || params[:property] == "0") ? "(1, 2, 3)" : "(" + params[:property] + ")"
    if @type == 1
      tea_courses = @user.courses.visible.not_deleted.select {|course| @user.has_teacher_role(course)}
      tea_course_ids = tea_courses.empty? ? "(-1)" : "(" + tea_courses.map {|course| course.id}.join(',') + ")"
      #user_ids = hw_publisher_user_ids search, tea_course_ids
      @homeworks = HomeworkCommon.where("course_id in #{tea_course_ids} and homework_type in #{type_ids} and name like '%#{search}%'").order("#{@order} #{@b_sort}")
    else
      stu_courses = @user.courses.visible.not_deleted.select {|course| @user.has_student_role(course)}
      stu_course_ids = stu_courses.empty? ? "(-1)" : "(" + stu_courses.map {|course| course.id}.join(',') + ")"
      #user_ids = hw_publisher_user_ids search, stu_course_ids
      @homeworks = HomeworkCommon.where("course_id in #{stu_course_ids} and homework_type in #{type_ids} and publish_time <= '#{Time.now}' and name like '%#{search}%'")
      if @order == "status"
        @homeworks.each do |homework|
          work = cur_user_works_for_homework homework
          if work.blank?
            homework[:infocount] = 0
          else
            homework[:infocount] = 1
          end
        end
        @b_sort == "asc" ? (@homeworks = @homeworks.sort {|x, y| x[:infocount] <=> y[:infocount]}) : (@homeworks = @homeworks.sort {|x, y| y[:infocount] <=> x[:infocount]})
        @homeworks = sortby_time_countcommon_nosticky @homeworks, "created_at"
      else
        @homeworks = @homeworks.order("#{@order} #{@b_sort}")
      end
    end
    @limit = 10
    @is_remote = true
    @hw_count = @homeworks.count
    @hw_pages = Paginator.new @hw_count, @limit, params['page'] || 1
    @offset ||= @hw_pages.offset
    @homeworks = paginateHelper @homeworks, @limit
    @search = search
    @property = params[:property]
    respond_to do |format|
      format.js
    end
  end

  def user_feedback4show
    query = @user.journals_for_messages
    if params[:lastid] != nil && !params[:lastid].empty?
      query = query.where("#{JournalsForMessage.table_name}.id < ?", params[:lastid])
    end
    logger.info('xxoo')
    @list = query.order("#{JournalsForMessage.table_name}.id desc").limit(3).all
    logger.info('aavv')
    render :layout => nil, :locals => {:feed_list => @list}
  end

  def show
    # 弹框提示试用一天
    if @user.certification == 3
      @user.update_column('certification', 0)
      @noticed = true
      notice = SystemUpdateNotice.last
      if notice.present? && notice.end_time > Time.now && notice.start_time >= Time.now - 21600 && User.current.user_system_notices.where(:notice_type => notice.notice_type).count == 0
        @noticed_update = true
      end
    end
    @show_all = @user == User.current || User.current.admin?
    order = params[:order] || "desc"
    @new_order = order == "desc" ? "asc" : "desc"

    # 学习-我的实训
    # l_shixun:学习-实训  l_course:学习-课堂  l_path:学习-实训路径  l_project:学习-项目
    # p_shixun:管理-实训  p_path:管理-实训路径  p_course:管理-课堂  p_project:管理-项目
    # 教师身份的“我管理”在前,其他身份“学习”在前
    # if @user.user_extensions.try(:identity) == 0
    #   @type = params[:type] || "p_course"
    # else
    #   @type = params[:type] || "l_course"
    # end

    @type = params[:type] || "a_course"

    if @type == "a_shixun" || @type == "l_shixun" || @type == "p_shixun"
      @sort = params[:sort] || "time"
      if @sort == "time"
        sort_str = @type == "a_shixun" ? "s.created_at" : (@type == "l_shixun" ? "ms.updated_at" : "s.updated_at")
      else
        sort_str = "sstr.name"
      end
    end

    # 对应类型的三级过滤
    case @type
      when "a_course", "l_course", "p_course"
        if @user == User.current
          @p = params[:p] || "0"
          status = @p == "a" ? "(0,1)" : "(" + @p + ")"
        else
          status = "(0,1)"
        end
      when "l_shixun"
        if @user == User.current
          @p = params[:p] || "0"
          status = @p == "a" ? [0,1] : [@p]
        else
          status = [0,1]
        end
      when "a_project", "l_project", "p_project"
        @p = params[:p] || "a"
        status = @p == "a" ? "(0,1)" : "(" + @p + ")"
      when "a_bank", "m_bank", "p_bank"
        @sort = params[:sort] || "updated_at"
        @p = params[:p] || "Common"
    end

    case @type
      when "a_course"
        student_course_ids = Course.find_by_sql("SELECT c.id FROM courses c, students_for_courses sfc WHERE sfc.course_id = c.id AND sfc.student_id=#{@user.id} AND c.is_delete = 0 AND c.is_end in #{status}")
        manage_course_ids = Course.find_by_sql("SELECT c.id FROM courses c, members m, member_roles mr WHERE m.course_id = c.id AND m.id=mr.member_id AND mr.role_id in (3,7,9) AND m.user_id=#{@user.id} AND c.is_delete = 0 AND c.is_end in #{status}")
        course_ids = student_course_ids.map(&:id) + manage_course_ids.map(&:id)
        @objects = Course.where(:id => course_ids.uniq).includes(:attachments, :teacher => [:user_extensions => [:school]]).order("updated_at #{order}")
      when "l_course"
        student_course_ids = Course.find_by_sql("SELECT c.id FROM courses c, students_for_courses sfc WHERE sfc.course_id = c.id AND sfc.student_id=#{@user.id} AND c.is_delete = 0 AND c.is_end in #{status}")
        @objects = Course.where(:id => student_course_ids.map(&:id)).includes(:attachments, :teacher => [:user_extensions => [:school]]).order("updated_at #{order}")
      when "p_course"
        course_ids = Course.find_by_sql("SELECT c.id FROM courses c, members m, member_roles mr WHERE m.course_id = c.id AND m.id=mr.member_id AND mr.role_id in (3,7,9) AND m.user_id=#{@user.id} AND c.is_delete = 0 AND c.is_end in #{status}")
        @objects = Course.where(:id => course_ids.map(&:id)).includes(:attachments, :teacher => [:user_extensions => [:school]]).order("id = 1309 desc, updated_at #{order}")
      when "a_shixun"
        shixun_ids = @user.shixun_members.map(&:shixun_id) + @user.myshixuns.map(&:shixun_id)
        shixun_ids = shixun_ids.size > 0 ? ("(" + shixun_ids.uniq.join(",") + ")") : "(-1)"
        @objects = @show_all ?
                       Shixun.find_by_sql("select s.id,s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                           from shixuns s LEFT JOIN (SELECT str.shixun_id, tr.name FROM shixun_tag_repertoires str LEFT JOIN tag_repertoires tr ON str.tag_repertoire_id = tr.id
                                           ) sstr ON s.id = sstr.shixun_id
                                           where s.status != -1 and s.id in #{shixun_ids} order by #{sort_str} #{order}") :
                       Shixun.find_by_sql("select s.id,s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                           from shixuns s LEFT JOIN (SELECT str.shixun_id, tr.name FROM shixun_tag_repertoires str LEFT JOIN tag_repertoires tr ON str.tag_repertoire_id = tr.id
                                           ) sstr ON s.id = sstr.shixun_id
                                           where s.status in (2, 3) and s.hidden =0 and s.id in #{shixun_ids}
                                           order by #{sort_str} #{order}")
      when "l_shixun"
        if @sort == "tag"
          shixun_ids = @user.myshixuns.where(:status => status).map(&:shixun_id)
          shixun_ids = shixun_ids.size > 0 ? ("(" + shixun_ids.join(",") + ")") : "(-1)"
          @objects = @show_all ?
                         Shixun.find_by_sql("select s.id,s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                             from shixuns s LEFT JOIN (SELECT str.shixun_id, tr.name FROM shixun_tag_repertoires str LEFT JOIN tag_repertoires tr ON str.tag_repertoire_id = tr.id
                                             ) sstr ON s.id = sstr.shixun_id
                                             where s.status != -1 and s.id in #{shixun_ids} order by #{sort_str} #{order}") :
                         Shixun.find_by_sql("select s.id,s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                             from shixuns s LEFT JOIN (SELECT str.shixun_id, tr.name FROM shixun_tag_repertoires str LEFT JOIN tag_repertoires tr ON str.tag_repertoire_id = tr.id
                                             ) sstr ON s.id = sstr.shixun_id
                                             where s.status in (2, 3) and s.hidden =0 and s.id in #{shixun_ids}
                                             order by #{sort_str} #{order}")
        else
          @objects = @show_all ?
                         Shixun.find_by_sql("select s.id,s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                           from shixuns s, myshixuns ms
                                           where ms.user_id = #{@user.id} AND ms.status in (#{status.join(",")}) and s.id = ms.shixun_id
                                           order by ms.updated_at #{order}") :
                         Shixun.find_by_sql("select s.id,s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                           from shixuns s, myshixuns ms
                                           where ms.user_id = #{@user.id} and s.status in (2, 3) and s.hidden =0 and s.id = ms.shixun_id
                                           order by ms.updated_at #{order}")
        end
      when "p_shixun"
        shixun_ids = @user.shixun_members.map(&:shixun_id)
        shixun_ids = shixun_ids.size > 0 ? ("(" + shixun_ids.join(",") + ")") : "(-1)"
        @p = params[:p] || "a"
        status = @p == "a" ? "(0,1,2,3)" : "(" + @p + ")"
        @objects = @show_all ?
                       Shixun.find_by_sql("select distinct(s.id),s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                           from shixuns s LEFT JOIN (SELECT str.shixun_id, tr.name FROM shixun_tag_repertoires str LEFT JOIN tag_repertoires tr ON str.tag_repertoire_id = tr.id
                                           ) sstr ON s.id = sstr.shixun_id
                                           where s.status in #{status} and s.id in #{shixun_ids}
                                           order by #{sort_str} #{order}") :
                       Shixun.find_by_sql("select distinct(s.id),s.name,s.user_id,s.challenges_count,s.status,s.identifier
                                           from shixuns s LEFT JOIN (SELECT str.shixun_id, tr.name FROM shixun_tag_repertoires str LEFT JOIN tag_repertoires tr ON str.tag_repertoire_id = tr.id
                                           ) sstr ON s.id = sstr.shixun_id
                                           where s.id in #{shixun_ids} and s.hidden =0 and s.status in (2, 3)
                                           order by #{sort_str} #{order}")
      when "a_path"
        subject_ids = StageShixun.where(:shixun_id => @user.myshixuns.map(&:shixun_id)).map(&:subject_id) + @user.subject_members.map(&:subject_id)
        @objects = @show_all ?
                       Subject.where(:id => subject_ids.uniq).order("updated_at #{order}") :
                       Subject.where(:id => subject_ids.uniq, :status => 2, :hidden => false).order("updated_at #{order}")
      when "l_path"
        @p = @user == User.current ? (params[:p] || "0") : "a"
        subject_ids = StageShixun.where(:shixun_id => @user.myshixuns.map(&:shixun_id)).map(&:subject_id)
        @objects = @show_all ?
                       Subject.where(:id => subject_ids.uniq).order("updated_at #{order}") :
                       Subject.where(:id => subject_ids.uniq, :status => 2, :hidden => false).order("updated_at #{order}")
        if @p != "a"
          complete_objects = @objects.includes(:stage_shixuns).select {|subject| subject.stage_shixuns.count == @user.myshixuns.where(:shixun_id => subject.stage_shixuns.map(&:shixun_id), :status => 1).count}
          if @p == "0"
            no_ids = complete_objects.blank? ? "(-1)" : "(" + complete_objects.map(&:id).join(",") + ")"
            @objects = @objects.where("id not in #{no_ids}").order("updated_at #{order}")
          elsif @p == "1"
            @objects = complete_objects
          end
        end
      when "p_path"
        @p = params[:p] || "a"
        status = @p == "a" ? "(0,1,2)" : "(" + @p + ")"
        @objects = @show_all ?
                       Subject.find_by_sql("select distinct(s.id), s.name, s.user_id, s.visits, s.status, s.updated_at from subjects s,
                                            subject_members sm where s.id = sm.subject_id and sm.user_id = #{@user.id} and s.status in
                                            #{status} order by updated_at #{order}") :
                       Subject.find_by_sql("select distinct(s.id), s.name, s.user_id, s.visits, s.status, s.updated_at from subjects s,
                                            subject_members sm where s.id = sm.subject_id and sm.user_id = #{@user.id} and s.status = 2
                                            order by updated_at #{order}")
      when "a_project"
        project_ids = Project.find_by_sql("SELECT p.id FROM projects p, members m, member_roles mr WHERE m.project_id = p.id AND m.id=mr.member_id AND mr.role_id in (3,4,5) AND m.user_id=#{@user.id} AND p.status != 9 AND p.is_public in #{status}")
        @objects = Project.where(:id => project_ids.map(&:id)).includes(:members, :issues, :owner => [:user_extensions => [:school]]).order("updated_on #{order}")
      when "l_project"
        project_ids = Project.find_by_sql("SELECT p.id FROM projects p, members m, member_roles mr WHERE m.project_id = p.id AND m.id=mr.member_id AND mr.role_id in (4,5) AND m.user_id=#{@user.id} AND p.status != 9 AND p.is_public in #{status}")
        @objects = Project.where(:id => project_ids.map(&:id)).includes(:members, :issues, :owner => [:user_extensions => [:school]]).order("updated_on #{order}")
      when "p_project"
        project_ids = Project.find_by_sql("SELECT p.id FROM projects p, members m, member_roles mr WHERE m.project_id = p.id AND m.id=mr.member_id AND mr.role_id = 3 AND m.user_id=#{@user.id} AND p.status != 9 AND p.is_public in #{status}")
        @objects = Project.where(:id => project_ids.map(&:id)).includes(:members, :issues, :owner => [:user_extensions => [:school]]).order("updated_on #{order}")
      when "m_bank"
        if @sort == "username"
          @objects = QuestionBank.find_by_sql("select qb.* from question_banks qb, users u where u.id = qb.user_id and qb.user_id = #{@user.id} and qb.container_type = '#{@p}' and u.status = 1 order by CONVERT (lastname USING gbk) COLLATE gbk_chinese_ci #{order}, CONVERT (firstname USING gbk) COLLATE gbk_chinese_ci #{order}")
        elsif @sort == "name"
          @objects = @user.question_banks.where(:container_type => @p).includes(:user).order("CONVERT(name USING gbk) COLLATE gbk_chinese_ci #{order}")
        else
          @objects = @user.question_banks.where(:container_type => @p).joins("join users on question_banks.user_id = users.id").order("#{@sort} #{order}")
        end
        @course_list = CourseList.where(:id => @objects.map(&:course_list_id))
        if params[:tag]
          @tag = params[:tag]
          @objects = @objects.where(:course_list_id => params[:tag]).order("#{@sort} #{order}")
        end
      when "p_bank"
        if @sort == "username"
          @objects = QuestionBank.find_by_sql("select qb.* from question_banks qb, users u where u.id = qb.user_id and qb.is_public = 1 and qb.container_type = '#{@p}' and u.status = 1 order by CONVERT (lastname USING gbk) COLLATE gbk_chinese_ci #{order}, CONVERT (firstname USING gbk) COLLATE gbk_chinese_ci #{order}")
        elsif @sort == "name"
          @objects = QuestionBank.where(:container_type => @p, :is_public => 1).includes(:user).order("CONVERT(name USING gbk) COLLATE gbk_chinese_ci #{order}")
        else
          @objects = QuestionBank.where(:container_type => @p, :is_public => 1).includes(:user).order("#{@sort} #{order}")
        end
        @course_list = CourseList.where(:id => @objects.map(&:course_list_id))
        if params[:tag]
          @tag = params[:tag]
          @objects = @objects.where(:course_list_id => params[:tag]).order("#{@sort} #{order}")
        end
    end
    @objects_count = @objects.size
    @objects = paginateHelper @objects, 16

    respond_to do |format|
      format.js
      format.html {
        # 用户签到情况
        attendance = Attendance.where(:user_id => @user).first
        @can_attendance = true
        @next_attachment_score = 10
        if attendance.present?
          if time_between_days(Time.now, attendance.created_at) == 0
            @can_attendance = false
          end
          @next_attachment_score = attendance.next_score
        end

        if @user == User.current && @user.certification != 1
          trail_authentication = ApplyAction.where(:user_id => @user.id, :container_type => "TrialAuthorization").order("created_at desc").first
          if trail_authentication.nil? || trail_authentication.try(:status) != 0
            @apply_trial = true
          end
        end

        @user_watchlist_count = User.watched_by(@user.id).count
        @user_fanlist_count = @user.watcher_users.count

        render :layout => 'base_edu_user'
      }
    end
  end

  def user_info


  end

  # 连续签到六天则每天累加10个金币
  # 中间停歇(隔天),则金币被初始化为50个
  # REDO: 如果有experience可以不需要Attendance
  def attendance
    ActiveRecord::Base.transaction do
      begin
        attendance = Attendance.where(:user_id => @user).first
        score = 50
        # 一天只能签到一次
        if attendance.present?
          return if time_between_days(Time.now, attendance.created_at) == 0 # 已签到则跳出
          score = attendance.next_score
          @next_attachment_score = attendance.next_score
        else
          @next_attachment_score = 50
        end
        @user.update_column(:grade, (@user.grade.to_i + score))
        Attendance.create!(:user_id => @user.id, :score => score)
        Grade.create!(:user_id => @user.id, :score => score, :container_id => User.current.id, :container_type => "Attendance")
      rescue Exception => e
        logger.info("attendance failed #{e}")
      end
    end
    respond_to do |format|
      format.js
      format.html {redirect_to user_grade_user_path(@user)}
    end
  end

  def growth_record
    games = @user.games.where(:status => 2)
    challenge_tags = ChallengeTag.where(:challenge_id => games.map(&:challenge_id))
    games = @user.games.where(:challenge_id => Challenge.where(:id => challenge_tags.map(&:challenge_id)).map(&:id))
    @user_tags = @user.experiences.where(:container_id => games.map(&:id)).reorder("created_at desc")
    @limit = 20
    @is_remote = true
    @tags_count = @user_tags.count
    @tags_pages = Paginator.new @tags_count, @limit, params['page'] || 1
    @offset ||= @tags_pages.offset
    @user_tags = paginateHelper @user_tags, @limit
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_edu_user'}
    end
  end

  def user_experience
    @user_experiences = @user.experiences.where("score > 0").reorder("created_at desc")
    @limit = 10
    @user_experiences = paginateHelper @user_experiences, @limit
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_edu_user'}
    end
  end

  def user_grade
    # 用户签到情况
    attendance = Attendance.where(:user_id => @user).first
    @can_attendance = true
    @next_attachment_score = 5
    if attendance.present?
      if time_between_days(Time.now, attendance.created_at) == 0
        @can_attendance = false
      end
      @next_attachment_score = attendance.next_score
    end
    @type = params[:type] ? params[:type].to_i : 1
    @user_grades = @type == 1 ? @user.grades.where("score > 0").reorder("created_at desc") : @user.grades.where("score < 0").reorder("created_at desc")
    @limit = 10
    @user_grades = paginateHelper @user_grades, @limit
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_edu_user'}
    end
  end

  def switch_user_module
    if params[:type] && params[:status]
      if params[:status].to_i == 0
        User.current.user_hidden_modules.where(:module_type => params[:type]).destroy_all
      elsif params[:status].to_i == 1
        if User.current.user_hidden_modules.where(:module_type => params[:type]).count == 0
          User.current.user_hidden_modules << UserHiddenModule.new(:module_type => params[:type])
        end
      end
    end
  end

  def name_update
    name = params[:name].strip
    @user.update_attribute(:nickname, name) if !name.blank?
  end

  def realname_update
    if (@user.lastname + @user.firstname) != params[:lastname] && @user.certification == 1
      @user.update_attribute(:certification, 0)
      apply_user = ApplyAction.where(:user_id => @user.id, :container_type => "TrialAuthorization")
      apply_user.update_all(:status => 2) unless apply_user.blank?
    end
    lastname = params[:lastname]
    id_number = params[:ID_number] && params[:ID_number].strip != "" ? params[:ID_number] : nil
    gender = params[:gender]
    @user.update_attributes(:lastname => lastname, :firstname => "", :ID_number => id_number)
    @user.extensions.update_attribute(:gender, gender)
    render :json => {name: lastname, id: @user.ID_number ? @user.user_identity_card : "", gender: gender}
  end

  def show_or_hide_realname
    User.current.update_attribute(:show_realname, !User.current.show_realname)
    redirect_to my_account_path
  end

  def update_user_pro
    user_extension = @user.user_extensions
    if user_extension.school_id != params[:occupation].to_i && @user.certification == 1
      @user.update_attribute(:certification, 0)
      apply_user = ApplyAction.where(:user_id => @user.id, :container_type => "TrialAuthorization")
      apply_user.update_all(:status => 2) unless apply_user.blank?
    end

    user_extension.school_id = params[:occupation]
    user_extension.department_id = params[:department_id] && params[:department_id].strip != "" ? params[:department_id] : nil
    user_extension.identity = params[:identity].to_i if params[:identity]
    if user_extension.identity == 0
      user_extension.technical_title = params[:te_technical_title] if params[:te_technical_title]
      user_extension.student_id = nil
    elsif user_extension.identity == 1
      user_extension.student_id = params[:no] if params[:no]
      user_extension.technical_title = nil
    elsif user_extension.identity == 2
      user_extension.technical_title = params[:pro_technical_title] if params[:pro_technical_title]
      user_extension.student_id = nil
    end
    user_extension.save
    req = Hash.new(false)
    req[:school_name] = user_extension.school.name
    req[:department_name] = user_extension.department ? user_extension.department.name : ''
    req[:identity] = user_extension.show_identity
    req[:technical_title] = user_extension.identity == 1 ? user_extension.student_id : user_extension.technical_title

    render :json => req
  end

  def update_user_location
    user_extension = @user.user_extensions
    user_extension.location = params[:province] if params[:province]
    user_extension.location_city = params[:city] if params[:city]
    user_extension.save
    render :json => {location: user_extension.location, location_city: user_extension.location_city}
  end

  def user_show_course_list
    @courses = @user.courses.not_deleted_not_end.order("updated_at desc")
    @courses_count = @courses.count
    # 精品课程
    @ex_courses = Course.where(:homepage_show => 1).order("updated_at desc").limit(8)
    @limit = 8
    @is_remote = true
    @courses_pages = Paginator.new @courses_count, @limit, params['page'] || 1
    @offset ||= @courses_pages.offset
    @courses = paginateHelper @courses, @limit
    respond_to do |format|
      format.js
    end
  end

  # 待解决的Issue
  def unsolved_issues_list
    @unsolved_issues = Issue.where(:assigned_to_id => @user.id, :status_id => [1, 2, 4, 6]).includes(:author, :project).order("updated_on desc")
    @unsolved_issues_count = @unsolved_issues.count
    @limit = 20
    @is_remote = true
    @unsolved_issues_pages = Paginator.new @unsolved_issues_count, @limit, params['page'] || 1
    @offset ||= @unsolved_issues_pages.offset
    @unsolved_issues = paginateHelper @unsolved_issues, @limit
    respond_to do |format|
      format.js
    end
  end

  # 待完成的作业
  def unfinished_homework_list
    my_course_ids = StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").blank? ? "(-1)" : "(" + StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").map {|sc| sc.course_id}.join(",") + ")"
    homeworks = HomeworkCommon.where("course_id in #{my_course_ids} and publish_time <= '#{Time.now}'")
    homework_ids = homeworks.blank? ? "(-1)" : "(" + homeworks.map {|homework| homework.id}.join(",") + ")"
    student_works = StudentWork.where("user_id = #{@user.id} and homework_common_id in #{homework_ids} and work_status != 0")
    finished_works_id = student_works.blank? ? "(-1)" : "(" + student_works.map {|sw| sw.homework_common_id.to_i}.join(",") + ")"
    @unfinished_homeworks = HomeworkCommon.where("course_id in #{my_course_ids} and publish_time <= '#{Time.now}' and id not in #{finished_works_id}").order("updated_at desc")
    @unfinished_homeworks_count = @unfinished_homeworks.count
    @limit = 20
    @unfinished_homework_pages = Paginator.new @unfinished_homeworks_count, @limit, params['page'] || 1
    @offset ||= @unfinished_homework_pages.offset
    @unfinished_homeworks = paginateHelper @unfinished_homeworks, @limit

    respond_to do |format|
      format.js
    end
  end

  # 待完成的测验
  def unfinished_test_list
    my_course_ids = StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").blank? ? "(-1)" : "(" + StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").map {|sc| sc.course_id}.join(",") + ")"
    exercises = Exercise.where("course_id in #{my_course_ids} and exercise_status = 2")
    exercise_ids = exercises.blank? ? "(-1)" : "(" + exercises.map {|ex| ex.id}.join(",") + ")"
    exercise_users = ExerciseUser.where("user_id = #{@user.id} and exercise_id in #{exercise_ids}")
    finished_test_ids = exercise_users.blank? ? "(-1)" : "(" + exercise_users.map {|eu| eu.exercise_id}.join(",") + ")"
    @unfinished_test = Exercise.where("course_id in #{my_course_ids} and exercise_status = 2 and id not in #{finished_test_ids}")
    @unfinished_test_count = @unfinished_test.count
    @limit = 20
    @unfinished_test_pages = Paginator.new @unfinished_test_count, @limit, params['page'] || 1
    @offset ||= @unfinished_test_pages.offset
    @unfinished_test = paginateHelper @unfinished_test, @limit
    respond_to do |format|
      format.js
    end
  end

  # 待完成的问卷
  def unfinished_poll_list
    my_course_ids = StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").blank? ? "(-1)" : "(" + StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").map {|sc| sc.course_id}.join(",") + ")"
    polls = Poll.where("polls_type = 'Course' and polls_group_id in #{my_course_ids} and polls_status = 2")
    poll_ids = polls.blank? ? "(-1)" : "(" + polls.map {|poll| poll.id}.join(",") + ")"
    poll_users = PollUser.where("user_id = #{@user.id} and poll_id in #{poll_ids}")
    finished_poll_ids = poll_users.blank? ? "(-1)" : "(" + poll_users.map {|pu| pu.poll_id}.join(",") + ")"
    @unfinished_poll = Poll.where("polls_type = 'Course' and polls_group_id in #{my_course_ids} and polls_status = 2 and id not in #{finished_poll_ids}").order("updated_at desc")
    @unfinished_poll_count = @unfinished_poll.count
    @limit = 20
    @unfinished_poll_pages = Paginator.new @unfinished_poll_count, @limit, params['page'] || 1
    @offset ||= @unfinished_poll_pages.offset
    @unfinished_poll = paginateHelper @unfinished_poll, @limit
    respond_to do |format|
      format.js
    end
  end

  # 待匿评的作业
  def anonymous_evaluation_list
    my_course_ids = StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").blank? ? "(-1)" : "(" + StudentsForCourse.includes(:course).where("student_id = #{@user.id} and courses.is_delete = 0").map {|sc| sc.course_id}.join(",") + ")"
    homeworks = HomeworkCommon.includes(:homework_detail_manual).where("homework_commons.course_id in #{my_course_ids} and homework_detail_manuals.comment_status in (1,2)")
    homework_ids = homeworks.blank? ? "(-1)" : "(" + homeworks.map {|homework| homework.id}.join(",") + ")"
    student_work_scores = @user.student_works_scores.where("reviewer_role = 3")
    anonymous_evaluation_ids = student_work_scores.blank? ? "(-1)" : "(" + student_work_scores.map {|st| st.student_work_id}.join(",") + ")"
    unfinished_evaluations = @user.student_works_evaluation_distributions.where("student_work_id not in #{anonymous_evaluation_ids}")
    unfinished_evaluations_work_ids = unfinished_evaluations.blank? ? "(-1)" : "(" + unfinished_evaluations.map {|st| st.student_work_id}.join(",") + ")"
    @anonymous_evaluation_count = StudentWork.where("student_works.id in #{unfinished_evaluations_work_ids} and homework_common_id in #{homework_ids}").count
    homework_ids = StudentWork.where("id in #{unfinished_evaluations_work_ids} and homework_common_id in #{homework_ids}").blank? ? "(-1)" : "(" + StudentWork.where("id in #{unfinished_evaluations_work_ids} and homework_common_id in #{homework_ids}").map {|st| st.homework_common_id}.join(",") + ")"
    @anonymous_evaluation = HomeworkCommon.where("homework_commons.id in #{homework_ids}")
    @limit = 20
    @anonymous_evaluation_pages = Paginator.new @anonymous_evaluation.count, @limit, params['page'] || 1
    @offset ||= @anonymous_evaluation_pages.offset
    @anonymous_evaluation = paginateHelper @anonymous_evaluation, @limit
    respond_to do |format|
      format.js
    end
  end

  # 待审批的申请
  # 待审批的消息一般不多,可以特殊处理
  def unapproval_applied_list
    user_id = User.current.id
    sql = "SELECT * FROM `message_alls` ma left join `forge_messages` fm on ma.message_id=fm.id
          left join `course_messages` cm on ma.message_id=cm.id left join `applied_messages` apm on ma.message_id=apm.id
          where (ma.user_id =#{user_id} and ma.message_type = 'ForgeMessage' and fm.forge_message_type='PullRequest' and fm.status=0 and fm.user_id=#{user_id} ) or
          (ma.user_id=#{user_id}  and ma.message_type='AppliedMessage' and apm.applied_type in ('Organization', 'AppliedContest', 'StudentWorksScoresAppeal', 'AppliedProject', 'ApplyAddSchools') and apm.user_id =#{user_id}  and apm.status =0 ) or
          (ma.user_id=#{user_id}  and ma.message_type='CourseMessage' and cm.course_message_type='JoinCourseRequest' and cm.status=0 and cm.user_id=#{user_id}) order by ma.created_at desc;"
    @message_alls = MessageAll.find_by_sql(sql)
    @message_count = @message_alls.count
    @message_alls = paginateHelper @message_alls, 20
    respond_to do |format|
      format.js
    end
  end

  # 课程社区
  def course_community
    @course_community = "课程"
    if params[:course_id] != nil
      join_course_messages = CourseMessage.where("course_id =? and course_message_type =? and user_id =? and course_message_id =? and viewed =?",
                                                 params[:course_id], 'JoinCourseRequest', User.current.id, @user.id, false)
      join_course_messages.update_all(:viewed => true)
    end
    shield_course_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{@user.id} and shield_type='Course'").map(&:shield_id)
    @page = params[:page] ? params[:page].to_i + 1 : 0
    user_course_ids = (@user.favorite_courses.visible.where("is_delete = 0").map {|course| course.id} - shield_course_ids).empty? ? "(-1)" : "(" + (@user.favorite_courses.visible.where("is_delete = 0").map {|course| course.id} - shield_course_ids).join(",") + ")"
    course_types = "('Message','News','HomeworkCommon','Poll','Course','JournalsForMessage','Attachment')"
    principal_types = "JournalsForMessage"
    container_type = ''
    act_type = ''

    if params[:type].present?
      case params[:type]
        when "course_homework"
          container_type = 'Course'
          act_type = 'HomeworkCommon'
        when "course_news"
          container_type = 'Course'
          act_type = 'News'
        when "course_message"
          container_type = 'Course'
          act_type = 'Message'
        when "course_resource"
          container_type = 'Course'
          act_type = "Attachment"
        when "course_poll"
          container_type = 'Course'
          act_type = 'Poll'
        when "course_journals"
          container_type = 'Course'
          act_type = 'JournalsForMessage'
        when "current_user"
          container_type = 'Principal'
          act_type = 'Principal'
        when "all"
          container_type = 'all'
          act_type = 'all'
      end
    end
    if container_type != '' && container_type != 'all'
      if container_type == 'Course'
        sql = "container_type = '#{container_type}' and container_id in #{user_course_ids} and act_type = '#{act_type}'"
      elsif container_type == 'Principal' && act_type == 'Principal'
        sql = "user_id = #{@user.id} and (container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types})"
      end
      if User.current != @user
        sql += " and user_id = #{@user.id}"
      end
    else
      sql = "(container_type = 'Course' and container_id in #{user_course_ids} and act_type in #{course_types})" +
          "or (container_type = 'Principal' and act_type= '#{principal_types}' and container_id = #{@user.id}) "
      if container_type != 'all' && User.current != @user
        sql = "user_id = #{@user.id} and(" + sql + ")"
      end
    end
    @user_activities_count = UserActivity.where("#{sql}").order('updated_at desc').count
    @user_activities = UserActivity.where("#{sql}").order('updated_at desc').limit(10).offset(@page * 10)
    @type = params[:type]
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_course_community'}
    end
  end

  # 项目社区
  def project_community
    @tab = params[:tab].nil? ? 1 : params[:tab].to_i
    @project_community = "我的项目"
    user = User.current
    case @tab
      when 2
        @projects = @user.projects.visible.order("updated_on desc").select {|project| user.manager_of_project?(project)}
      when 3
        @projects = @user.projects.visible.order("updated_on desc").select {|project| !user.has_teacher_role(project)}
      when 1
        @projects = @user.projects.visible.order("updated_on desc")
    end

    @limit = 15
    @projects = paginateHelper @projects, @limit

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

  # 竞赛社区
  def contest_community
    @contest_community = "竞赛"
    shield_contest_ids = ShieldActivity.select("shield_id").where("container_type='User' and container_id=#{@user.id} and shield_type='Contest'").map(&:shield_id)
    @page = params[:page] ? params[:page].to_i + 1 : 0
    user_contest_ids = (@user.favorite_contests.visible.where("is_delete = 0").map {|contest| contest.id} - shield_contest_ids).empty? ? "(-1)" : "(" + (@user.favorite_contests.visible.map {|contest| contest.id} - shield_contest_ids).join(",") + ")"
    contest_types = "('Message','News','Work','Contest','JournalsForMessage')"
    container_type = ''
    act_type = ''

    if params[:type].present?
      case params[:type]
        when "contest_work"
          container_type = 'Contest'
          act_type = 'Work'
        when "contest_news"
          container_type = 'Contest'
          act_type = 'News'
        when "contest_message"
          container_type = 'Contest'
          act_type = 'Message'
        when "contest_journals"
          container_type = 'Contest'
          act_type = 'JournalsForMessage'
        when "current_user"
          container_type = 'Principal'
          act_type = 'Principal'
        when "all"
          container_type = 'all'
          act_type = 'all'
      end
    end
    if container_type != '' && container_type != 'all'
      if container_type == 'Contest'
        sql = "container_type = '#{container_type}' and container_id in #{user_contest_ids} and act_type = '#{act_type}'"
      elsif container_type == 'Principal' && act_type == 'Principal'
        sql = "user_id = #{@user.id} and (container_type = 'Contest' and container_id in #{user_contest_ids} and act_type in #{contest_types})"
      end
      if User.current != @user
        sql += " and user_id = #{@user.id}"
      end
    else
      sql = "(container_type = 'Contest' and container_id in #{user_contest_ids} and act_type in #{contest_types})"
      if container_type != 'all' && User.current != @user
        sql = "user_id = #{@user.id} and(" + sql + ")"
      end
    end
    @user_activities_count = UserActivity.where("#{sql}").order('updated_at desc').count
    @user_activities = UserActivity.where("#{sql}").order('updated_at desc').limit(10).offset(@page * 10)
    @type = params[:type]
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_contest_community'}
    end
  end

  def show_old
    pre_count = 10 #limit
    # Time 2015-02-04 11:46:34
    # Author lizanle
    # Description type 1 :所有动态包括我关注的人 type 2:我的动态 type 3:关于我的回复
    case params[:type]
      when "1"
        if @user == User.current
          activity = Activity.where('user_id = ?', User.current.id).order('id desc')
          @activity_count = activity.count
          @activity_pages = Paginator.new @activity_count, pre_count, params['page']
          @activity = activity.offset(@activity_pages.offset).limit(@activity_pages.per_page).all
          @state = 1
        end
      when "2"
        message = []
        if @user == User.current
          message = JournalsForMessage.reference_message(@user.id)
          message += Journal.reference_message(@user.id)
        end
        @activity_count = message.size
        @info_pages = Paginator.new @activity_count, pre_count, params['page']
        messages = message.sort {|x, y| y.created_on <=> x.created_on}
        @message = messages[@info_pages.offset, @info_pages.per_page]
        @state = 2
      else
        # Time 2015-02-04 10:50:49
        # Author lizanle
        # Description 所有动态
        where_condition = nil;
        # where_condition = "act_type <> 'JournalsForMessage'"
        user_ids = []
        if @user == User.current
          watcher = User.watched_by(@user)
          watcher.push(User.current)
          user_ids = watcher.map {|x| x.id}
        else
          user_ids << @user.id
        end
        activity = Activity.where(where_condition).where(user_id: user_ids).order('id desc')

        permission = !User.current.admin?
        if permission
          #Issue
          act_ids = activity.where(act_type: 'Issue').select('act_id').map {|x| x.act_id}
          project_ids = Issue.where(id: act_ids).select('distinct project_id').map {|x| x.project_id}
          p_ids = []
          Project.where(id: project_ids).each do |x|
            p_ids << x.id unless x.visible?(User.current)
          end
          ids = []
          ids << Issue.where(id: act_ids, project_id: p_ids).map {|x| x.id}

          #HomeworkCommon
          act_ids = activity.where(act_type: 'HomeworkCommon').select('act_id').map {|x| x.act_id}
          course_ids = HomeworkCommon.where(id: act_ids).select('distinct course_id').map {|x| x.course_id}
          c_ids = []
          Course.where(id: course_ids).each do |x|
            c_ids << x.id unless x.is_public != 0 && User.current.member_of_course?(x)
          end
          ids << HomeworkCommon.where(id: act_ids, course_id: c_ids).map {|x| x.id}

          #Journal
          act_ids = activity.where(act_type: 'Journal').select('act_id').map {|x| x.act_id}
          project_ids = Journal.where(id: act_ids, journalized_type: 'Project').select('distinct journalized_id').map {|x| x.journalized_id}
          p_ids = []
          Project.where(id: project_ids).each do |x|
            p_ids << x.id unless x.visible?(User.current)
          end
          ids << Journal.where(id: act_ids, journalized_id: p_ids, journalized_type: 'Project').map {|x| x.id}

          #News
          act_ids = activity.where(act_type: 'News').select('act_id').map {|x| x.act_id}
          project_ids = News.where(id: act_ids).select('distinct project_id').map {|x| x.project_id}
          p_ids = []
          Project.where(id: project_ids).each do |x|
            p_ids << x.id unless x.visible?(User.current)
          end
          ids << News.where(id: act_ids, project_id: p_ids).map {|x| x.id}

          project_ids = News.where(id: act_ids).select('distinct course_id').map {|x| x.course_id}
          c_ids = []
          Course.where(id: project_ids).each do |x|
            c_ids << x.id unless x.is_public != 0 && User.current.member_of_course?(x)
          end
          ids << News.where(id: act_ids, course_id: p_ids).map {|x| x.id}

          #Message
          act_ids = activity.where(act_type: 'Message').select('act_id').map {|x| x.act_id}
          board_ids = Message.where(id: act_ids).select('distinct board_id').map {|x| x.board_id}
          project_ids = Board.where(id: board_ids).select('distinct project_id').map {|x| x.project_id}
          p_ids = []
          Project.where(id: project_ids).each do |x|
            p_ids << x.id unless x.visible?(User.current)
          end
          ids << Message.where(id: act_ids, board_id: p_ids).map {|x| x.id}

          project_ids = Board.where(id: board_ids).select('distinct course_id').map {|x| x.course_id}
          c_ids = []
          Course.where(id: project_ids).each do |x|
            c_ids << x.id unless x.is_public != 0 && User.current.member_of_course?(x)
          end
          ids << Message.where(id: act_ids, board_id: c_ids).map {|x| x.id}

          logger.debug "filter ids #{ids}"

          activity = activity.where('act_id not in (?)', ids.flatten).order('id desc') unless ids.flatten.empty?
        end

        # activity = activity.reject { |e|
        #       e.act.nil? ||
        #       (!User.current.admin? && !e.act.nil?
        #       (((e.act_type == "Issue") && !e.act.project.visible?(User.current)) ||
        #           (e.act_type == "Bid" && !e.act.courses.first.nil? && e.act.courses.first.is_public == 0 && !User.current.member_of_course?(e.act.courses.first)) ||
        #           (e.act_type == "Journal" && e.act.respond_to?("Project") && !e.act.project.visible?(User.current)) ||
        #           (e.act_type == "News" && ((!e.act.project.nil? && !e.act.project.visible?(User.current)) || (!e.act.course.nil? && e.act.course.is_public == 0 && !User.current.member_of_course?(e.act.course)))) ||
        #           (e.act_type == "Message" && !e.act.board.nil? && ((!e.act.board.project.nil? && !e.act.board.project.visible?(User.current)) || (!e.act.board.course.nil? && e.act.board.course.is_public == 0 && !User.current.member_of_course?(e.act.board.course))))))
        # }
        #

        @activity_count = activity.count
        @activity_pages = Paginator.new @activity_count, pre_count, params['page']
        @activity = activity.slice(@activity_pages.offset, @activity_pages.per_page)
        @state = 0
    end

    if params[:user].present?

      user_temp = User.find_by_sql("select id from users where concat(lastname,firstname) like '%#{params[:user]}%' or lastname like '%#{params[:user]}%'")

      if user_temp.size > 1
        activity = Activity.where('user_id in (?)', user_temp).where('user_id in (?)', watcher).order('id desc')
      elsif user_temp.size == 1
        activity = Activity.where('user_id = ?', user_temp).where('user_id in (?)', watcher).order('id desc')
      else
        activity = Activity.where("1 = 0")
      end
      @offset, @limit = api_offset_and_limit({:limit => 10})
      @activity_count = activity.count
      @activity_pages = Paginator.new @activity_count, @limit, params['page']
      @offset ||= @activity_pages.offset
      @activity = activity.offset(@offset).limit(@limit)
      @state = 0
    end


    #Modified by nie
    unless User.current.admin?
      if !@user.active? #|| (@user != User.current  && @memberships.empty? && events.empty?)
        # redirect_to home_path
        render_404
        return
      end
    end

    respond_to do |format|
      format.html
      format.api
    end
  end

  ##end  fq

  #### added by fq
  def info

    message = []
    if @user == User.current
      message = JournalsForMessage.reference_message(@user.id)
      message += Journal.reference_message(@user.id)
    end
    @offset, @limit = api_offset_and_limit({:limit => 10})
    @info_count = message.size
    @info_pages = Paginator.new @info_count, @limit, params['page']
    @offset ||= @info_pages.offset

    messages = message.sort {|x, y| y.created_on <=> x.created_on}

    @message = messages[@offset, @limit]

    unless User.current.admin?
      if !@user.active?
        render_404
        return
      end
    end

    respond_to do |format|
      format.html
      format.api
    end
  end

  #### end


  def new
    @user = User.new(:language => Setting.default_language, :mail_notification => Setting.default_notification_option)
    @auth_sources = AuthSource.all
    render :layout => "users_base"
  end

  def create
    @user = User.new(:language => Setting.default_language, :mail_notification => Setting.default_notification_option)
    @user.safe_attributes = params[:user]
    @user.admin = params[:user][:admin] || false
    @user.login = params[:user][:login]
    @user.password, @user.password_confirmation = params[:user][:password], params[:user][:password_confirmation] unless @user.auth_source_id

    if @user.save
      @user.pref.attributes = params[:pref]
      @user.pref[:no_self_notified] = (params[:no_self_notified] == '1')
      @user.pref.save
      @user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : [])

      Mailer.run.account_information(@user, params[:user][:password]) if params[:send_information]

      respond_to do |format|
        format.html {
          flash[:notice] = l(:notice_user_successful_create, :id => view_context.link_to(@user.login, user_path(@user)))
          if params[:continue]
            redirect_to new_user_url
          else
            redirect_to edit_user_url(@user)
          end
        }
        format.api {render :action => 'show', :status => :created, :location => user_url(@user)}
      end
    else
      @auth_sources = AuthSource.all
      # Clear password input
      @user.password = @user.password_confirmation = nil

      respond_to do |format|
        format.html {render :action => 'new', :layout => "users_base"}
        format.api {render_validation_errors(@user)}
      end
    end

    unless @user.id.nil?
      #后台注册的用户默认权限为男性开发员
      ue = UserExtensions.create(:identity => 3,
                                 :gender => 0,
                                 :user_id => @user.id)
      ue.save
    end
  end

  def edit
    @auth_sources = AuthSource.all
    @membership ||= Member.new
  end

  def watch_projects
    @watch_projects = Project.joins(:watchers).where("project_type <>? and watchable_type = ? and `watchers`.user_id = ?", '1', 'Project', @user.id)
    @state = 1
    respond_to do |format|
      format.html {
        render :layout => 'base_users'
      }
      format.api
    end
  end

  def update
    @user.admin = params[:user][:admin] if params[:user][:admin]
    @user.login = params[:user][:login] if params[:user][:login]
    if params[:user][:password].present? && (@user.auth_source_id.nil? || params[:user][:auth_source_id].blank?)
      @user.password, @user.password_confirmation = params[:user][:password], params[:user][:password_confirmation]
    end
    @user.safe_attributes = params[:user]
    # Was the account actived ? (do it before User#save clears the change)
    was_activated = (@user.status_change == [User::STATUS_REGISTERED, User::STATUS_ACTIVE])
    # TODO: Similar to My#account
    @user.pref.attributes = params[:pref]
    @user.pref[:no_self_notified] = (params[:no_self_notified] == '1')

    if @user.save
      @user.pref.save
      @user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : [])

      if was_activated
        Mailer.run.account_activated(@user)
      elsif @user.active? && params[:send_information] && !params[:user][:password].blank? && @user.auth_source_id.nil?
        Mailer.run.account_information(@user, params[:user][:password])
      end

      respond_to do |format|
        format.html {
          flash[:notice] = l(:notice_successful_update)
          redirect_to_referer_or edit_user_url(@user)
        }
        format.api {render_api_ok}
      end
    else
      @auth_sources = AuthSource.all
      @membership ||= Member.new
      # Clear password input
      @user.password = @user.password_confirmation = nil

      respond_to do |format|
        format.html {render :action => :edit}
        format.api {render_validation_errors(@user)}
      end
    end
  end

  # 上传用户资源
  def user_resource_create
    user_course_ids = User.current.courses.map {|c| c.is_delete == 0 && c.id}
    user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id}
    # user_org_ids = User.current.organizations.map {|o| o.id}
    @user = User.current
    # 保存文件
    attach = Attachment.attach_filesex_public(@user, params[:attachments], params[:attachment_type], is_public = true)
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    # user_org_ids = User.current.organizations.map {|o| o.id}
    if (params[:type].blank? || params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      if params[:status] == "2"
        @attachments = get_course_resources(@user.id, user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources(@user.id, user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources(@user.id, @order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources(@user.id, @order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_my_resources(@user.id, user_course_ids, user_project_ids, @order, @score)
      end
    elsif params[:type] == "6" # 公共资源
      if params[:status] == "2"
        @attachments = get_course_resources_public(user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources_public(user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_public(@order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_public(@order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
      end
    end

    @status = params[:status]
    @type = params[:type]
    @path = user_resource_user_path(User.current, :type => @type)
    @limit = 25
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 25
    respond_to do |format|
      format.js
    end
  end

  # 删除用户资源,分为批量删除 和 单个删除,只能删除自己上传的资源
  def user_resource_delete
    if params[:resource_id].present?
      Attachment.where("author_id =? and id =?", User.current.id, params[:resource_id]).first.destroy
    elsif params[:checkbox1].present?
      params[:checkbox1].each do |id|
        Attachment.where("author_id =? and id =?", User.current.id, id).first.destroy
      end
    end
    @user = User.current
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    user_course_ids = User.current.courses.map {|c| c.id}
    user_project_ids = User.current.projects.map {|p| p.id}
    # user_org_ids = User.current.organizations.map {|o| o.id}
    if (params[:type].blank? || params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      if params[:status] == "2"
        @attachments = get_course_resources(@user.id, user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources(@user.id, user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources(@user.id, @order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources(@user.id, @order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_my_resources(@user.id, user_course_ids, user_project_ids, @order, @score)
      end
    elsif params[:type] == "6" # 公共资源
      if params[:status] == "2"
        @attachments = get_course_resources_public(user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources_public(user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_public(@order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_public(@order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
      end
    end
    @status = params[:status]
    @type = params[:type]
    @path = user_resource_user_path(User.current, :type => @type)
    @limit = 25
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 25
    respond_to do |format|
      format.js
    end
  end

  #根据id或者名称搜索教师或者助教为当前用户的课程
  def search_user_course
    @user = User.current
    if !params[:search].nil?
      search = "%#{params[:search].to_s.strip.downcase}%"
      @course = @user.courses.not_deleted_not_end.where(" #{Course.table_name}.id = #{params[:search].to_i } or #{Course.table_name}.name like :p", :p => search)
    else
      @course = @user.courses.not_deleted_not_end
    end
    @search = params[:search]
    @type = params[:type]
    #这里仅仅是传递需要发送的资源id
    @send_id = params[:send_id]
    @send_ids = params[:checkbox1] || params[:send_ids]
    respond_to do |format|
      format.js
    end
  end

  # 根据id或者名称搜索当前用户所在的项目
  def search_user_project
    @user = User.current
    if !params[:search].nil?
      search = "%#{params[:search].to_s.strip.downcase}%"
      @projects = @user.projects.visible.where(" #{Project.table_name}.id = #{params[:search].to_i } or #{Project.table_name}.name like :p", :p => search)
    else
      @projects = @user.projects.visible
    end
    @search = params[:search]
    @type = params[:type]
    #这里仅仅是传递需要发送的资源id
    @send_id = params[:send_id]
    @send_ids = params[:checkbox1] || params[:send_ids] #搜索的时候  和 直接 用表格提交的时候的send_ids
    @hidden_unproject = hidden_unproject_infos
    respond_to do |format|
      format.js
    end
  end

  # 将资源发送到对应的课程,分为发送单个,或者批量发送
  def add_exist_file_to_course
    @flag = true
    if params[:send_id].present?
      rs = ResourcesService.new
      @ori, @flag, @save_message = rs.send_resource_to_course(User.current, params)
    elsif params[:send_ids].present?
      send_ids = params[:send_ids].split(",")
      course_ids = params[:course_ids]
      if course_ids.nil?
        @flag = false
      end
      send_ids.each do |send_id|
        quotes = 0
        @ori = Attachment.find_by_id(send_id)
        unless course_ids.nil?
          course_ids.each do |id|
            quotes = 0
            next if @ori.blank?
            @exist = false
            Course.find(id).attachments.each do |att| #如果课程中包含该资源
              if att.id == @ori.id || (!att.copy_from.nil? && !@ori.copy_from.nil? && att.copy_from == @ori.copy_from) || att.copy_from == @ori.id || att.id == @ori.copy_from
                att.created_on = Time.now
                att.save
                @exist = true
                break
              end
            end
            next if @exist
            attach_copied_obj = @ori.copy
            attach_copied_obj.tag_list.add(@ori.tag_list) # tag关联
            attach_copied_obj.container = Course.find(id)
            attach_copied_obj.created_on = Time.now
            attach_copied_obj.author_id = User.current.id
            attach_copied_obj.is_public = 1
            attach_copied_obj.unified_setting = 1
            attach_copied_obj.copy_from = @ori.copy_from.nil? ? @ori.id : @ori.copy_from #发送要添加copy_from
            if attach_copied_obj.attachtype == nil
              attach_copied_obj.attachtype = 4
            end
            if attach_copied_obj.save
              # 更新引用次数
              quotes = @ori.quotes.to_i + 1
              @ori.update_attribute(:quotes, quotes) unless @ori.nil?
              @ori.forwards << Forward.new(:to_type => attach_copied_obj.class.name, :to_id => attach_copied_obj.id, :created_at => Time.now)
            end
            @save_message = attach_copied_obj.errors.full_messages
          end
        end
      end
    else
      @flag = false
    end
    # @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    # @score = @b_sort == "desc" ? "asc" : "desc"
    # user_project_ids = User.current.projects.map {|p| p.id}
    # user_course_ids = User.current.courses.map { |c| c.id}  #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
    # if(params[:type] == "1") # 我的资源
    #   # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
    #   if params[:status] == "2"
    #     @attachments = get_course_resources(User.current.id, user_course_ids, @order, @score)
    #   elsif params[:status] == "3"
    #     @attachments = get_project_resources(User.current.id, user_project_ids, @order, @score)
    #   elsif params[:status] == "4"
    #     @attachments = get_attch_resources(User.current.id, @order, @score)
    #   elsif params[:status] == "5"
    #     @attachments = get_principal_resources(User.current.id, @order, @score)
    #   else
    #     # 公共资源库:所有公开资源或者我上传的私有资源
    #     @attachments = get_my_resources(User.current.id, user_course_ids, user_project_ids, @order, @score)
    #   end
    # elsif (params[:type].blank? || params[:type] == "6") # 公共资源
    #   if params[:status] == "2"
    #     @attachments = get_course_resources_public( user_course_ids, @order, @score)
    #   elsif params[:status] == "3"
    #     @attachments = get_project_resources_public(user_project_ids, @order, @score)
    #   elsif params[:status] == "4"
    #     @attachments = get_attch_resources_public(@order, @score)
    #   elsif params[:status] == "5"
    #     @attachments = get_principal_resources_public(@order, @score)
    #   else
    #     # 公共资源库:所有公开资源或者我上传的私有资源
    #     @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
    #   end
    #   # elsif params[:type] == "2"
    #   #   apply_ids = ApplyResource.where("user_id =? and status =?", params[:id], 2).map { |ar| ar.attachment_id}
    #   #   if params[:status] == "2"
    #   #     resource_type = "'Course'"
    #   #   elsif params[:status] == "3"
    #   #     resource_type = "'Project'"
    #   #   elsif params[:status] == "5"
    #   #     resource_type = "'Principal'"
    #   #   else
    #   #     resource_type = "'Project','OrgSubfield','Principal','Course'"
    #   #   end
    #   #   @attachments = get_my_private_resources(apply_ids, resource_type, @order, @score)
    # end
    # @type = params[:type]
    # @limit = 25
    # @path = user_resource_user_path(User.current, :type => @type)
    # @user = User.current
    # @is_remote = true
    # @atta_count = @attachments.count
    # @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    # @offset ||= @atta_pages.offset
    # #@curse_attachments_all = @all_attachments[@offset, @limit]
    # @attachments = paginateHelper @attachments,25
    @course = @ori.course
    respond_to do |format|
      format.js
    end
  end

  # 添加资源到对应的项目
  def add_exist_file_to_project
    @flag = true
    # 发送单个资源
    if params[:send_id].present?
      send_id = params[:send_id]
      project_ids = params[:projects_ids]
      if project_ids.nil?
        @flag = false
      end
      ori = Attachment.find_by_id(send_id)
      unless project_ids.nil?
        project_ids.each do |project_id|
          next if ori.blank?
          @exist = false
          # 如果对象中包含该资源
          Project.find(project_id).attachments.each do |att|
            if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from
              att.created_on = Time.now
              att.save
              @exist = true
              break
            end
          end
          next if @exist
          attach_copied_obj = ori.copy
          attach_copied_obj.tag_list.add(ori.tag_list) # tag关联
          attach_copied_obj.container = Project.find(project_id)
          attach_copied_obj.created_on = Time.now
          attach_copied_obj.author_id = User.current.id
          attach_copied_obj.is_public = 0
          attach_copied_obj.copy_from = ori.copy_from.nil? ? ori.id : ori.copy_from #发送要添加copy_from
          if attach_copied_obj.attachtype == nil
            attach_copied_obj.attachtype = 1
          end
          if attach_copied_obj.save
            # 更新引用次数
            quotes = ori.quotes.to_i + 1
            ori.update_attribute(:quotes, quotes) unless ori.nil?
            ori.forwards << Forward.new(:to_type => attach_copied_obj.class.name, :to_id => attach_copied_obj.id, :created_at => Time.now)
            # 项目中添加动态
            ForgeActivity.create(:user_id => User.current.id, :project_id => project_id, :forge_act_id => attach_copied_obj.id, :forge_act_type => "Attachment")
          end
          unless Project.find(project_id).project_score.nil?
            Project.find(project_id).project_score.update_attribute(:attach_num,
                                                                    Project.find(project_id).project_score.attach_num + 1)
          end
        end
        @ori = ori
      end
      # 发送多个资源
    elsif params[:send_ids].present?
      send_ids = params[:send_ids].split(",")
      project_ids = params[:projects_ids]
      if project_ids.nil?
        @flag = false
      end
      send_ids.each do |send_id|
        quotes = 0
        ori = Attachment.find_by_id(send_id)
        unless project_ids.nil?
          project_ids.each do |project_id|
            quotes = 0
            next if ori.blank?
            @exist = false
            Project.find(project_id).attachments.each do |att| #如果课程中包含该资源
              if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from
                att.created_on = Time.now
                att.save
                @exist = true
                break
              end
            end
            next if @exist
            attach_copied_obj = ori.copy
            attach_copied_obj.tag_list.add(ori.tag_list) # tag关联
            attach_copied_obj.container = Project.find(project_id)
            attach_copied_obj.created_on = Time.now
            attach_copied_obj.author_id = User.current.id
            attach_copied_obj.is_public = 0
            attach_copied_obj.copy_from = ori.copy_from.nil? ? ori.id : ori.copy_from #发送要添加copy_from
            if attach_copied_obj.attachtype == nil
              attach_copied_obj.attachtype = 1
            end
            if attach_copied_obj.save
              # 更新引用次数
              quotes = ori.quotes.to_i + 1
              ori.update_attribute(:quotes, quotes) unless ori.nil?
              ori.forwards << Forward.new(:to_type => attach_copied_obj.class.name, :to_id => attach_copied_obj.id, :created_at => Time.now)
              # 项目中添加动态
              ForgeActivity.create(:user_id => User.current.id, :project_id => project_id, :forge_act_id => attach_copied_obj.id, :forge_act_type => "Attachment")
            end
            unless Project.find(project_id).project_score.nil?
              Project.find(project_id).project_score.update_attribute(:attach_num, Project.find(project_id).project_score.attach_num + 1)
            end
          end
        end
      end
    else
      @flag = true
    end
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    user_project_ids = User.current.projects.map {|p| p.id}
    user_course_ids = User.current.courses.map {|c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
    if (params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      if params[:status] == "2"
        @attachments = get_course_resources(User.current.id, user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources(User.current.id, user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources(User.current.id, @order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources(User.current.id, @order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_my_resources(User.current.id, user_course_ids, user_project_ids, @order, @score)
      end
    elsif (params[:type].blank? || params[:type] == "6") # 公共资源
      if params[:status] == "2"
        @attachments = get_course_resources_public(user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources_public(user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_public(@order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_public(@order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
      end
      # elsif params[:type] == "2"
      #   apply_ids = ApplyResource.where("user_id =? and status =?", params[:id], 2).map { |ar| ar.attachment_id}
      #   if params[:status] == "2"
      #     resource_type = "'Course'"
      #   elsif params[:status] == "3"
      #     resource_type = "'Project'"
      #   elsif params[:status] == "5"
      #     resource_type = "'Principal'"
      #   else
      #     resource_type = "'Project','OrgSubfield','Principal','Course'"
      #   end
      #   @attachments = get_my_private_resources(apply_ids, resource_type, @order, @score)
    end
    @status = params[:status]
    @type = params[:type]
    @limit = 25
    @path = user_resource_user_path(User.current, :type => @type)
    @user = User.current
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 25
    respond_to do |format|
      format.js
    end
  end

  def add_exist_file_to_org
    @flag = true
    if params[:send_id].present?
      send_id = params[:send_id]
      subfield_id = params[:subfield]
      if subfield_id.nil?
        @flag = false
      end
      ori = Attachment.find_by_id(send_id)
      unless subfield_id.nil?
        attach_copied_obj = ori.copy
        @exist = false
        OrgSubfield.find(subfield_id).attachments.each do |att| #如果课程中包含该资源
          if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from
            att.created_on = Time.now
            att.save
            @exist = true
            break
          end
        end
        if @exist == false #如果不存在该资源
          attach_copied_obj.tag_list.add(ori.tag_list) # tag关联
          attach_copied_obj.container = OrgSubfield.find(subfield_id)
          attach_copied_obj.created_on = Time.now
          attach_copied_obj.author_id = User.current.id
          attach_copied_obj.is_public = 0
          attach_copied_obj.copy_from = ori.copy_from.nil? ? ori.id : ori.copy_from #发送要添加copy_from
          if attach_copied_obj.attachtype == nil
            attach_copied_obj.attachtype = 1
          end
          if attach_copied_obj.save
            # 更新引用次数
            quotes = ori.quotes.to_i + 1
            ori.update_attribute(:quotes, quotes) unless ori.nil?
            ori.forwards << Forward.new(:to_type => attach_copied_obj.class.name, :to_id => attach_copied_obj.id, :created_at => Time.now)
          end
        end
      end
      @ori = ori
    elsif params[:send_ids].present?
      send_ids = params[:send_ids].split(",")
      subfield_id = params[:subfield]
      if subfield_id.nil?
        @flag = false
      end
      send_ids.each do |send_id|
        quotes = 0
        ori = Attachment.find_by_id(send_id)
        unless subfield_id.nil?
          next if ori.blank?
          @exist = false
          OrgSubfield.find(subfield_id).attachments.each do |att| #如果课程中包含该资源
            if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from
              att.created_on = Time.now
              att.save
              @exist = true
              break
            end
          end
          next if @exist
          attach_copied_obj = ori.copy
          attach_copied_obj.tag_list.add(ori.tag_list) # tag关联
          attach_copied_obj.container = OrgSubfield.find(subfield_id)
          attach_copied_obj.created_on = Time.now
          attach_copied_obj.author_id = User.current.id
          attach_copied_obj.is_public = 0
          attach_copied_obj.copy_from = ori.copy_from.nil? ? ori.id : ori.copy_from #发送要添加copy_from
          if attach_copied_obj.attachtype == nil
            attach_copied_obj.attachtype = 1
          end
          if attach_copied_obj.save
            # 更新引用次数
            quotes = ori.quotes.to_i + 1
            ori.update_attribute(:quotes, quotes) unless ori.nil?
            ori.forwards << Forward.new(:to_type => attach_copied_obj.class.name, :to_id => attach_copied_obj.id, :created_at => Time.now)
          end
        end
      end
    else
      @flag = true
    end
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    user_project_ids = User.current.projects.map {|p| p.id}
    user_course_ids = User.current.courses.map {|c| c.id} #我的资源库的话,那么应该是我上传的所有资源 加上 我加入的课程的所有资源
    if (params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      if params[:status] == "2"
        @attachments = get_course_resources(User.current.id, user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources(User.current.id, user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources(User.current.id, @order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources(User.current.id, @order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_my_resources(User.current.id, user_course_ids, user_project_ids, @order, @score)
      end
    elsif (params[:type].blank? || params[:type] == "6") # 公共资源
      if params[:status] == "2"
        @attachments = get_course_resources_public(user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources_public(user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_public(@order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_public(@order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
      end
      # elsif params[:type] == "2"
      #   apply_ids = ApplyResource.where("user_id =? and status =?", params[:id], 2).map { |ar| ar.attachment_id}
      #   if params[:status] == "2"
      #     resource_type = "'Course'"
      #   elsif params[:status] == "3"
      #     resource_type = "'Project'"
      #   elsif params[:status] == "5"
      #     resource_type = "'Principal'"
      #   else
      #     resource_type = "'Project','OrgSubfield','Principal','Course'"
      #   end
      #   @attachments = get_my_private_resources(apply_ids, resource_type, @order, @score)
    end
    @type = params[:type]
    @limit = 25
    @path = user_resource_user_path(User.current, :type => @type)
    @user = User.current
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 25
    respond_to do |format|
      format.js
    end
  end

  def share_news_to_course
    news = News.find(params[:send_id])
    course_ids = params[:course_ids]
    course_ids.each do |course_id|
      if Course.find(course_id).news.map(&:id).exclude?(news.id)
        course_news = News.create(:course_id => course_id.to_i, :title => news.title, :summary => news.summary, :description => news.description, :author_id => User.current.id, :created_on => Time.now, :project_id => -1)
        #record forward to table forwards if new record is valid
        if course_news.valid?
          news.forwards << Forward.new(:to_type => course_news.class.name, :to_id => course_news.id)
        end
        news.attachments.each do |attach|
          course_news.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest,
                                                    :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype,
                                                    :is_public => attach.is_public, :quotes => 0)
        end
      end
    end
  end

  def share_news_to_project
    news = News.find(params[:send_id])
    project_ids = params[:project_ids]
    project_ids.each do |project_id|
      project = Project.find(project_id)
      if project.news.map(&:id).exclude?(news.id)
        #  message = Message.create(:board_id => project.boards.first.id, :subject => news.title, :content => news.description, :author_id => User.current.id)
        message = News.create(:project_id => project.id, :title => news.title, :summary => news.summary, :description => news.description, :author_id => User.current.id, :created_on => Time.now)
        # record forward to table forwards if new record is valid
        if message.valid?
          news.forwards << Forward.new(:to_type => message.class.name, :to_id => message.id)
        end
        news.attachments.each do |attach|
          message.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest,
                                                :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype,
                                                :is_public => attach.is_public, :quotes => 0)
        end
      end
    end
  end

  def share_news_to_org
    news = News.find(params[:send_id])
    field_id = params[:subfield]
    org_news = News.create(:org_subfield_id => field_id.to_i, :title => news.title, :summary => news.summary, :description => news.description, :author_id => User.current.id, :created_on => Time.now, :project_id => -1)
    # record forward to table forwards if new record is valid
    if org_news.valid?
      news.forwards << Forward.new(:to_type => org_news.class.name, :to_id => org_news.id)
    end
    news.attachments.each do |attach|
      org_news.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest,
                                             :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype,
                                             :is_public => attach.is_public, :quotes => 0)
    end
    OrgActivity.create(:container_type => 'OrgSubfield', :container_id => field_id.to_i, :org_act_type => 'News', :org_act_id => org_news.id, :user_id => User.current.id)
  end

  def share_message_to_course
    @message = Message.find(params[:send_id])
    course_ids = params[:course_ids]
    course_ids.each do |course_id|
      course = Course.find(course_id)
      if course.news.map(&:id).exclude?(@message.id)
        message = Message.create(:board_id => course.boards.first.id, :subject => @message.subject, :content => @message.content, :author_id => User.current.id)
        # record forward to table forwards if new record is valid
        if message.valid?
          @message.forwards << Forward.new(:to_type => message.class.name, :to_id => message.id)
        end
        @message.attachments.each do |attach|
          message.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest,
                                                :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype,
                                                :is_public => attach.is_public, :quotes => 0)
        end
      end
    end
  end

  def share_message_to_project
    @message = Message.find(params[:send_id])
    project_ids = params[:project_ids]
    project_ids.each do |project_id|
      project = Project.find(project_id)
      if project.news.map(&:id).exclude?(@message.id)
        message = Message.create(:board_id => project.boards.first.id, :subject => @message.subject, :content => @message.content, :author_id => User.current.id)
        # record forward to table forwards if new record is valid
        if message.valid?
          @message.forwards << Forward.new(:to_type => message.class.name, :to_id => message.id)
        end
        @message.attachments.each do |attach|
          message.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest,
                                                :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype,
                                                :is_public => attach.is_public, :quotes => 0)
        end
      end
    end
  end

  def share_message_to_org
    field_id = params[:subfield]
    @message = Message.find(params[:send_id])
    @message.quotes = @message.quotes.nil? ? 1 : (@message.quotes + 1)
    @message.save
    board = OrgSubfield.find(field_id).boards.first
    mes = Message.create(:board_id => board.id, :subject => @message.subject, :content => @message.content, :author_id => User.current.id)
    # record forward to table forwards if new record is valid
    if mes.valid?
      @message.forwards << Forward.new(:to_type => mes.class.name, :to_id => mes.id)
    end
    @message.attachments.each do |attach|
      mes.attachments << Attachment.new(:filename => attach.filename, :disk_filename => attach.disk_filename, :filesize => attach.filesize, :content_type => attach.content_type, :digest => attach.digest,
                                        :downloads => 0, :author_id => User.current.id, :created_on => Time.now, :description => attach.description, :disk_directory => attach.disk_directory, :attachtype => attach.attachtype,
                                        :is_public => attach.is_public, :quotes => 0)
    end
    OrgActivity.create(:container_type => 'OrgSubfield', :container_id => field_id.to_i, :org_act_type => 'Message', :org_act_id => mes.id, :user_id => User.current.id)
  end

  def change_org_subfield

  end

  # 资源预览
  def resource_preview
    preview_id = params[:resource_id]
    @file = Attachment.find(preview_id)
    @preview_able = false;
    if %w(pdf pptx doc docx xls xlsx).any? {|x| @file.filename.downcase.end_with?(x)}
      @preview_able = true;
    end
    respond_to do |format|
      format.js
    end
  end

  # 重命名资源
  def rename_resource
    @attachment = Attachment.find(params[:res_id]) if params[:res_id].present?
    if @attachment != nil
      @attachment.filename = params[:res_name]
      @flag = @attachment.save
    end
    # respond_to do |format|
    #   format.js
    # end
    if @flag
      render :text => download_named_attachment_path(@attachment.id, @attachment.filename)
    else
      render :text => 'fail'
    end
  end

  def destroy
    @user.destroy
    respond_to do |format|
      format.html {redirect_back_or_default(params[:back_url])}
      format.api {render_api_ok}
    end
  end

  def edit_membership
    @membership = Member.edit_membership(params[:membership_id], params[:membership], @user)
    @membership.save
    respond_to do |format|
      format.html {redirect_to edit_user_url(@user, :tab => 'memberships')}
      format.js
    end
  end

  def destroy_membership
    @membership = Member.find(params[:membership_id])
    if @membership.deletable?
      @membership.destroy
    end
    respond_to do |format|
      format.html {redirect_to edit_user_url(@user, :tab => 'memberships')}
      format.js
    end
  end

  ################# added by william
  def tag_save
    @tags = params[:tag_for_save][:name]
    @obj_id = params[:tag_for_save][:object_id]
    @obj_flag = params[:tag_for_save][:object_flag]

    case @obj_flag
      when '1' then
        @obj = User.find_by_id(@obj_id)
      when '2' then
        @obj = Project.find_by_id(@obj_id)
      when '3' then
        @obj = Issue.find_by_id(@obj_id)
      when '4' then
        # @obj = Bid.find_by_id(@obj_id)
      when '5' then
        @obj = Forum.find_by_id(@obj_id)
      when '6'
        @obj = Attachment.find_by_id(@obj_id)
      when '7' then
        @obj = Contest.find_by_id(@obj_id)
      when '8'
        @obj = OpenSourceProject.find_by_id(@obj_id)
      when '9'
        @obj = Course.find_by_id(@obj_id)
      else
        @obj = nil
    end
    unless @obj.nil?
      @obj.tag_list.add(@tags.split(","))
    else
      return
    end
    if @obj.save
      logger.debug "#{__FILE__}:#{__LINE__} ===> #{@obj.to_json}"
    else
      logger.error "#{__FILE__}:#{__LINE__} ===> #{@obj.errors.try(:full_messages)}"
    end
    respond_to do |format|
      format.js
      format.html
    end
  end

  def tag_saveEx
    @tags = params[:tag_name]
    @obj_id = params[:obj_id]
    @obj_flag = params[:obj_flag]

    case @obj_flag
      when '1' then
        @obj = User.find_by_id(@obj_id)
      when '2' then
        @obj = Project.find_by_id(@obj_id)
      when '3' then
        @obj = Issue.find_by_id(@obj_id)
      when '4' then
        # @obj = Bid.find_by_id(@obj_id)
      when '5' then
        @obj = Forum.find_by_id(@obj_id)
      when '6'
        @obj = Attachment.find_by_id(@obj_id)
      when '7' then
        @obj = Contest.find_by_id(@obj_id)
      when '8'
        @obj = OpenSourceProject.find_by_id(@obj_id)
      when '9'
        @obj = Course.find_by_id(@obj_id)
      else
        @obj = nil
    end
    unless @obj.nil?
      @obj.tag_list.add(@tags.split(","))
    else
      return
    end
    if @obj.save
      ## 执行成功的操作。
    else
      #捕获异常
    end
    respond_to do |format|
      format.js
      format.html
    end
  end

  ###add by huang
  def user_watchlist
    watch_query = User.watched_by(@user.id)
    @user_watchlist_count = watch_query.size
    @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc")
    @limit = 10
    @user_watchlist = paginateHelper @user_watchlist, @limit
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_edu_user'}
    end
  end

  ###add by huang
  def user_fanslist
    fan_query = @user.watcher_users
    @user_fanlist_count = fan_query.size
    @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")

    @limit = 10
    @user_fanlist = paginateHelper @user_fanlist, @limit
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_edu_user'}
    end
  end

  def user_wathlist_and_fanslist
    watch_query = User.watched_by(@user.id)
    @user_watchlist_count = watch_query.count
    @user_watchlist = watch_query.order("#{Watcher.table_name}.id desc")
    fan_query = @user.watcher_users
    @user_fanlist_count = fan_query.count
    @user_fanlist = fan_query.order("#{Watcher.table_name}.id desc")
    respond_to do |format|
      format.html {render :layout => 'base_edu_user'}
    end
  end

  def user_visitorlist
    limit = 10;
    #query = @user.watcher_users;
    query = User.joins("join visitors v on #{User.table_name}.id=v.user_id")
    query = query.where("v.master_id=?", @user.id)
    @obj_count = query.count();
    @obj_pages = Paginator.new @obj_count, limit, params['page']
    @list = query.order("v.updated_on desc").limit(limit).offset(@obj_pages.offset).all();
    @action = 'visitor'
    render :template => 'users/user_fanslist', :layout => 'base_users_new'
  end

  #william
  def update_extensions(user_extensions)
    user_extensions = params[:user_extensions]
    unless user_extensions.nil?
      user_extensions = UserExtensions.find_by_id(user_extensions.user_id)

      # user_extensions.
    end
  end

  def update_score
    @user = User.find(params[:id])
  end

  #修改个人简介
  def edit_brief_introduction
    if @user && @user.extensions
      @user.extensions.update_column("brief_introduction", params[:brief_introduction])
    end
    respond_to do |format|
      format.js
    end
  end

  # 获取公共资源
  def get_public_resources user_course_ids, user_project_ids, order, score
    attachments = Attachment.where("(is_publish = 1 and is_public = 1 and container_id is not null and container_type in('Project','Principal','Course')) ").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取公共资源搜索
  def get_public_resources_search user_course_ids, user_project_ids, order, score, search
    attachments = Attachment.includes(:author).where("is_publish = 1 and is_public = 1 and container_id is not null and container_type in('Project','Principal','Course') and (filename like :p or LOWER(concat(users.lastname, users.firstname)) LIKE :p)", :p => search).order("#{order.nil? ? 'attachments.created_on' : order} #{score}")
  end

  # 获取我的资源
  def get_my_resources author_id, user_course_ids, user_project_ids, order, score
    attachments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type in('Principal','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) " +
                                       "or (container_type = 'Course'  and container_id in (#{user_course_ids.empty? ? '0' : user_course_ids.join(',')}) and is_publish = 1 and container_id is not null)" +
                                       "or (container_type = 'Project'  and container_id in (#{user_project_ids.empty? ? '0' : user_project_ids.join(',')}) and is_publish = 1 and container_id is not null)").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我的资源查询结果
  def get_my_resources_search (author_id, user_course_ids, user_project_ids, order, score, search)
    @attachments = Attachment.includes(:author).where("((author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type in('Project','Principal','Course','Issue','Document','Message','News','StudentWorkScore','HomewCommon')) " +
                                                          "or (container_type = 'Course'  and container_id in (#{user_course_ids.empty? ? '0' : user_course_ids.join(',')}) and is_publish = 1 and container_id is not null)" +
                                                          "or (container_type = 'Project'  and container_id in (#{user_project_ids.empty? ? '0' : user_project_ids.join(',')}) and is_publish = 1 and container_id is not null)) and (filename like :p or LOWER(concat(users.lastname, users.firstname)) LIKE :p)", :p => search).order("#{order.nil? ? 'attachments.created_on' : order} #{score}")
  end

  # 获取我的课程资源
  def get_course_resources author_id, user_course_ids, order, score
    attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_id in (#{user_course_ids.empty? ? '0' : user_course_ids.join(',')}) and container_type = 'Course')" +
                                      "or (container_type = 'Course' and container_id in (#{user_course_ids.empty? ? '0' : user_course_ids.join(',')})
                               and is_publish = 1 and container_id is not null)").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # # 获取我的私有资源分享结果
  # def get_my_private_resources apply_ids, resource_type, order, score
  #   attachments = Attachment.where("id in (#{apply_ids.empty? ? '0': apply_ids.join(',')}) and container_type in(#{resource_type})").order("#{order.nil? ? 'created_on' : order} #{score}")
  # end
  #
  # # 获取我的私有资源分享搜索结果
  # def get_my_private_resources_search apply_ids, resource_type, order, score, search
  #   attachments = Attachment.where("id in (#{apply_ids.empty? ? '0': apply_ids.join(',')}) and container_type in(#{resource_type}) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  # end

  # 获取我的课程资源中搜索结果
  def get_course_resources_search author_id, user_course_ids, order, score, search
    attchments = Attachment.where("((author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Course')" +
                                      "or (container_type = 'Course'  and container_id in (#{user_course_ids.empty? ? '0' : user_course_ids.join(',')})
                               and is_publish = 1 and container_id is not null)) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取公共资源中课程资源
  def get_course_resources_public user_course_ids, order, score
    attchments = Attachment.where("(container_type = 'Course'and container_id is not null and is_publish = 1 and is_public =1)").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取公共资源中课程资源搜索结果
  def get_course_resources_public_search user_course_ids, order, score, search
    attchments = Attachment.where("(container_type = 'Course'and container_id is not null and is_publish = 1 and is_public =1) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我的项目资源
  def get_project_resources author_id, user_project_ids, order, score
    attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Project') " +
                                      "or (container_type = 'Project'  and container_id in (#{user_project_ids.empty? ? '0' : user_project_ids.join(',')})
                              and is_publish = 1 and container_id is not null)").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我的项目资源搜索
  def get_project_resources_search author_id, user_project_ids, order, score, search
    attchments = Attachment.where("((author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Project') " +
                                      "or (container_type = 'Project'  and container_id in (#{user_project_ids.empty? ? '0' : user_project_ids.join(',')})
                              and is_publish = 1 and container_id is not null)) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取公共资源的项目资源
  def get_project_resources_public user_project_ids, order, score
    attchments = Attachment.where("container_type = 'Project' and container_id is not null and is_public =1").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取公共资源的项目资源搜索
  def get_project_resources_public_search user_project_ids, order, score, search
    attchments = Attachment.where("(container_type = 'Project' and container_id is not null and is_public =1) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我上传的附件
  def get_attch_resources author_id, order, score
    attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type in('Project','OrgSubfield','Principal','Course','Issue',
                               'Document','Message','News','StudentWorkScore','HomewCommon'))").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我上传的附件搜索结果
  def get_attch_resources_search author_id, order, score, search
    attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type in('Project','OrgSubfield','Principal','Course','Issue',
                               'Document','Message','News','StudentWorkScore','HomewCommon')) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取公共资源中我上传的附件
  def get_attch_resources_public order, score
    attchments = Attachment.where("container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon','OrgSubfield','Principal')
                               and container_id is not null and is_public =1").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取公共资源中我上传的附件
  def get_attch_resources_public_search order, score, search
    attchments = Attachment.where("(container_type in('Issue','Document','Message','News','StudentWorkScore','HomewCommon','OrgSubfield','Principal')
                               and container_id is not null and is_public =1) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我的用户类型资源
  def get_principal_resources author_id, order, score
    attchments = Attachment.where("author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Principal'").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我的用户类型资源搜索
  def get_principal_resources_search author_id, order, score, search
    attchments = Attachment.where("(author_id = #{author_id} and is_publish = 1 and container_id is not null and container_type = 'Principal') and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我的用户类型资源
  def get_principal_resources_public order, score
    attchments = Attachment.where("container_type = 'Principal' and is_public =1 and container_id is not null").order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 获取我的用户类型资源
  def get_principal_resources_public_search order, score, search
    attchments = Attachment.where("(container_type = 'Principal'and container_id is not null and is_public =1) and (filename like :p)", :p => search).order("#{order.nil? ? 'created_on' : order} #{score}")
  end

  # 资源库 分为全部  课程资源 项目资源 附件
  def user_resource
    # 别人的资源库是没有权限去看的
    if User.current.id.to_i != @user.id.to_i
      render_403
      return
    end
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    user_course_ids = User.current.courses.map {|c| c.is_delete == 0 && c.id}
    user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id}
    # user_org_ids = User.current.organizations.map {|o| o.id}
    if (params[:type].blank? || params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      if params[:status] == "2"
        @attachments = get_course_resources(User.current.id, user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources(User.current.id, user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources(User.current.id, @order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources(User.current.id, @order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_my_resources(User.current.id, user_course_ids, user_project_ids, @order, @score)
      end
    elsif (params[:type] == "6") # 公共资源
      if params[:status] == "2"
        @attachments = get_course_resources_public(user_course_ids, @order, @score)
      elsif params[:status] == "3"
        @attachments = get_project_resources_public(user_project_ids, @order, @score)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_public(@order, @score)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_public(@order, @score)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_public_resources(user_course_ids, user_project_ids, params[:order], @score)
      end
      # elsif params[:type] == "2" # 私有资源
      #   apply_ids = ApplyResource.where("user_id =? and status =?", params[:id], 2).map { |ar| ar.attachment_id}
      #   if params[:status] == "2"
      #     resource_type = "'Course'"
      #   elsif params[:status] == "3"
      #     resource_type = "'Project'"
      #   elsif params[:status] == "5"
      #     resource_type = "'Principal'"
      #   else
      #     resource_type = "'Project','OrgSubfield','Principal','Course'"
      #   end
      #   @attachments = get_my_private_resources(apply_ids, resource_type, @order, @score)
    end
    @status = params[:status]
    @type = params[:type]
    @limit = 25
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 25
    respond_to do |format|
      format.js
      format.html {render :layout => 'new_base'}
    end
  end


  # 导入资源
  def import_resources
    @resource_id = params[:project_id].nil? ? (params[:course_id].nil? ? params[:subfield_file_id] : params[:course_id]) : params[:project_id]
    @resource_type = params[:project_id].nil? ? (params[:course_id].nil? ? "SubfieldFile" : "Course") : "Project"
    @order, @b_sort = params[:order] || "attachments.created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    @search = params[:name].nil? ? "" : params[:name]
    switch_search = "%#{@search.strip.downcase}%"
    user_course_ids = User.current.courses.map {|c| c.is_delete == 0 && c.id}
    user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id} # user_org_ids = User.current.organizations.map {|o| o.id}
    if (params[:type].blank? || params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      @attachments = get_my_resources_search(User.current.id, user_course_ids, user_project_ids, @order, @score, switch_search)
    elsif params[:type] == "6" # 公共资源
      # 公共资源库:所有公开资源或者我上传的私有资源
      @attachments = get_public_resources_search(user_course_ids, user_project_ids, params[:order], @score, switch_search)
    end
    @status = params[:status]
    @type = params[:type]
    @limit = 10
    @page = params['page'] || 1
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, @page
    @total_pages = (@atta_count / 10.0).ceil
    # @offset ||= @atta_pages.offset
    # @curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 10
    respond_to do |format|
      format.js
      format.html {render :layout => 'new_base'}
      format.json {
        render json: resource_json_data(@attachments)
      }
    end
  end

  def import_resources_search
    @resource_id = params[:mul_id]
    @resource_type = params[:mul_type]
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "asc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    @user = User.current
    @switch_search = params[:name].nil? ? " " : params[:name]
    search = "%#{@switch_search.strip.downcase}%"
    # 别人的资源库是没有权限去看的
    if (params[:type].blank? || params[:type] == "1") # 我的资源
      # 修正:我的资源库的话,那么应该是我上传的所有资源加上,我加入的课程、项目、组织的所有资源
      user_course_ids = User.current.courses.map {|c| c.is_delete == 0 && c.id}
      user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id}
      # user_org_ids = User.current.organizations.map {|o| o.id}
      @attachments = get_my_resources_search(User.current.id, user_course_ids, user_project_ids, @order, @score, search)
    elsif params[:type] == "6" # 公共资源
      # 公共资源库:所有公开资源或者我上传的私有资源
      @attachments = get_public_resources_search(user_course_ids, user_project_ids, @order, @score, search)
    end
    @type = params[:type]
    @limit = 10
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 10
    respond_to do |format|
      format.js
      # format.html {render :layout => 'new_base'}
    end
  end

  # 内容导入到对象中
  def import_into_container
    send_ids = params[:import_resource]
    # mul_id为当前课程id、项目id、组织id的多种形态
    mul_id = params[:mul_id]
    if params[:mul_type] == "Course"
      mul_container = Course.find(mul_id)
    elsif params[:mul_type] == "Project"
      mul_container = Project.find(mul_id)
    elsif params[:mul_type] == "SubfieldFile"
      mul_container = OrgSubfield.find(mul_id)
    end
    unless params[:import_resource].blank?
      send_ids.each do |send_id|
        ori = Attachment.find_by_id(send_id)
        # 如果该附件已经存课程中,则只更新附件创建时间
        mul_container.attachments.each do |att|
          @exist = false
          if att.id == ori.id || (!att.copy_from.nil? && !ori.copy_from.nil? && att.copy_from == ori.copy_from) || att.copy_from == ori.id || att.id == ori.copy_from
            att.created_on = Time.now
            att.save
            @exist = true
            break
          end
        end
        next if @exist
        attach_copied_obj = ori.copy
        attach_copied_obj.tag_list.add(ori.tag_list) # tag关联
        attach_copied_obj.container = mul_container
        attach_copied_obj.created_on = Time.now
        attach_copied_obj.author_id = User.current.id
        attach_copied_obj.is_public = 0
        attach_copied_obj.copy_from = ori.copy_from.nil? ? ori.id : ori.copy_from #发送要添加copy_from
        if attach_copied_obj.attachtype == nil
          attach_copied_obj.attachtype = 4
        end
        attach_copied_obj.save
        # 附件保存成功后更新项目和课程的统计数
        if params[:mul_type] == "Project"
          mul_container.project_score.update_attribute(:attach_num, mul_container.project_score.attach_num + 1) unless mul_container.project_score.nil?
        end
        @save_message = attach_copied_obj.errors.full_messages
      end
    end
    respond_to do |format|
      format.html {
        if params[:mul_type] == "Course"
          redirect_to course_files_url(mul_container) unless mul_container.nil?
        elsif params[:mul_type] == "Project"
          redirect_to project_files_url(mul_container) unless mul_container.nil?
        elsif params[:mul_type] == "SubfieldFile"
          redirect_to org_subfield_files_url(mul_container) unless mul_container.nil?
        end
      }
    end
  end

  # 根据资源关键字进行搜索
  def resource_search
    @order, @b_sort = params[:order] || "created_on", params[:sort] || "desc"
    @score = @b_sort == "desc" ? "asc" : "desc"
    @user = User.current
    @switch_search = params[:search].nil? ? " " : params[:search]
    search = "%#{@switch_search.strip.downcase}%"
    user_course_ids = User.current.courses.map {|c| c.is_delete == 0 && c.id}
    user_project_ids = User.current.projects.map {|p| p.status != 9 && p.id}
    if (params[:type].nil? || params[:type].blank? || params[:type] == "1" || params[:type] == 'all') # 全部
      if params[:status] == "2"
        @attachments = get_course_resources_search(User.current.id, user_course_ids, @order, @score, search)
      elsif params[:status] == "3"
        @attachments = get_project_resources_search(User.current.id, user_project_ids, @order, @score, search)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_search(User.current.id, @order, @score, search)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_search(User.current.id, @order, @score, search)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_my_resources_search(User.current.id, user_course_ids, user_project_ids, @order, @score, search)
      end
    elsif params[:type] == "6" # 公共资源
      if params[:status] == "2"
        @attachments = get_course_resources_public_search(user_course_ids, @order, @score, search)
      elsif params[:status] == "3"
        @attachments = get_project_resources_public_search(user_project_ids, @order, @score, search)
      elsif params[:status] == "4"
        @attachments = get_attch_resources_public_search(@order, @score, search)
      elsif params[:status] == "5"
        @attachments = get_principal_resources_public_search(@order, @score, search)
      else
        # 公共资源库:所有公开资源或者我上传的私有资源
        @attachments = get_public_resources_search(user_course_ids, user_project_ids, @order, @score, search)
      end
      # elsif params[:type] == "2" # 私有资源
      #   apply_ids = ApplyResource.where("user_id =? and status =?", params[:id], 2).map { |ar| ar.attachment_id}
      #   if params[:status] == "2"
      #     resource_type = "'Course'"
      #   elsif params[:status] == "3"
      #     resource_type = "'Project'"
      #   elsif params[:status] == "5"
      #     resource_type = "'Principal'"
      #   else
      #     resource_type = "'Project','OrgSubfield','Principal','Course'"
      #   end
      #   @attachments = get_my_private_resources_search(apply_ids, resource_type, @order, @score, search)
      #   @attachments
    end
    @status = params[:status]
    @type = params[:type]
    @limit = 25
    @is_remote = true
    @atta_count = @attachments.count
    @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    @offset ||= @atta_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @attachments = paginateHelper @attachments, 25
    respond_to do |format|
      format.js
    end
  end

  def user_organizations
    @user = User.current
    @orgs = @user.organizations
    respond_to do |format|
      format.html {render :layout => 'static_base'}
    end
  end

  def search_user_orgs
    name = ""
    if !params[:search_orgs].nil?
      name = params[:search_orgs].strip
    end
    name = "%" + name + "%"
    @orgs = User.current.organizations.where("name like ?", name)
    @user = User.current
    @type = params[:type]
    respond_to do |format|
      format.html {render :layout => 'static_base'}
      format.js
    end
  end

  def search_user_org
    @user = User.current
    if !params[:search].nil? #发送到有栏目类型为资源的组织中
      search = "%#{params[:search].to_s.strip.downcase}%"
      if params[:send_type].present? and (params[:send_type] == 'news' or params[:send_type] == 'message')
        @orgs = @user.organizations.where("name like ?", search).select {|org| OrgSubfield.where("organization_id = #{org.id} and field_type='Post'").count > 0}
      else
        @orgs = @user.organizations.where("name like ?", search).select {|org| OrgSubfield.where("organization_id = #{org.id} and field_type='Resource'").count > 0}
      end
    else
      if params[:send_type].present? and (params[:send_type] == 'news' or params[:send_type] == 'message')
        @orgs = @user.organizations.select {|org| OrgSubfield.where("organization_id = #{org.id} and field_type='Post'").count > 0}
      else
        @orgs = @user.organizations.select {|org| OrgSubfield.where("organization_id = #{org.id} and field_type='Resource'").count > 0}
      end
    end
    @type = params[:type]
    @search = params[:search]
    #这里仅仅是传递需要发送的资源id
    @send_id = params[:send_id]
    @send_ids = params[:checkbox1] || params[:send_ids]
    @hidden_unproject = hidden_unproject_infos
    respond_to do |format|
      format.js
    end
  end

  def user_courselist
    @user_courselist = "课程"
    @order, @c_sort, @type, @list_type = 1, 2, 1, 1

    @my_syllabuses = @user.syllabuses

    if @user == User.current
      archive_ids = Course.where("tea_id = #{@user.id} and is_delete = 1 and syllabus_id is NOT NULL").blank? ? "(-1)" : "(" + Course.where("tea_id = #{@user.id} and is_delete = 1 and syllabus_id is NOT NULL").map {|course| course.syllabus_id}.join(",") + ")"
      @archive_syllabuses = Syllabus.where("id in #{archive_ids}")
    end

    sy_courses = @user.courses.visible.not_deleted
    syllabus_ids = sy_courses.empty? ? '(-1)' : "(" + sy_courses.map {|course| !course.syllabus_id.nil? && course.syllabus_id}.join(",") + ")"
    syllabus_members = SyllabusMember.where("user_id = #{@user.id}")
    syllabus_member_ids = syllabus_members.empty? ? "(-1)" : "(" + syllabus_members.map {|syl_mem| syl_mem.syllabus_id}.join(',') + ")"
    @join_syllabuses = Syllabus.where("(id in #{syllabus_ids} or id in #{syllabus_member_ids}) and user_id != #{@user.id}")

    @my_syllabuses = syllabus_course_list_sort @my_syllabuses
    @join_syllabuses = syllabus_course_list_sort @join_syllabuses
    @my_syllabuses = @my_syllabuses.sort {|x, y| y[:last_update] <=> x[:last_update]}
    @join_syllabuses = @join_syllabuses.sort {|x, y| y[:last_update] <=> x[:last_update]}
    @is_course = 1

    #分页
    # @limit = 10
    # @is_remote = true
    # @atta_count = @syllabus.count
    # @atta_pages = Paginator.new @atta_count, @limit, params['page'] || 1
    # @offset ||= @atta_pages.offset
    # @syllabus = paginateHelper @syllabus,@limit

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

  #课程列表的排序
  def sort_syllabus_list
    @order, @c_sort, @type, @list_type = params[:order] || 1, params[:sort] || 1, params[:type] || 1, params[:list_type] || 1

    #确定 sort_type
    if @order.to_i == @type.to_i
      @c_sort = @c_sort.to_i == 1 ? 2 : 1 #1升序 2降序
    else
      @c_sort = 2
    end

    sort_name = "updated_at"

    if @list_type.to_i == 1
      @syllabuses = @user.syllabuses.order("updated_at desc")
    else
      sy_courses = @user.courses.visible.where("is_delete =? and tea_id != ?", 0, @user.id)
      syllabus_ids = sy_courses.empty? ? '(-1)' : "(" + sy_courses.map {|course| !course.syllabus_id.nil? && course.syllabus_id}.join(",") + ")"
      @syllabuses = Syllabus.where("id in #{syllabus_ids} and user_id != #{@user.id}").order("updated_at desc")
    end

    if @order.to_i == 1 #根据 班级更新时间排序
      @syllabuses = syllabus_course_list_sort @syllabuses
      @c_sort == 1 ? (@syllabuses = @syllabuses.sort {|x, y| x[:last_update] <=> y[:last_update]}) : (@syllabuses = @syllabuses.sort {|x, y| y[:last_update] <=> x[:last_update]})
      @type = 1
    elsif @order.to_i == 2 #根据 作业+资源数排序
      @type = 2
      @syllabuses.each do |syllabus|
        count = 0
        courses = syllabus.courses.not_deleted
        courses.each do |c|
          count += (User.current.admin? || User.current.allowed_to?(:as_teacher, c)) ? (c.homework_commons.count + visable_attachemnts_incourse(c).count) : (c.homework_commons.where("publish_time <= '#{Time.now}'").count + visable_attachemnts_incourse(c).count)
        end
        syllabus[:infocount] = count
      end
      @c_sort == 1 ? (@syllabuses = @syllabuses.sort {|x, y| x[:infocount] <=> y[:infocount]}) : (@syllabuses = @syllabuses.sort {|x, y| y[:infocount] <=> x[:infocount]})
      @syllabuses = sortby_time_countcommon_nosticky @syllabuses, sort_name
    else
      @type = 1
    end

    respond_to do |format|
      format.js
    end
  end

  # 归档班级列表
  def user_archive_courses
    if User.current.logged?
      @order, @c_sort, @type = params[:order] || 1, params[:sort] || 1, params[:type] || 1

      #确定 sort_type
      if @order.to_i == @type.to_i
        @c_sort = @c_sort.to_i == 1 ? 2 : 1 #1升序 2降序
      else
        @c_sort = 2
      end

      @user = User.current
      sort_name = "updated_at"
      archive_ids = Course.where("tea_id = #{@user.id} and is_delete = 1 and syllabus_id is NOT NULL").blank? ? "(-1)" : "(" + Course.where("tea_id = #{@user.id} and is_delete = 1 and syllabus_id is NOT NULL").map {|course| course.syllabus_id}.join(",") + ")"
      @archive_syllabuses = Syllabus.where("id in #{archive_ids}")

      if @order.to_i == 1 #根据 班级更新时间排序
        @archive_syllabuses = syllabus_course_list_sort @archive_syllabuses
        @c_sort == 1 ? (@archive_syllabuses = @archive_syllabuses.sort {|x, y| x[:last_update] <=> y[:last_update]}) : (@archive_syllabuses = @archive_syllabuses.sort {|x, y| y[:last_update] <=> x[:last_update]})
        @type = 1
      elsif @order.to_i == 2 #根据 作业+资源数排序
        @type = 2
        @archive_syllabuses.each do |syllabus|
          count = 0
          courses = syllabus.courses.not_deleted
          courses.each do |c|
            count += (User.current.admin? || User.current.allowed_to?(:as_teacher, c)) ? (c.homework_commons.count + visable_attachemnts_incourse(c).count) : (c.homework_commons.where("publish_time <= '#{Date.today}'").count + visable_attachemnts_incourse(c).count)
          end
          syllabus[:infocount] = count
        end
        @c_sort == 1 ? (@archive_syllabuses = @archive_syllabuses.sort {|x, y| x[:infocount] <=> y[:infocount]}) : (@archive_syllabuses = @archive_syllabuses.sort {|x, y| y[:infocount] <=> x[:infocount]})
        @archive_syllabuses = sortby_time_countcommon_nosticky @archive_syllabuses, sort_name
      else
        @type = 1
      end
      respond_to do |format|
        format.js
        format.html {render :layout => 'base_course_community'}
      end
    end
  end

  # 展开课程下的班级
  def expand_courses
    @syllabus = Syllabus.where("id = #{params[:syllabus_id]}").first
    unless @syllabus.nil?
      if params[:is_delete] && params[:is_delete] == '1'
        @courses = @syllabus.courses.where("is_delete = 1").select("courses.*,(SELECT MAX(updated_at)  FROM `course_activities` WHERE course_activities.course_id = courses.id) AS updatetime").order("updatetime desc")
      else
        @courses = @syllabus.courses.not_deleted.select("courses.*,(SELECT MAX(updated_at)  FROM `course_activities` WHERE course_activities.course_id = courses.id) AS updatetime").order("updatetime desc")
      end
      respond_to do |format|
        format.js
      end
    end
  end

  # 收藏班级/项目/竞赛
  def cancel_or_collect
    if params[:project]
      @project = Project.find params[:project]
      member = Member.where("user_id = #{@user.id} and project_id = #{@project.id}")
    elsif params[:course]
      @course = Course.find params[:course]
      member = Member.where("user_id = #{@user.id} and course_id = #{@course.id}")
    elsif params[:contest]
      @contest = Contest.find params[:contest]
      member = ContestMember.where("user_id = #{@user.id} and contest_id = #{@contest.id}")
    end
    if !member.empty? && params[:contest]
      member.first.update_attribute(:is_collect, member.first.is_collect == false ? 1 : 0)
    elsif !member.empty?
      member.first.update_attribute(:is_collect, member.first.is_collect == 0 ? 1 : 0)
    end
    if @project
      @projects = @user.favorite_projects.visible.select("projects.*, (SELECT MAX(updated_at)  FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS a").order("a desc").limit(10)
    elsif @course
      @courses = @user.favorite_courses.visible.where("is_delete =?", 0).select("courses.*,(SELECT MAX(updated_at)  FROM `course_activities` WHERE course_activities.course_id = courses.id) AS a").order("a desc").limit(10)
    elsif @contest
      @contests = @user.favorite_contests.visible.where("is_delete =?", 0).select("contests.*,(SELECT MAX(updated_at)  FROM `contest_activities` WHERE contest_activities.contest_id = contests.id) AS a").order("a desc").limit(10)
    end
    respond_to do |format|
      format.js
    end
  end

  # 用户竞赛列表
  def user_contestlist
    # 我创建的竞赛
    @contest_community = "竞赛"
    @my_contests = @user.contests.where(:user_id => @user.id).order("created_at desc")
    @my_contests_count = @my_contests.count
    # 我参与的竞赛
    my_all_contests = @user.contest_members.where(:user_id => @user.id).blank? ? "(-1)" : "(" + @user.contest_members.where(:user_id => @user.id).map {|cm| cm.contest_id}.join(",") + ")"
    @my_joined_contests = Contest.where("id in #{my_all_contests} and user_id != #{@user.id}").order("created_at desc")
    @my_joined_contests_count = @my_joined_contests.count
    respond_to do |format|
      format.html {render :layout => 'base_contest_community'}
    end
  end

  def user_projectlist
    @user_projectlist = "项目"
    @order, @c_sort, @type, @list_type = 1, 2, 1, 1
    #limit = 5

    # 用户的所有项目
    # @my_projects = @user.projects.visible.where("projects.user_id = #{@user.id}").select("projects.*,(SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS updatetime").order("updatetime DESC")
    @my_projects = @user.projects.where("projects.user_id = #{@user.id}").select("projects.*,(SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS updatetime").order("updatetime DESC")
    @my_projects_count = @my_projects.count

    #@my_joined_projects = @user.projects.visible.where("projects.user_id != #{@user.id}").select("projects.*,(SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS updatetime").order("updatetime DESC")
    @my_joined_projects = @user.projects.where("projects.user_id != #{@user.id}").select("projects.*,(SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS updatetime").order("updatetime DESC")
    @my_joined_projects_count = @my_joined_projects.count

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

  def sort_project_list
    @order, @c_sort, @type, @list_type = params[:order] || 1, params[:sort] || 1, params[:type] || 1, params[:list_type] || 1
    #limit = 5

    #确定 sort_type
    if @order.to_i == @type.to_i
      @c_sort = @c_sort.to_i == 1 ? 2 : 1 #1升序 2降序
    else
      @c_sort = 2
    end

    sort_name = "updatetime"
    sort_type = @c_sort == 1 ? "asc" : "desc"

    #@projects = @user.projects.visible.order("#{sort_name} #{sort_type}")
    if @list_type.to_i == 1
      @projects = @user.projects.visible.where("projects.user_id = #{@user.id}").select("projects.*,(SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS #{sort_name}").order("#{sort_name} #{sort_type}")
    else
      @projects = @user.projects.visible.where("projects.user_id != #{@user.id}").select("projects.*,(SELECT MAX(updated_at) FROM `forge_activities` WHERE forge_activities.project_id = projects.id) AS #{sort_name}").order("#{sort_name} #{sort_type}")
    end
    @projects_count = @projects.count

    #根据 问题+资源数排序 @project.project_score.issue_num @project.project_score.attach_num
    if @order.to_i == 2
      @type = 2
      @projects.each do |project|
        project[:infocount] = project.project_score.issue_num + project.project_score.attach_num
        if project[:infocount] < 0
          project[:infocount] = 0
        end
      end
      @c_sort == 1 ? (@projects = @projects.sort {|x, y| x[:infocount] <=> y[:infocount]}) : (@projects = @projects.sort {|x, y| y[:infocount] <=> x[:infocount]})
      @projects = sortby_time_countcommon_nosticky @projects, sort_name
    else
      @type = 1
    end

    respond_to do |format|
      format.js
    end
  end

  def all_journals
    if params[:type].present?
      case params[:type]
        when 'OrgDocumentComment'
          @user_activity_id = params[:div_id].to_i if params[:div_id]
          @type = 'OrgDocumentComment'
          @journals = OrgDocumentComment.where("root_id = #{params[:id].to_i}").reorder("created_at desc")
        when 'Message', 'is_project_message'
          @type = 'Message'
          @user_activity_id = params[:div_id].to_i if params[:div_id]
          @journals = Message.where("root_id = #{params[:id].to_i}").reorder("created_on desc")
        when 'News'
          obj = News.where('id = ?', params[:id].to_i).first
          @journals = obj.comments.reorder("created_on desc")
          @type = 'News'
          @user_activity_id = params[:div_id].to_i if params[:div_id]
        when 'Syllabus'
          obj = Syllabus.where('id = ?', params[:id].to_i).first
          @journals = obj.journals_for_messages.reorder("created_on desc")
          @type = 'Syllabus'
          @user_activity_id = params[:div_id].to_i if params[:div_id]
        when 'JournalsForMessage'
          @journals = JournalsForMessage.where("root_id = #{params[:id].to_i}").reorder("created_on desc")
          @type = 'JournalsForMessage'
          @user_activity_id = params[:div_id].to_i if params[:div_id]
        when 'Issue'
          obj = Issue.where('id = ?', params[:id].to_i).first
          @journals = obj.journals.reorder("created_on desc")
          @type = 'Issue'
          @user_activity_id = params[:div_id].to_i if params[:div_id]
        when 'is_project_issue'
          @activity = Issue.where('id = ?', params[:id].to_i).first
          @journals = @activity.journals.reorder("created_on desc")
          @user_activity_id = params[:div_id].to_i if params[:div_id]
          @user_activity = ForgeActivity.where(params[:div_id].to_i).first if params[:div_id]
        when 'is_project_training_task'
          @activity = TrainingTask.where('id = ?', params[:id].to_i).first
          @journals = @activity.journals.reorder("created_on desc")
          @user_activity_id = params[:div_id].to_i if params[:div_id]
          @user_activity = ForgeActivity.where(params[:div_id].to_i).first if params[:div_id]
        when 'BlogComment'
          obj = BlogComment.where('id = ?', params[:id].to_i).first
          @user_activity_id = params[:div_id].to_i if params[:div_id]
          @type = 'BlogComment'
          @journals = BlogComment.where("root_id = #{params[:id].to_i}").reorder("created_on desc")
        when 'HomeworkCommon'
          obj = HomeworkCommon.where('id = ?', params[:id].to_i).first
          @type = 'HomeworkCommon'
          @journals = obj.journals_for_messages.reorder("created_on desc")
          @is_teacher = User.current.allowed_to?(:as_teacher, obj.course)
          @user_activity_id = params[:user_activity_id].to_i if params[:user_activity_id]
        when 'Work'
          obj = Work.where('id = ?', params[:id].to_i).first
          @type = 'Work'
          @journals = obj.journals_for_messages.reorder("created_on desc")
          @is_teacher = User.current.admin_of_contest?(obj.contest)
          @user_activity_id = params[:user_activity_id].to_i if params[:user_activity_id]
      end
    end
    @journals = get_no_children_comments_all @journals
  end

  def homepage
    @article = @user.base_homepage
    respond_to do |format|
      format.html {render :layout => 'clear_base'}
    end
  end

  # 邮件激活页面,用户修改邮件地址弹框
  def change_user_email
    @user = User.find params[:id]
  end

  private
  def show_system_message
    # 系统消息总显示在最前面,显示周期30天
    @system_messages = SystemMessage.where("created_at > ?", Time.now - 86400 * 30)
  end

  def find_user
    begin
      if params[:id] == 'current'
        require_login || return
        @user = User.current
      else
        logger.info("################{params}")
        @user = User.find_by_login(params[:id])
        # 解决登录名为纯数字的问题
        @user = User.find(params[:id]) if @user.nil?
      end
    rescue ActiveRecord::RecordNotFound
      render_404
    end
  end

  def setting_layout(default_base = 'base_users_new')
    User.current.admin? ? default_base : default_base
  end

  # 必填自己的工作单位,其实就是学校
  def auth_user_extension
    if @user == User.current && @user.user_extensions.nil?
      flash[:error] = l(:error_complete_occupation)
      redirect_to my_account_url
    end
  end

  #重置用户得分
  def rest_user_score
    memo_num(@user)
    messges_for_issue_num(@user)
    issues_status_num(@user)
    replay_for_memo_num(@user)
    tread_num(@user)
    praise_num(@user)
    changeset_num(@user)
    document_num(@user)
    attachment_num(@user)
    issue_done_ratio_num(@user)
    post_issue_num(@user)
  end

  #验证是否显示课程
  def can_show_course
    @first_page = FirstPage.find_by_page_type('project')
    if @first_page.show_course == 2
      render_404
    end
  end

  def recorded_visitor
    if (User.current.logged? && User.current != @user)
      #impl = Visitor.where('user_id=? and master_id=?',User.current.id,@user.id).find;
      # impl = Visitor.find_by_sql('user_id=? and master_id=?',[User.current.id,@user.id]);
      impl = Visitor.find_by_user_id_and_master_id(User.current.id, @user.id);
      if (impl.nil?)
        impl = Visitor.new
        impl.user_id = User.current.id
        impl.master_id = @user.id
      else
        impl.updated_on = Time.now
      end
      impl.save
    end
  end


end