# encoding: utf-8
# Trustie - education management software
# Copyright (C) 2013-2014
class StoresController < ApplicationController
  layout 'base_stores'

  def search
    begin
    q = "%#{params[:name].strip}%"
    (redirect_to stores_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?

    result = find_public_attache q
    @searched_attach = paginateHelper result
    @result_all_count = result.count;
    rescue Exception => e
      #render 'stores'
      redirect_to stores_url
  end

  end

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

    resultSet.to_a.map { |res|
       if(res.container.nil? ||
         (res.container.class.to_s=="Project" && res.container.is_public == false) ||
         (res.container.has_attribute?(:project) && res.container.project.is_public == false) ||
         (res.container.class.to_s=="HomeworkAttach" && res.container.bid.reward_type == 3) ||
         false
         ) || (res.container.is_a?(Course) && res.container.is_public == 0)
         result.delete(res)
       end
    }
    result
  end

  LIMIT = 12 unless const_defined?(:LIMIT)
  def index
    @projects_attach = project_classification(0).take(LIMIT)
    @courses_attach = Attachment.includes(:course).where("courses.is_public = 1").
                      where(container_type: 'Course').
                      limit(LIMIT)
    # @projects_attach = Attachment.includes(:project).where("projects.project_type=? AND projects.is_public = ?", 0, 1).
    #           reorder("#{Attachment.table_name}.downloads DESC").
    #           limit(LIMIT)

    # @courses_attach = Attachment.includes(:project).where("projects.project_type=? AND projects.is_public = ?", 1, 1).
    #           reorder("#{Attachment.table_name}.downloads DESC").
    #           limit(LIMIT)
    # 悲剧 下面竞赛里没文件
    # @homeworks_attach = Attachment.
    #           joins("LEFT JOIN homework_attaches ON homework_attaches.id=attachments.container_id
    #                   LEFT JOIN bids ON homework_attaches.bid_id=bids.id").
    #           where("container_type = 'HomeworkAttach' AND bids.reward_type <> 3").
    # 					reorder("downloads DESC").
    # 					limit(LIMIT)
    @homeworks_attach = join_tools_project Message, 0
    @memos_attach = Attachment.where("container_type = 'Memo'").
    					reorder("downloads DESC").
    					limit(LIMIT)
    @attach_array = Array.new
    @attach_array.push(@projects_attach, @courses_attach, @homeworks_attach, @memos_attach)
    @str_arr = [ l(:label_project_deposit), 
               l(:label_course_practice), 
               l(:label_borad_project), #l(:label_contest_innovate),
               l(:label_forum) ]
  end

  #缺失文件列表
  def lost_file
    attachments = []
    Attachment.where("container_id is not null and container_type is not null and container_type <> 'Bid' and container_type <> 'HomeworkAttach'").each do |attachment|
      unless File.exist?(attachment.diskfile)
        attachments << attachment
      end
    end
    respond_to do |format|
      format.xls {
        send_data(homework_to_xls(attachments), :type => "text/excel;charset=utf-8; header=present",
                  :filename => filename_for_content_disposition("#{l(:label_file_lost_list)}.xls") )
      }
    end
  end
  
  private

  def project_classification project_type=0
  	# pro_attach   = Attachment.joins("LEFT JOIN projects ON attachments.container_id = projects.id").
  	# 				where("attachments.container_type='Project' AND projects.is_public=1 AND projects.project_type=#{project_type}").
  	# 				reorder("downloads DESC").
  	# 				limit(LIMIT)
    pro_attach   = join_tools_project Project, project_type
    doc_attach   = join_tools_project Document, project_type
    issue_attach = join_tools_project Issue, project_type
    mess_attach  = []#join_tools_project Message, project_type
    news_attach  = join_tools_project News, project_type
    vers_attach  = join_tools_project Version, project_type
    wiki_attach  = join_tools_project WikiPage, project_type

    tmp = pro_attach
    tmp = pro_attach+doc_attach+issue_attach+mess_attach+news_attach+vers_attach+wiki_attach
  	tmp.sort { |a, b| b.downloads <=> a.downloads }
  end
  def join_tools_project tableName, project_type=0
  	Attachment.joins(str_join_table(tableName)).
  		where("attachments.container_type='#{tableName.to_s}' AND projects.is_public=1 AND projects.project_type=#{project_type}").
  		reorder('downloads DESC').
  		limit(LIMIT)
  end

  def str_join_table tableClass
    case tableClass.to_s
    when 'Project'
      "LEFT JOIN projects ON attachments.container_id = projects.id"
    when 'Document', 'Issue', 'Version', 'News' # 连接子表即有 project_id 字段，即两层连接
      "LEFT JOIN #{tableClass.table_name} ON attachments.container_id = #{tableClass.table_name}.id 
        LEFT JOIN projects ON #{tableClass.table_name}.project_id = projects.id"
    when 'Message' # 三层连接
      "LEFT JOIN #{tableClass.table_name} ON attachments.container_id = #{tableClass.table_name}.id
        LEFT JOIN boards ON boards.id = #{tableClass.table_name}.board_id
        LEFT JOIN projects ON boards.project_id = projects.id"
    when 'WikiPage'# 三层连接
      "LEFT JOIN #{tableClass.table_name} ON attachments.container_id = #{tableClass.table_name}.id
        LEFT JOIN wikis ON wikis.id = #{tableClass.table_name}.wiki_id
        LEFT JOIN projects ON wikis.project_id = projects.id"
    else
    end
  end

  #作品列表转换为excel
  def homework_to_xls attachments
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "homework"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["文件ID","文件名","硬盘路径","上传时间","是否公开","所属对象","所属对象Id"])
    count_row = 1
    attachments.each do |attachment|
      sheet1[count_row,0] = attachment.id
      sheet1[count_row,1] = attachment.filename
      sheet1[count_row,2] = attachment.diskfile
      sheet1[count_row,3] = format_time(attachment.created_on)
      sheet1[count_row,4] = (attachment.is_public == 1 || attachment.is_public) ? "是" :"否"
      sheet1[count_row,5] = attachment.container_type
      sheet1[count_row,6] = attachment.container_id
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end
end
