#  fq
# class BidsController < ApplicationController
class ContestsController < ApplicationController
  layout "contest_base"
  
  menu_item :respond                
  menu_item :project, :only => :show_project
  menu_item :application, :only => :show_softapplication
  menu_item :attendingcontests, :only => :show_attendingcontest
  menu_item :contestnotifications, :only => :index

  before_filter :can_show_contest, :except => []    # modified by alan
  
  # modified by longjun
  before_filter :find_contest, :only => [
                                      :show_contest, :show_project, :show_softapplication,
                                      :show_attendingcontest, :index, :set_reward_project, 
                                      :set_reward_softapplication, :create, :destroy, :more,
                                      :back, :add, :add_softapplication, :new,:show_results, 
                                      :set_reward, :show_contest_project, :show_contest_user, :watcherlist,
                                      :join_in_contest, :unjoin_in_contest, :new_join,  :settings
                                    ]
  # end longjun            
         
  # added by fq
  before_filter :require_login, :only => [:join_in_contest, :unjoin_in_contest]
  # end
  before_filter :require_login,:only => [:set_reward, :destroy, :add, :new ]

  helper :watchers
  helper :attachments
  helper :projects
  helper :words

  include AttachmentsHelper
  include ApplicationHelper
  

  def index
    render_404 unless params[:name]
    # @contests = Contest.visible
    # @contests ||= []
    @offset, @limit = api_offset_and_limit(:limit => 10)
    #@contests = Contest.visible
    #@contests = @contests.like(params[:name]) if params[:name].present?
    @is_search = params[:name] ? true:false
    @contests =  Contest.visible.where("name like '%#{params[:name]}%'")
    if params[:contests_search]
      (redirect_to contests_url, :notice => l(:label_sumbit_empty);return) if params[:name].blank?
    end
    @contest_count = @contests.count
    @contest_pages = Paginator.new @contest_count, @limit, params['page']

    @offset ||= @contest_pages.reverse_offset
    if params[:contest_sort_type].present?
    case params[:contest_sort_type]
    when '0'
       # modified by longjun
      # never use unless and else, 将下面重复操作模块化，放在private下
      # unless @offset == 0
      # if @offset != 0
      #   @contests = @contests.reorder('contests.commit').offset(@offset).limit(@limit).all.reverse
      # else
      #   limit = @contest_count % @limit
      #   limit = @limit  if limit == 0
      #   @contests = @contests.reorder('contests.commit').offset(@offset).limit(limit).all.reverse

      @contests = index_page_sort(@offset, @limit, @contest_count, @contests, 'contests.commit')
      # end
      @s_state = 0
    when '1'

      @contests = index_page_sort(@offset, @limit, @contest_count, @contests, 'contests.created_on')
      @s_state = 1
    # modified by longjun
    # 目前只有 0， 1 两个sort_type
    # when '2'
      else
    # end longjun

      @contests = index_page_sort(@offset, @limit, @contest_count, @contests, '')
      @s_state = 0
    end
    else
      # modified by longjun
      # never use unless and else
      # unless @offset == 0
      if @offset != 0
        @contests = @contests.reorder('contests.created_on').offset(@offset).limit(@limit).all.reverse
      else
        limit = @contest_count % @limit
        limit = @limit  if limit == 0
        @contests = @contests.reorder('contests.created_on').offset(@offset).limit(limit).all.reverse
      end
      @s_state = 1
    end
  end

  def search
    redirect_to action: 'index',name:params[:name]
  end

  def homework
    @offset, @limit = api_offset_and_limit({:limit => 10})
    @bids = @course.homeworks.order('deadline DESC')
    @bids = @bids.like(params[:name]) if params[:name].present?
    @bid_count = @bids.count
    @bid_pages = Paginator.new @bid_count, @limit, params['page']

    @offset ||= @bid_pages.reverse_offset
    # modified by longjun
    # never use unless and else
    # unless @offset == 0
    if @offset != 0
      @bids = @bids.offset(@offset).limit(@limit).all.reverse
    else
      limit = @bid_count % @limit
      @bids = @bids.offset(@offset).limit(limit).all.reverse
    end
    render :layout => 'base_courses'

  end


  def show_contest
    @user = @contest.author
    @jours = @contest.journals_for_messages.where('m_parent_id IS NULL').order('created_on DESC')
    #@limit =  10
    #@feedback_count = @jours.count
    #@feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    #@offset ||= @feedback_pages.offset
    #@jour = @jours[@offset, @limit]
    @jour = paginateHelper @jours,10
    @state = false

    respond_to do |format|
      format.html {
        render :layout => 'base_newcontest'
      }
      format.api
    end
  end
  
  def join_in_contest
    if params[:contest_password] == @contest.password
      JoinInCompetition.create(:user_id => User.current.id, :competition_id => @contest.id)
      @state = 0
    else
      @state = 1
    end
 
    respond_to do |format|
      format.js { render :partial => 'set_join', :locals => {:user => User.current, :object_id => params[:id]} }
    end
  end
  
  def unjoin_in_contest
     
    joined = JoinInCompetition.where('competition_id = ? and user_id = ?', @contest.id, User.current.id)
            
    joined.each do |join|
      join.delete
    end
    
    respond_to do |format|
      format.js { render :partial => 'set_join', :locals => {:user => User.current, :object_id => params[:id]} }
    end
  end
  

  
  def show_participator
    render :layout => 'base_newcontest'
    
  end
  
  
  def settings
     if @contest.author.id == User.current.id 
           @contest = Contest.find(params[:id])
           render :layout => 'base_newcontest'
     else
         render_403 :message => :notice_not_contest_setting_authorized
     end
  end

  # Added by Longjun
  def destroy_contest
    @contest = Contest.find(params[:id])
    if @contest.author_id == User.current.id || User.current.admin?
      
      @contest.destroy
      redirect_to  welcome_contest_url
    else
      render_403 :message => :notice_not_contest_delete_authorized
    end
    
  end
  # end
  
  def show_contest_project
    contests = Contest.where('parent_id = ?', @contest.id)
    @projects = []
    
    # Modified by longjun
    # 用 arr.each 替换 for [ according to the style guide ]
    
    # for contest in contests
      # @projects += contest.contesting_projects
    # end
    
    contests.each do |contest|
        @projects += contest.contesting_projects
    end  
    
    # end

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

  def show_contest_softapplication
    contests = Contest.where('parent_id = ?', @contest.id)
    @softapplications = []
    
    # Modified by Longjun
    # for contest in contests
      # @softapplications += contest.contesting_softapplications
    
  
    contests.each do |contest|
        @softapplications += contest.contesting_softapplications
     end
     
     # end
     
    respond_to do |format|
        format.html {
          render :layout => 'base_newcontest'
        }
        format.api

    end
  end
  
  def show_contest_user
    contests = Contest.find(:all)
    @users = []
  
    # Modified by Longjun 
    # for contest in contests
      # for project in contest.projects
        # @users += project.users
      # end
  
    
    contests.each do |contest|
        contest.projects.each do |project|
          @users += project.users
        end
    end
    # end 
    
    respond_to do |format|
        format.html {
          render :layout => 'base_newcontest'
        }
        format.api

    end
  end
  #显示参赛的项目
  def show_project
    @membership = User.current.memberships.all(:conditions => Project.visible_condition(User.current))
    @option = []
    # @contesting_project_count = @contesting_project_all.count
    # @contesting_project_pages = Paginator.new @contesting_project_count, per_page_option, params['page']
    @membership.each do |membership|
      
      # Modified by Longjun 
      # 将两个判断语句合并
      # unless membership.project.project_type==1
        # if User.current.allowed_to?(:quote_project, membership.project)
            # @option << membership.project
        # end
      # end
      if membership.project.project_type != 1 && User.current.allowed_to?(:quote_project, membership.project)
            @option << membership.project
        
      end
      # end
      
    end
    @user = @contest.author
    @contesting_project = @contest.contesting_projects.all
    if params[:student_id].present?
      @temp = []
      @contesting_project.each do |pro|
        if pro.project && pro.project.project_status
          if /#{params[:student_id]}/ =~  pro.user.user_extensions.student_id
            @temp << pro
          end
        end
        @temp
      end
      @contesting_project = @temp
    else
  
      @temp = []
      @contesting_project.each do |pro|
        # modified by longjun
        # if pro.project && pro.project.project_status
        #   @temp << pro
        # end
        @temp << pro if pro.project && pro.project.project_status
        # end longjun
        @temp
      end
      if @temp.size > 0
          @contesting_project = @temp.sort {|a,b| b.project.project_status.grade <=> a.project.project_status.grade}
      end
    end
    @contesting_project = paginateHelper(@contesting_project)
    respond_to do |format|
      format.html {
        render :layout => 'base_newcontest'
      }     
      format.api
    end
  end 
  ############
  ##显示参赛的应用
  def show_softapplication
    
    # @membership = User.current.memberships.all(:conditions => Project.visible_condition(User.current))
    # @option = []  

    # @user = @contest.user
    @softapplication = Softapplication.all 
    @contesting_softapplication = @contest.contesting_softapplications

    @contesting_softapplication = paginateHelper(@contesting_softapplication, 10) 
    
    # @temp = []
    # @softapplicationt.each do |pro|
    #   if pro.project && pro.project.project_status
    #     @temp << pro
    #   end
    #   @temp
  
    # if @temp.size > 0
    #     @contesting_project = @temp.sort {|a,b| b.project.project_status.grade <=> a.project.project_status.grade}
    # end
    # end
    # respond_to do |format|
    #   format.html {
    #     render :layout => 'base_newcontest'
    #   }     
    #   format.api
    # end  
