#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 FilesController < ApplicationController
  layout 'base_projects' #by young

  menu_item :files
  # before_filter :check_authentication, :except => []
  # before_filter :auth_login1, :only => [:index]
  # before_filter :logged_user_by_apptoken,:only => [:index]
  before_filter :find_project_by_project_id#, :except => [:getattachtype]
  # before_filter :authorize, :except => [:create,:getattachtype,:quote_resource_show,:search,:searchone4reload,:search_project,:quote_resource_show_project,
  #                                       :search_tag_attachment,:subfield_upload_file,:search_org_subfield_tag_attachment,
  #                                       :search_tag_attachment,:quote_resource_show_org_subfield,:find_org_subfield_attache,
  #                                       :search_files_in_subfield,:upload_files_menu,:setting,:republish_file,:update_file_description, :edit_file_description]

  helper :sort
  include SortHelper
  include FilesHelper
  helper :project_score
  include CoursesHelper
  include ApplicationHelper

  def show_attachments obj
    if obj.first.class.to_s == "Course"
      @attachments = obj.first.attachments
      if User.current.admin? || User.current.allowed_to?(:as_teacher,obj.first)
        @all_attachments = @attachments.reorder("created_on desc")
      elsif User.current.member_of_course?(@course)
        member = @course.members.where(:user_id => User.current.id).first
        if member.try(:course_group_id).to_i == 0
          @all_attachments = @attachments.where("is_publish = 1 and unified_setting = 1").reorder("created_on desc")
        else
          not_atta_ids = @course.attachment_group_settings.where("course_group_id = #{member.try(:course_group_id)} and publish_time > '#{Time.now}'")
          not_atta_ids = not_atta_ids.blank? ? "(-1)" : "(" + not_atta_ids.map(&:attachment_id).join(",") + ")"
          @all_attachments = @attachments.where("is_publish = 1 and attachments.id not in #{not_atta_ids}").reorder("created_on desc")
        end
      else
        @all_attachments = @attachments.where("is_publish = 1 and unified_setting = 1").reorder("created_on desc")
      end
    else
      @attachments = []
      obj.each do |container|
        @attachments += container.attachments
      end
      @all_attachments = User.current.admin? ? @attachments : visable_attachemnts(@attachments)
    end
    @limit = 10
    @feedback_count = @all_attachments.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @obj_attachments = paginateHelper @all_attachments,10
  end

  def searchone4reload
    attachment = Attachment.find_by_id(params[:fileid])
    respond_to do |format|
      format.html{render :layout => nil,:locals=>{:file=>attachment,:course=>@course}}
    end
  end

  def search
    sort = ""
    @sort = ""
    @order = ""
    @is_remote = true
    @q = params[:name].strip
    if params[:sort]
      order_by = params[:sort].split(":")
      @sort = order_by[0]
      if order_by.count > 1
        @order = order_by[1]
      end
      sort = "#{@sort} #{@order}"
    end
    # show_attachments [@course]
    begin
      q = "%#{params[:name].strip}%"
      #(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
      # if params[:insite]
      #   if q == "%%"
      #     @result = []
      #     # @searched_attach = paginateHelper @result,10
      #   else
      #     @result = find_public_attache q,sort
      #     @result = visable_attachemnts_insite @result,@course
      #     # @searched_attach = paginateHelper @result,10
      #   end
      # else
        @result = find_course_attache q,@course,sort
        @result = visable_attachemnts @result
        # @searched_attach = paginateHelper @result,10
        #@tag_list = get_course_tag_list @course
      #end
      @all_attachments = @result
      get_attachment_for_tip(@all_attachments)
      @limit = 10
      @feedback_count = @all_attachments.count
      @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
      @offset ||= @feedback_pages.offset
      #@curse_attachments_all = @all_attachments[@offset, @limit]
      @obj_attachments = paginateHelper @all_attachments,10
      #rescue Exception => e
      #  #render 'stores'
      #  redirect_to search_course_files_url
    end
  end

  def setting
    @file = Attachment.find params[:id]
    @attachment = @file
    @attachment_histories = @file.attachment_histories
    @course = Course.find params[:course_id]
    respond_to do |format|
      format.js
    end
  end

  def republish_file
    @file = Attachment.find params[:id]
    @course = Course.find params[:course_id]
    if params[:publish_time]
      unless params[:publish_time] == ""
        @file.publish_time = params[:publish_time]
      end
    end
    if @file.publish_time > Time.now
      @file.is_publish = 0
    else
      @file.is_publish = 1
    end
    if @file.is_public == 0 && params[:is_public]
      @file.is_public = 1
    end
    @file.save
    respond_to do |format|
      format.js
    end
  end

  def search_project
    sort = ""
    @sort = ""
    @order = ""
    @is_remote = true
    @q = params[:name].strip
    if params[:sort]
      order_by = params[:sort].split(":")
      @sort = order_by[0]
      if order_by.count > 1
        @order = order_by[1]
      end
      sort = "#{@sort} #{@order}"
    end
    # show_attachments [@course]
    begin
      q = "%#{params[:name].strip}%"
      #(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
      if params[:insite]
        if q == "%%"
          @project_attachment_result = []
          # @searched_attach = paginateHelper @project_attachment_result, 10
        else
          @project_attachment_result = find_public_attache q,sort
          @project_attachment_result = visable_attachemnts_insite  @project_attachment_result, @project
          # @searched_attach = paginateHelper @project_attachment_result, 10
        end
      else
        @project_attachment_result = find_project_attache q, @project,sort
        @project_attachment_result = visable_attachemnts @project_attachment_result
        # @searched_attach = paginateHelper @project_attachment_result,10
        @tag_list = get_project_tag_list @project
      end

      @all_attachments = @project_attachment_result
      get_attachment_for_tip(@all_attachments)
      @limit = 10
      @feedback_count = @all_attachments.count
      @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
      @offset ||= @feedback_pages.offset
      #@curse_attachments_all = @all_attachments[@offset, @limit]
      @obj_attachments = paginateHelper @all_attachments,10
      #rescue Exception => e
      #  #render 'stores'
      #  redirect_to search_course_files_url
    end
  end

  def search_files_in_subfield
    sort = ""
    @sort = ""
    @order = ""
    @is_remote = true
    @q = params[:name].strip
    if params[:sort]
      order_by = params[:sort].split(":")
      @sort = order_by[0]
      if order_by.count > 1
        @order = order_by[1]
      end
      sort = "#{@sort} #{@order}"
    end
    # show_attachments [@course]
    begin
      q = "%#{params[:name].strip}%"
      #(redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
      if params[:insite]
        if q == "%%"
          @result = []
          @searched_attach = paginateHelper @result,10
        else
          @result = find_public_attache q,sort
          @result = visable_attachemnts_insite @result,@org_subfield
          @searched_attach = paginateHelper @result,10
        end
      else
        @result = find_org_subfield_attache q,@org_subfield,sort
        @result = visable_attachemnts @result
        @searched_attach = paginateHelper @result,10
        @tag_list = attachment_tag_list @result
      end
      #rescue Exception => e
      #  #render 'stores'
      #  redirect_to search_course_files_url
    end
    @page = params[:page] || 1
  end

  def find_course_attache keywords,course,sort = ""
    if sort == ""
      sort =  "created_on DESC"
    end
    if keywords != "%%"
      resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' AND (filename LIKE '#{keywords}' or description LIKE '#{keywords}')").reorder(sort)
    else
      resultSet = Attachment.where("attachments.container_type = 'Course' And attachments.container_id = '#{course.id}' ").reorder(sort)
    end
    #resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC")
  end

  def find_org_subfield_attache keywords,org_subfield,sort = ""
    if sort == ""
      sort =  "created_on DESC"
    end
    if keywords != "%%"
      resultSet = Attachment.where("attachments.container_type = 'OrgSubfield' And attachments.container_id = '#{org_subfield.id}' AND filename LIKE :like ", like: "%#{keywords}%").
          reorder(sort)
    else
      resultSet = Attachment.where("attachments.container_type = 'OrgSubfield' And attachments.container_id = '#{org_subfield.id}' "). reorder(sort)
    end
    #resultSet = Attachment.find_by_sql("SELECT `attachments`.* FROM `attachments` LEFT OUTER JOIN `homework_attaches` ON `attachments`.container_type = 'HomeworkAttach' AND `attachments`.container_id = `homework_attaches`.id LEFT OUTER JOIN `homework_for_courses` ON `homework_attaches`.bid_id = `homework_for_courses`.bid_id LEFT OUTER JOIN `homework_for_courses` AS H_C ON `attachments`.container_type = 'Bid' AND `attachments`.container_id = H_C.bid_id WHERE (`homework_for_courses`.course_id = 117 OR H_C.course_id = 117 OR (`attachments`.container_type = 'Course' AND `attachments`.container_id = 117)) AND `attachments`.filename LIKE '%#{keywords}%'").reorder("created_on DESC")
  end

  def find_project_attache keywords,project,sort = ""
    if sort == ""
      sort =  "created_on DESC"
    end
    if keywords != "%%"
      resultSet = Attachment.where("attachments.container_type = 'Project' And attachments.container_id = '#{project.id}' AND filename LIKE :like ", like: "%#{keywords}%").reorder(sort)
    else
      resultSet = Attachment.where("attachments.container_type = 'Project' And attachments.container_id = '#{project.id}' "). reorder(sort)
    end
  end

  def find_public_attache keywords,sort = ""
    # StoresController#search 将每条文件都查出来,再次进行判断过滤。---> resultSet.to_a.map
    # 此时内容不多速度还可,但文件增长,每条判断多则进行3-4次表连接。
    # 现在还木有思路 药丸
    if sort == ""
      sort =  "created_on DESC"
    end
    resultSet = Attachment.where("attachments.container_type IS NOT NULL AND attachments.copy_from IS NULL AND filename LIKE :like ", like: "%#{keywords}%").
        reorder(sort)
  end

  def index
    # 顶部导航
    @project_menu_type = 4

    @flag = params[:flag] || false
    sort = ""
    @sort = ""
    @order = ""
    @is_remote = false
    if params[:project_id]
      # 更新资源申请消息为已读
      # ar_ids = ApplyResource.where("user_id =? and container_id =? and container_type =?", User.current.id, params[:project_id].to_i, "Project").map{|ar| ar.id}
      # cms = CourseMessage.where("course_message_type =? and user_id =? and course_message_id in (#{ar_ids.empty? ? '0': ar_ids.join(',')})", "ApplyResource", User.current.id)
      # cms.each do |cm|
      #   cm.update_column(:viewed, true)
      # end
      # over
      @page = params[:page] ? params[:page].to_i + 1 : 2
      @container_type = 0
      if params[:sort]
        params[:sort].split(",").each do |sort_type|
          order_by = sort_type.split(":")
          case order_by[0]
            when "filename"
              attribute = "filename"
            when "size"
              attribute = "filesize"
            when "attach_type"
              attribute = "attachtype"
            when "content_type"
              attribute = "created_on"
            when "field_file_dense"
              attribute = "is_public"
            when "downloads"
              attribute = "downloads"
            when "created_on"
              attribute = "created_on"
            when "quotes"
              attribute = "quotes"
            else
              attribute = "created_on"
          end
          @sort = order_by[0]
          @order = order_by[1]
          if order_by.count == 1 && attribute
            sort += "#{Attachment.table_name}.#{attribute} asc "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          elsif order_by.count == 2 && order_by[1]
            sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          end
        end
      else
        sort = "#{Attachment.table_name}.created_on desc"
      end
      # @containers = [ Project.includes(:attachments).find(@project.id)]
      # @containers += @project.versions.includes(:attachments).all

      @containers = [ Project.includes(:attachments).reorder(sort).find(@project.id)]

      show_attachments @containers
      get_attachment_for_tip(@all_attachments)

      @tag_list = attachment_tag_list @all_attachments

      render :layout => 'base_projects'
    elsif params[:course_id]
      @container_type = 1
      @page = params[:page] ? params[:page].to_i + 1 : 2
      if params[:sort]
        params[:sort].split(",").each do |sort_type|
          order_by = sort_type.split(":")

          case order_by[0]
            when "filename"
              attribute = "filename"
            when "size"
              attribute = "filesize"
            when "attach_type"
              attribute = "attachtype"
            when "content_type"
              attribute = "created_on"
            when "field_file_dense"
              attribute = "is_public"
            when "downloads"
              attribute = "downloads"
            when "created_on"
              attribute = "created_on"
            when "quotes"
              attribute = "quotes"
            else
              attribute = "created_on"
          end
          @sort = order_by[0]
          @order = order_by[1]
          if order_by.count == 1 && attribute
            sort += "#{Attachment.table_name}.#{attribute} asc "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          elsif order_by.count == 2 && order_by[1]
            sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          end
        end
      else
        @sort = "created_on"
        @order = "desc"
        sort = "#{Attachment.table_name}.created_on desc"
      end

      @containers = [ Course.includes(:attachments).reorder(sort).find(@course.id)]

      show_attachments @containers
      get_attachment_for_tip(@all_attachments)

      @tag_list = attachment_tag_list @all_attachments
      # Rails.logger.info("#333tag_list:  #{@tag_list}")
      @is_teacher = User.current.allowed_to?(:as_teacher,@course) || User.current.admin?
      @left_nav_type = 5
      render :layout => 'base_courses'
    elsif params[:org_subfield_id]
      if params[:sort]
        params[:sort].split(",").each do |sort_type|
          order_by = sort_type.split(":")

          case order_by[0]
            when "filename"
              attribute = "filename"
            when "size"
              attribute = "filesize"
            when "attach_type"
              attribute = "attachtype"
            when "content_type"
              attribute = "created_on"
            when "field_file_dense"
              attribute = "is_public"
            when "downloads"
              attribute = "downloads"
            when "created_on"
              attribute = "created_on"
            when "quotes"
              attribute = "quotes"
            else
              attribute = "created_on"
          end
          @sort = order_by[0]
          @order = order_by[1]
          if order_by.count == 1 && attribute
            sort += "#{Attachment.table_name}.#{attribute} asc "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          elsif order_by.count == 2 && order_by[1]
            sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
            if sort_type != params[:sort].split(",").last
              sort += ","
            end
          end
        end
      else
        sort = "#{Attachment.table_name}.created_on desc"
      end
      @container_type = 2
      @containers = [ OrgSubfield.includes(:attachments).reorder(sort).find(@org_subfield.id)]
      @organization = Organization.find(@containers.first.organization_id)
      if @organization.is_public? or User.current.admin? or User.current.member_of_org?(@organization)
        show_attachments @containers
        @tag_list = attachment_tag_list @all_attachments
        @page = params[:page] || 1
        render :layout => 'base_org'
      else
        render_403
      end
      # @subfield = params[:org_subfield_id]
    end

  end

  # 获取提示中私有、公开总数信息
  def get_attachment_for_tip all_attachment

    @tip_all_public_attachments = all_attachment.select{|attach| attach.is_public == 1}.count
    if params[:project_id]
      if User.current.member_of?(@project) || User.current.admin?
        @tip_all_attachments = all_attachment.count
        @tip_all_private_attachments =  all_attachment.select{|attach| attach.is_public == 0}.count
      else
        if params[:tag_name]
          @tip_all_attachments = all_attachment.count
          @tip_all_private_attachments = 0
        else
          @tip_all_attachments = Attachment.where(:container_id => params[:project_id], :container_type => "Project").count
          @tip_all_private_attachments = Attachment.where(:container_id => params[:project_id], :container_type => "Project", :is_public => 0).count
        end
      end
    elsif params[:course_id]
      if User.current.member_of_course?(@course) || User.current.admin?
        @tip_all_attachments = all_attachment.count
        @tip_all_private_attachments =  all_attachment.select{|attach| attach.is_public == 0}.count
      else
        if params[:tag_name]
          @tip_all_attachments = all_attachment.count
          @tip_all_private_attachments = 0
        else
          @tip_all_attachments = Attachment.where(:container_id => params[:course_id], :container_type => "Course").count
          @tip_all_private_attachments = Attachment.where(:container_id => params[:course_id], :container_type => "Course", :is_public => 0).count
        end
      end
    end
  end

  def quote_resource_show
    @file = Attachment.find(params[:id])
    @can_quote = attachment_candown @file
  end

  def quote_resource_show_project
    @file = Attachment.find(params[:id])
    @can_quote = attachment_candown @file
  end

  def quote_resource_show_org_subfield
    @file = Attachment.find(params[:id])
    @org_subfield = OrgSubfield.find(params[:org_subfield_id])
    @can_quote = attachment_candown @file
  end

  def new
    @versions = @project.versions.sort
    @course_tag = @project.project_type
    if @project.project_type == 1
      @left_nav_type = 5
      render :layout => 'base_courses'
    end
  end

  def create
    if params[:add_tag]
      @addTag=true
      #render :back
      tag_saveEx
      #render :text =>"success"
      respond_to do |format|
        format.js
      end
    else
      #modify by nwb
      if @project
        @addTag=false
        if params[:in_project_toolbar]
          @in_project_toolbar =  params[:in_project_toolbar]
        end
        attachments = Attachment.attach_filesex(@project, params[:attachments], params[:attachment_type])
        if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
          # 发送邮件
          # Mailer.run.attachments_added(attachments[:files])
          # 生成动态
          attachments[:files].each do |file|
            ForgeActivity.create(:user_id => User.current.id, :project_id => @project.id, :forge_act_id => file.id, :forge_act_type => "Attachment")
          end
          # 更新资源总数, 根据上传的附件数累加
          @project.project_score.update_attribute(:attach_num, @project.project_score.attach_num + attachments[:files].count) unless @project.project_score.nil?
        end
        # end
        if params[:project_attachment_type] && params[:project_attachment_type].is_a?(Array)
          params[:project_attachment_type].each do |type|
            tag_name = get_project_tag_name_by_type_nmuber type
            if !attachments.empty? && attachments[:files] && tag_name != ""
              attachments[:files].each do |attachment|
                attachment.tag_list.add(tag_name)
                attachment.description = params[:description]
                attachment.save
              end
            end
          end
        else
          if params[:project_attachment_type] && params[:project_attachment_type] != "6"
            tag_name = get_project_tag_name_by_type_nmuber params[:project_attachment_type]
            if !attachments.empty? && attachments[:files] && tag_name != ""
              attachments[:files].each do |attachment|
                attachment.tag_list.add(tag_name)
                attachment.description = params[:description]
                attachment.save
              end
            end
          end
        end
        # TODO: 临时用 nyan
        sort_init 'created_on', 'desc'
        sort_update 'created_on' => "#{Attachment.table_name}.created_on",
                    'filename' => "#{Attachment.table_name}.filename",
                    'size' => "#{Attachment.table_name}.filesize",
                    'downloads' => "#{Attachment.table_name}.downloads"

        @containers = [Project.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@project.id)]
        show_attachments @containers
        @tag_list = attachment_tag_list @all_attachments
        @attachtype = 0
        @contenttype = 0
        respond_to do |format|
          format.js
          format.html {
            redirect_to project_files_url(@project)
          }
        end
      elsif @course
        @addTag=false
        if params[:in_course_toolbar]
          @in_course_toolbar =  params[:in_course_toolbar]
        end
        attachments = Attachment.attach_filesex(@course, params[:attachments], params[:attachment_type])

        # if !attachments.empty? && !attachments[:files].blank? && Setting.notified_events.include?('file_added')
        #   # Mailer.run.attachments_added(attachments[:files])
        # end
        if !attachments.empty? && attachments[:files]
          attachments[:files].each do |attachment|
            attachment.description = params[:description]
            attachment.is_public = params[:is_public] ? 1 : 0
            attachment.save
            if params[:publish_time]
              if params[:publish_time] == ""
                attachment.publish_time = Time.now
              else
                attachment.publish_time = params[:publish_time]
                attachment.is_publish = 0
              end
            else
              attachment.publish_time = Time.now
            end

            if !params[:unified_setting] && params[:attachment_publish_time] && @course.course_groups.count > 1
              attachment.unified_setting = 0
              min_publish_time = ""
              params[:attachment_publish_time].each do |publish_time|
                if publish_time != "" && publish_time < min_publish_time
                  min_publish_time = publish_time
                end
              end
              attachment.is_publish = min_publish_time > (format_time Time.now).to_s ? 0 : 1
              attachment.publish_time = min_publish_time > (format_time Time.now).to_s ? min_publish_time : attachment.created_on

              @course.course_groups.each do |group|
                att_group_setting = AttachmentGroupSetting.create(:attachment_id => attachment.id, :course_group_id => group.id, :course_id => @course.id, :publish_time => attachment.publish_time)
              end
              attachment.attachment_group_settings.joins(:course_group).reorder("course_groups.name asc").each_with_index do |setting, index|
                if params[:attachment_publish_time][index] && params[:attachment_publish_time][index] != ""
                  setting.update_column(:publish_time, params[:attachment_publish_time][index])
                end
              end
            elsif params[:publish_time] && params[:publish_time] != ""
              attachment.publish_time = params[:publish_time]
              attachment.is_publish = 0
            else
              attachment.publish_time = Time.now
            end
            attachment.save

            resource_bank = ResourceBank.create(:course_id => @course.id, :attachment_id => attachment.id, :filename => attachment.filename, :disk_filename => attachment.disk_filename, :filesize => attachment.filesize, :digest => attachment.digest, :downloads => 0,
                                                :user_id => attachment.author_id, :description => attachment.description, :disk_directory => attachment.disk_directory, :is_public => attachment.is_public, :copy_from => attachment.copy_from,
                                                :quotes => 1, :applicable_syllabus => @course.course_list_name, :content_type => attachment.content_type)
            attachment.update_column('resource_bank_id', resource_bank.id)
          end
        end
        if params[:course_attachment_type] && params[:course_attachment_type].is_a?(Array)
          params[:course_attachment_type].each do |type|
            tag_name = get_tag_name_by_type_number type
            if !attachments.empty? && attachments[:files] && tag_name != ""
              attachments[:files].each do |attachment|
                attachment.tag_list.add(tag_name)
                attachment.save
              end
            end
          end
        else
          if params[:course_attachment_type] && params[:course_attachment_type] != "5"
            tag_name = get_tag_name_by_type_number params[:course_attachment_type]
            if !attachments.empty? && attachments[:files] && tag_name != ""
              attachments[:files].each do |attachment|
                attachment.tag_list.add(tag_name)
                attachment.save
              end
            end
          end
        end
        # 更新课程英雄榜得分
        course_member_score(@course.id, attachments[:files].first.author_id, "Attachment")
        # end
        # end
        # TODO: 临时用 nyan
        sort_init 'created_on', 'desc'
        sort_update 'created_on' => "#{Attachment.table_name}.created_on",
                    'filename' => "#{Attachment.table_name}.filename",
                    'size' => "#{Attachment.table_name}.filesize",
                    'downloads' => "#{Attachment.table_name}.downloads"

        @containers = [Course.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@course.id)]

        show_attachments @containers
        @tag_list = attachment_tag_list @all_attachments

        @attachtype = 0
        @contenttype = 0

        respond_to do |format|
          format.js
          format.html {
            redirect_to course_files_url(@course)
          }
        end
      elsif @org_subfield
        @addTag=false
        attachments = Attachment.attach_filesex(@org_subfield, params[:attachments], params[:org_subfield_attachment_type])

        if params[:org_subfield_attachment_type] && params[:org_subfield_attachment_type].is_a?(Array)
          params[:org_subfield_attachment_type].each do |type|
            tag_name = get_tag_name_by_type_number  type
            if !attachments.empty? && attachments[:files] && tag_name != ""
              attachments[:files].each do |attachment|
                attachment.tag_list.add(tag_name)
                attachment.description = params[:description]
                attachment.save
              end
            end
          end
        else
          if params[:org_subfield_attachment_type] && params[:org_subfield_attachment_type] != "5"
            tag_name = get_tag_name_by_type_number  params[:org_subfield_attachment_type]
            if !attachments.empty? && attachments[:files] && tag_name != ""
              attachments[:files].each do |attachment|
                attachment.tag_list.add(tag_name)
                attachment.description = params[:description]
                attachment.save
              end
            end
          end
        end

        # TODO: 临时用 nyan
        sort_init 'created_on', 'desc'
        sort_update 'created_on' => "#{Attachment.table_name}.created_on",
                    'filename' => "#{Attachment.table_name}.filename",
                    'size' => "#{Attachment.table_name}.filesize",
                    'downloads' => "#{Attachment.table_name}.downloads"

        @containers = [OrgSubfield.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@org_subfield.id)]

        show_attachments @containers
        @tag_list = attachment_tag_list @all_attachments
        @attachtype = 0
        @contenttype = 0

        respond_to do |format|
          format.js
          # format.html {
          #   redirect_to org_subfield_files_url(@org_subfield)
          # }
        end
        # 组织添加附件,为了修改图片
      elsif params[:organization_id]
        @organization = Organization.find(params[:organization_id])
        @addTag=false
        # atttchment_type = 0为logo 1为banner
        if params[:logo]
          attachments = Attachment.attach_filesex(@organization, params[:attachments], false)
        else
          attachments = Attachment.attach_filesex(@organization, params[:attachments], true)
        end
        # TODO: 临时用 nyan
        sort_init 'created_on', 'desc'
        sort_update 'created_on' => "#{Attachment.table_name}.created_on",
                    'filename' => "#{Attachment.table_name}.filename",
                    'size' => "#{Attachment.table_name}.filesize",
                    'downloads' => "#{Attachment.table_name}.downloads"

        @containers = [Organization.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@organization.id)]

        show_attachments @containers
        @tag_list = attachment_tag_list @all_attachments
        @attachtype = 0
        @contenttype = 0

        respond_to do |format|
          format.js
          # format.html {
          #   redirect_to org_subfield_files_url(@org_subfield)
          # }
        end
      end
    end
  end

  def get_project_tag_name_by_type_nmuber type
    case type
      when "1"
        tag_name = "软件版本"
      when "2"
        tag_name = "文档"
      when "3"
        tag_name = "代码"
      when "4"
        tag_name = "媒体"
      when "5"
        tag_name = "论文"
      when "6"
        tag_name = "其它"
      else
        tag_name = ""
    end
  end

  def get_tag_name_by_type_number type
    case type
      when "1"
        tag_name = l(:label_courseware)
      when "2"
        tag_name = l(:label_software)
      when "3"
        tag_name = l(:label_media)
      when "4"
        tag_name = l(:label_code)
      when "6"
        tag_name = "论文"
      else
        tag_name = ""
    end
  end

  def tag_saveEx
    @tags = params[:tag_name][:name]
    @obj_id = params[:object_id]
    @obj_flag = params[: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
      ## 执行成功的操作。
    else
      #捕获异常
    end
  end

  # 返回指定资源类型的资源列表
  # added by nwb
  def getattachtype
    sort_init 'created_on', 'desc'
    sort_update   'created_on' => "#{Attachment.table_name}.created_on",
                  'filename' => "#{Attachment.table_name}.filename",
                  'size' => "#{Attachment.table_name}.filesize",
                  'downloads' => "#{Attachment.table_name}.downloads"
    sort=''

    if params[:sort]
      params[:sort].split(",").each do |sort_type|
        order_by = sort_type.split(":")

        case order_by[0]
          when "filename"
            attribute = "filename"
          when "size"
            attribute = "filesize"
          when "attach_type"
            attribute = "attachtype"
          when "content_type"
            attribute = "created_on"
          when "field_file_dense"
            attribute = "is_public"
          when "downloads"
            attribute = "downloads"
          when "created_on"
            attribute = "created_on"
        end

        if order_by.count == 1
          sort += "#{Attachment.table_name}.#{attribute} asc "
        elsif order_by.count == 2
          sort += "#{Attachment.table_name}.#{attribute} #{order_by[1]} "
        end
        if sort_type != params[:sort].split(",").last
          sort += ","
        end
      end
    end

    if @project
      @isproject = true
      @containers = [ Project.includes(:attachments).reorder("#{Attachment.table_name}.created_on DESC").find(@project.id)]
      @containers += @project.versions.includes(:attachments).reorder(sort).all
      show_attachments @containers
      @attachtype = params[:type].to_i
      @contenttype = params[:contentType].to_s
      respond_to do |format|
        format.js
        format.html {
          render :layout => 'base_projects'
        }
      end

    elsif @course
      @isproject = false
      @containers = [ Course.includes(:attachments).reorder(sort).find(@course.id)]
      show_attachments @containers
      @attachtype = params[:type].to_i
      @contenttype = params[:contentType].to_s
      # render layout:  'base_courses'
      @left_nav_type = 5
      respond_to do |format|
        format.js
        format.html {
          render :layout => 'base_courses'
        }
      end
    else
      show_attachments @containers
      @attachtype = params[:type].to_i
      @contenttype = params[:contentType].to_s

      respond_to do |format|
        format.js
        format.html
      end
    end
  end

  #查找指定TAG的按条件过滤的资源列表,只有课程内搜索有此功能
  def search_tag_attachment
    @q,@tag_name,@order = params[:q],params[:tag_name]
    @is_remote = true
    if params[:sort]
      order_by = params[:sort].split(":")
      @sort = order_by[0]
      if order_by.count > 1
        @order = order_by[1]
      end
      sort = "#{@sort} #{@order}"
    else
      @sort = "created_on"
      sort = "created_on desc"
    end

    q = "%#{@q.strip}%"
    if @project
      @result = find_project_attache q, @project,sort
    else
      @result = find_course_attache q,@course,sort
    end
    @result = visable_attachemnts @result
    if params[:other]
      if @project
        @result = @result.select{|attachment| !attachment.tag_list.include?('软件版本') && !attachment.tag_list.include?('文档') && !attachment.tag_list.include?('代码') && !attachment.tag_list.include?('媒体') && !attachment.tag_list.include?('论文')  }
      else
        @result = @result.select{|attachment|
          !attachment.tag_list.include?('课件') &&
              !attachment.tag_list.include?('软件') &&
              !attachment.tag_list.include?('媒体') &&
              !attachment.tag_list.include?('代码') &&
              !attachment.tag_list.include?('论文')  }
      end
    else
      @result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} unless @tag_name.blank?
    end

    @all_attachments = @result
    get_attachment_for_tip(@all_attachments)
    @limit = 10
    @feedback_count = @all_attachments.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    #@curse_attachments_all = @all_attachments[@offset, @limit]
    @obj_attachments = paginateHelper @all_attachments,10


    # @searched_attach = paginateHelper @result,10
    if @project
      @tag_list = get_project_tag_list @project
      @result_search_project = @result
    else
      @tag_list = get_course_tag_list @course
    end
    respond_to do |format|
      format.js
      # format.html
    end
  end

  #搜索资源栏目的指定TAG的资源列表
  def search_org_subfield_tag_attachment
    @q,@tag_name,@order = params[:q],params[:tag_name]
    @is_remote = true
    if params[:sort]
      order_by = params[:sort].split(":")
      @sort = order_by[0]
      if order_by.count > 1
        @order = order_by[1]
      end
      sort = "#{@sort} #{@order}"
    end

    q = "%#{@q.strip}%"
    @result = find_org_subfield_attache q,@org_subfield,sort
    @result = visable_attachemnts @result
    if params[:other]
      @result = @result.select{|attachment|
        attachment.tag_list.index{|tag|tag != '软件' and tag != '媒体' and tag != '代码'}.present?
      }
    else
      @result = @result.select{|attachment| attachment.tag_list.include?(@tag_name)} unless @tag_name.blank?
    end
    @searched_attach = paginateHelper @result,10
    @tag_list = get_org_subfield_tag_list @org_subfield

    respond_to do |format|
      format.js
      # format.html
    end
  end

  def subfield_upload_file
    @org_subfield = OrgSubfield.find(params[:org_subfield_id])
  end

  def upload_files_menu

  end

  def edit_file_description
    @attachment = Attachment.find(params[:id])
    @attachment.description = params[:file_description_edit]
    @attachment.save
  end

  def update_file_description
    @attachment = Attachment.find(params[:id])
    @attachment.description = params[:description]
    @attachment.save
  end
end