##########################
    @contest = Contest.find_by_id(params[:id])
    respond_to do |format|
      format.html {
        render :layout => 'base_newcontest'
      }     
      format.api
    end
  end
 
 
 ###我要参赛
 def show_attendingcontest
##取出参赛项目--项目列表
    @membership = User.current.memberships.all(:conditions => Project.visible_condition(User.current))
    @option = []
    # @contesting_project_count = @contesting_project_all.count
    # @contesting_project_pages = Paginator.new @contesting_project_count, per_page_option, params['page']
    @membership.each do |membership|
      unless membership.project.project_type==1
        #拥有编辑项目权限的可将该项目参赛
        if User.current.allowed_to?(:quote_project, membership.project)
          @option << membership.project
        end
      end
    end
    @user = @contest.author
    @contesting_project = @contest.contesting_projects.all
    if params[:student_id].present?
      @temp = []
      @contesting_project.each do |pro|
        if pro.project && pro.project.project_status
          if /#{params[:student_id]}/ =~  pro.user.user_extensions.student_id
            @temp << pro
          end
        end
        @temp
      end
      @contesting_project = @temp
    else
  
      @temp = []
      @contesting_project.each do |pro|
        # modified by longjun
        # if pro.project && pro.project.project_status
        #   @temp << pro
        # end
        @temp << pro if pro.project && pro.project.project_status
        # end longjun
        @temp
      end
      if @temp.size > 0
          @contesting_project = @temp.sort {|a,b| b.project.project_status.grade <=> a.project.project_status.grade}
      end
    end
    # 取出参赛应用   --应用列表
    @softapplication = Softapplication.all 
    @contesting_softapplication = @contest.contesting_softapplications.
      joins("LEFT JOIN softapplications ON contesting_softapplications.softapplication_id=softapplications.id").
      joins("LEFT JOIN (
              SELECT * FROM seems_rateable_cached_ratings
                  WHERE cacheable_type='Softapplication' AND DIMENSION = 'quality') AS cached
                  ON cached.cacheable_id=softapplications.id").
      order("cached.avg").reverse_order
    @contesting_softapplication = paginateHelper  @contesting_softapplication, 10
    
    
    #引用base_newcontest整体样式
    @contest = Contest.find_by_id(params[:id])
    respond_to do |format|
      format.html {
        render :layout => 'base_newcontest'
      }     
      format.api
    end  
 end
 
 ###end

  def show_notification
      @contest = Contest.find_by_id(params[:id])
      respond_to do |format|
        format.html {
          render :layout => 'base_newcontest'
        }     
        format.api
      end 
  end

 
  def set_reward_project
    @c_p = nil
    @contesting_project_id = nil

    if params[:set_reward_project][:reward]&&((User.current.id==@contest.author_id)||User.current.admin)
      # @bid_id = params[:id]
      @contesting_project_id = params[:set_reward_project][:c_id]
      @c_p = ContestingProject.find_by_id(@contesting_project_id)

      # 把字段存进表中
      @c_p.update_reward(params[:set_reward_project][:reward].to_s)
    end

    respond_to do |format|
      format.js
    end
  end
 
  def set_reward_softapplication
    @c_sa = nil
    @contesting_softapplication_id = nil

    if params[:set_reward_softapplication][:reward]&&((User.current.id==@contest.author_id)||User.current.admin)
      # @bid_id = params[:id]
      @contesting_softapplication_id = params[:set_reward_softapplication][:c_id]
      @c_sa = ContestingSoftapplication.find_by_id(@contesting_softapplication_id)

      # 把字段存进表中
      @c_sa.update_reward(params[:set_reward_softapplication][:reward].to_s)
    end

    respond_to do |format|
      format.js
    end
  end 
 
 
  ###添加已创建的参赛项目
  def add
    project = Project.find(params[:contest])
    contest_message = params[:contest_for_save][:contest_message]
    if ContestingProject.where("project_id = ? and contest_id = ?", project.id, @contest.id).size == 0
      # modified by longjun, create 写错了
      # if ContestingProject.cerate_contesting(@contest.id, project.id, contest_message)
      if ContestingProject.create_contesting(@contest.id, project.id, contest_message)
      # end longjun

        flash.now[:notice] = l(:label_bidding_contest_succeed)
      end
    else
      flash.now[:error] = l(:label_bidding_fail)
    end
    
    @contesting_project = paginateHelper @contest.contesting_projects
    
    respond_to do |format|

      format.html { redirect_to :back }
      format.js
    end
  end
  ###添加已发布的参赛应用
  def add_softapplication
    softapplication = Softapplication.find(params[:contest])
    contest_message = params[:contest_for_save][:contest_message]
    if ContestingSoftapplication.where("softapplication_id = ? and contest_id = ?", softapplication.id, @contest.id).size == 0
      if ContestingSoftapplication.create_softapplication_contesting(@contest.id, softapplication.id, contest_message)
        flash.now[:notice] = l(:label_release_add_contest_succeed)
      end
    else
      flash.now[:error] = l(:label_add_contest_succeed_fail)
    end
    
    @contesting_softapplication = paginateHelper @contest.contesting_softapplications
    
    respond_to do |format|

      format.html { redirect_to :back }
      format.js
    end
  end
  ## 新建留言
  def create

    if params[:contest_message][:message].size>0
      if params[:reference_content]
        message = params[:contest_message][:message] + "\n" + params[:reference_content]
      else
        message = params[:contest_message][:message]
      end
      refer_user_id = params[:contest_message][:reference_user_id].to_i
      @contest.add_jour(User.current, message, refer_user_id)
    end
    @user = @contest.author
    @jours = @contest.journals_for_messages.where('m_parent_id IS NULL').order('created_on DESC')
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]
    @contest.set_commit(@feedback_count)

    respond_to do |format|
      format.js
    end

  end

  ##删除留言
  def destroy
    @user = @contest.author
    if User.current.admin? || User.current.id == @user.id
      JournalsForMessage.delete_message(params[:object_id])
    end
    @jours = @contest.journals_for_messages.reverse
    @limit =  10
    @feedback_count = @jours.count
    @feedback_pages = Paginator.new @feedback_count, @limit, params['page']
    @offset ||= @feedback_pages.offset
    @jour = @jours[@offset, @limit]

    @contest.set_commit(@feedback_count)
    respond_to do |format|
      format.js
    end
  end

  ##引用留言
  def new
    @jour = JournalsForMessage.find(params[:journal_id]) if params[:journal_id]
    if @jour
      user = @jour.user
      text = @jour.notes
    else
      user = @contest.author
      text = @contest.description
    end
    text = text.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]')
    @content = "> #{ll(User.current.language, :text_user_wrote, user)}\n> "
    @content << text.gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
    @id = user.id
    rescue ActiveRecord::RecordNotFound
    render_404
  end

  ##新建竞赛
  def new_contest
    @contest = Contest.new
    @contest.safe_attributes = params[:contest]
  end
  
  ##提交创建的竞赛
  def create_contest
    @contest = Contest.new
    @contest.name = params[:contest][:name]
    @contest.description = params[:contest][:description]
    @contest.budget = params[:contest][:budget]
    @contest.deadline = params[:contest][:deadline]
    @contest.password = params[:contest][:password]     
    @contest.author_id = User.current.id
    @contest.commit = 0
    if @contest.save
      unless @contest.watched_by?(User.current)
        if @contest.add_watcher(User.current)
          flash[:notice] = l(:label_contesting_created_succeed)
        end
      end
      redirect_to show_contest_contest_url(@contest)
    else
      @contest.safe_attributes = params[:contest]
      render :action => 'new_contest'
    end
  end

  ##更新竞赛配置信息
  def update_contest
    @contest = Contest.find(params[:id])
    @contest.name = params[:contest][:name]
    @contest.description = params[:contest][:description]
 
    @contest.budget = params[:contest][:budget]
    @contest.deadline = params[:contest][:deadline]
    @contest.password = params[:contest][:password]      
    @contest.author_id = User.current.id
    @contest.commit = 0
    if @contest.save
      unless @contest.watched_by?(User.current)
        if @contest.add_watcher(User.current)
          flash[:notice] = l(:label_contesting_updated_succeed)
        end
      end
      redirect_to show_contest_contest_url(@contest)
      
    else
      @contest.safe_attributes = params[:contest]
      render :action => 'new_contest'
    end
  end

  def more
    @jour = @contest.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
    @state = true

    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    #format.api { render_api_ok }
    end
  end

  def back
    @jour = @contest.journals_for_messages
    @jour.each_with_index {|j,i| j.indice = i+1}
    @state = false

    respond_to do |format|
      format.html { redirect_to :back }
      format.js
    #format.api { render_api_ok }
    end
  end

  def set_reward
    @b_p = nil
    @contesting_project_id = nil

    if params[:set_reward][:reward]&&((User.current.id==@contest.author_id)||User.current.admin)
      # @contest_id = params[:id]
      @contesting_project_id = params[:set_reward][:b_id]   #[:b_id]???
      @b_p = ContestingProject.find_by_id(@contesting_project_id)

      # 把字段存进表中
      @b_p.update_reward(params[:set_reward][:reward].to_s)
    end

    respond_to do |format|
      format.js
    end
  end
  def watcherlist
    render :layout => 'base_newcontest'
  end



  private

  def find_contest
    if params[:id]
      @contest = Contest.find(params[:id])
      @user = @contest.author
    end
    rescue
    render_404
  end

  #验证是否显示竞赛
  def can_show_contest
    @first_page = FirstPage.find_by_page_type('project')
    if @first_page.show_contest == 2
      render_404
    end
  end

  # added by longjun
  # 将index页面中分页排序的方法抽离出来
  def index_page_sort(offset, limit, contest_count, contests, contest_sort_by)
    # modified by longjun
    # never use unless and else
    # unless @offset == 0
    if offset != 0
      contests = contests.reorder(contest_sort_by).offset(offset).limit(limit).all.reverse
    else
      limit = contest_count % limit
      limit = limit  if limit == 0
      contests = contests.reorder(contest_sort_by).offset(offset).limit(limit).all.reverse
    end
    contests
  end
end

