class MemosController < ApplicationController
  default_search_scope :memos
  before_filter :find_forum, :only => [:new, :create, :preview, :update, :reply]
  before_filter :find_attachments, :only => [:preview]
  before_filter :find_memo, :except => [:new, :create, :preview]
  before_filter :authenticate_user_edit, :only => [:edit, :update]
  before_filter :authenticate_user_destroy, :only => [:destroy]
  before_filter :require_login, :only => [:new, :create]
  
  helper :attachments
  include AttachmentsHelper
  include ApplicationHelper

  # layout 'base_memos'

  def quote
    # @subject = @memo.subject
    # @subject = "RE: #{@subject}" unless @subject.starts_with?('RE:')
    #
    # @content = "#{ll(Setting.default_language, :text_user_wrote, @memo.author)} <br/> &nbsp; "
    # @content << @memo.content.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub(/(\r?\n|\r\n?)/, "\n") + "</blockquote>\n\n<br/>"
    # @content = "<blockquote style='word-break: break-all;word-wrap: break-word;'>" << @content
    # #@content = "> #{ll(Setting.default_language, :text_user_wrote, @memo.author)}\n> "
    # #@content << @memo.content.to_s.strip.gsub(%r{<pre>((.|\s)*?)</pre>}m, '[...]').gsub(/(\r?\n|\r\n?)/, "\n> ") + "\n\n"
    # #@content_html = textilizable(@content)
    # @temp = Memo.new
    # @temp.content = @content
  end

  # 这样处理是为了 前端react显示图片所使用
  def new
    render file: 'public/react/build/index.html', :layout => false
  end
  
  def create
    if params[:quote].nil?
      @quote = ""
    else
      @quote = params[:quote]
    end

    @memo = Memo.new(params[:memo])
    if params[:forum_type]
      case params[:forum_type]
        when '1'
          @memo.forum_id = 1
        when '3'
          @memo.forum_id = 3
        else
          @memo.forum_id = 5
          @memo.language = params[:forum_type]
      end
    else
      @memo.forum_id = @forum.id
    end
    @memo.author_id = User.current.id
    # 问吧置顶sticky:1 置顶;0不置顶
    @memo.sticky = params[:memo][:sticky].to_i

    if params[:memo][:parent_id]
      @memo.root_id = (Memo.find params[:memo][:parent_id]).root_id.nil? ? params[:memo][:parent_id].to_i : (Memo.find params[:memo][:parent_id]).root_id
    end

    @memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads]))
    @memo.content = @quote + @memo.content
    respond_to do |format|
      if @memo.save
        # Time 2015-03-24 14:47:05
        # Author lizanle
        # Description after save后需要进行资源记录的更新
        # owner_type = 1 对应的是 memo
        if !params[:asset_id].nil?
          ids = params[:asset_id].split(',')
          ids.each do |id|
            asset = Kindeditor::Asset.find(id.to_i)
            asset.owner_id = @memo.id
            asset.owner_type = 1
            asset.save
          end
        end
        format.js
        format.html {redirect_to forum_memo_path(@memo.forum, (@memo.root.nil? ? @memo : @memo.root))}
        format.json { render json: @memo, status: :created, location: @memo }
      else
        flash.now[:error] = "#{l :label_memo_create_fail}: #{@memo.errors.full_messages[0]}"
          format.js
          format.html { redirect_to(forum_path(),:errors=>@memo.errors.full_messages[0]) }
          format.json { render json: @memo.errors, status: :unprocessable_entity }
      end
    end
  end
  
  REPLIES_PER_PAGE = 20 unless const_defined?(:REPLIES_PER_PAGE)
  def show
    @user = User.current
    # 更新贴吧帖子留言对应的memo_messages的viewed字段
    unless @memo.children.blank?
      @memo.children.each do |child|
        child.memo_messages.each do |memo_message|
          if User.current.id == memo_message.user_id
            memo_message.update_attributes(:viewed => true)
          end
        end
      end
    end
    query_memo_messages = @memo.memo_messages
    unless query_memo_messages
      query_memo_messages.each do |query_memo_message|
        if User.current.id == query_memo_message.user_id
          query_memo_message.update_attributes(:viewed => true)
        end
      end
    end
    pre_count = REPLIES_PER_PAGE
    @memo = @memo.root # 取出楼主,防止输入帖子id让回复作为主贴显示
    @memo.update_column(:viewed_count, (@memo.viewed_count.to_i + 1))

    # page = params[:page]
    # if params[:r] && page.nil?
    #   offset = @memo.children.where("#{Memo.table_name}.id < ?", params[:r].to_i).count
    #   page = 1 + offset / pre_count
    # else
    # end

    # @reply_count = @memo.children.count
    # @reply_pages = Paginator.new @reply_count, pre_count, page
    # @replies = @memo.children.
    #             includes(:author, :attachments).
    #             reorder("#{Memo.table_name}.created_at DESC").
    #             limit(@reply_pages.per_page).
    #             offset(@reply_pages.offset).
    #             all

    @replies = Memo.where("root_id = #{@memo.id}").reorder("created_at desc")
    @reply_count = @replies.count
    @replies = get_no_children_comments_all @replies
    @limit_count = @replies.count
    @page = params[:page] ? params[:page].to_i + 1 : 0
    @limit = 10
    @replies = @replies[@page * @limit..@page * @limit + 9]
    @forum_page = params[:p]
    case @forum.id
      when 1
        @type = 'feed'
      when 3
        @type = 'guide'
      when 5
        @type = 'tech'
    end
    @memo_new = Memo.new

    @my_topic_count =  0
    @my_replies_count =  Memo.where(:parent_id => @memo.id).count
    
    respond_to do |format|
      format.js
      format.html {render :layout => 'base_edu'}
      format.json { render json: @memo }
      format.xml { render xml: @memo }
    end
  end

  def edit
    #@my_topic_count = 0
    #@my_replies_count =  Memo.where(:parent_id => @memo.id).count
    #@forums = Forum.reorder("topic_count desc,updated_at desc")
    #@replying = false
    @mirrors_name = MirrorRepository.where(:status => 1).map(&:type_name).sort()
    @user = User.current
    respond_to do |format|
      format.html {render :layout => 'base_edu'}
    end
  end

  def update
    # 注意,如果不需要

    @flag = false
    respond_to do |format|
      if(  @memo.update_column(:content, params[:memo][:content]) &&
           @memo.update_column(:sticky, params[:memo][:sticky].to_i) &&
           @memo.update_column(:lock, params[:memo][:lock].to_i) &&
           @memo.update_column(:subject,params[:memo][:subject]) &&
           @memo.update_column(:updated_at,Time.now))
        @memo.save_attachments(params[:attachments] || (params[:memo] && params[:memo][:uploads]))
        if params[:forum_type]
          case params[:forum_type]
            when '1'
              @memo.forum_id = 1
            when '3'
              @memo.forum_id = 3
            else
              @memo.forum_id = 5
              @memo.language = params[:forum_type]
          end
        end
        # @memo.forum_id = @forum.id
        @flag = @memo.save
        # @memo.root.update_attribute(:updated_at, @memo.updated_at)
        format.js
        format.html {redirect_to forum_memo_path(@memo.forum, (@memo.root.nil? ? @memo : @memo.root))}
      else
        format.js
        format.html { render action: "edit" }
        format.json { render json: @person.errors, status: :unprocessable_entity }
      end
    end
  end

  def reply
    if params[:memo].present? && params[:memo][:parent_id].present?
      parent = Memo.find params[:memo][:parent_id]
      @memo = params[:activity_id].blank? ? parent : Memo.find(params[:activity_id].to_i)
      @reply = Memo.new
      @reply.author = User.current
      @reply.forum_id = parent.forum_id
      @reply.content = params[:content]
      @reply.subject = "RE: #{@memo.subject}"
      #@reply.reply_id = params[:id]
      @reply.root_id = parent.root_id.nil? ? parent.id : parent.root_id
      # @reply.reply_id = params[:id]
      parent.children << @reply
    else
      @reply = Memo.new()
      @reply.content = params[:content]
      @reply.subject = @memo.subject
      @reply.author = User.current
      @reply.forum_id = @forum.id
      #@reply.content = @quote + @reply.content
      #@reply.subject = "RE: #{@topic.subject}" unless params[:reply][:subject]
      @reply.root_id = @memo.id
      @reply.safe_attributes = params[:reply]
      @memo.children << @reply
      # @reply.reply_id = params[:id]
    end

    redirect_to message_replies_forum_memo_path(@memo.forum, @memo, :user_activity_id => params[:user_activity_id])
  end

  def message_replies
    @replies = Memo.where(:root_id => @memo.id).order("created_at desc")
    @reply_count = @replies.count
    @replies = get_no_children_comments_all @replies
    #@limit_count = @replies.count
    #@page = params[:page] ? params[:page].to_i + 1 : 0
    #@limit = 10
    #@replies = @replies[@page * @limit..@page * @limit + 9]
    @reply = Message.new()
    @user_activity_id = params[:user_activity_id].blank? ? @memo.id : params[:user_activity_id].to_i
    respond_to do |format|
      format.js
    end

  end

  def destroy
    case @memo.forum_id
      when 1
        type = 'feed'
      when 3
        type = 'guide'
      when 5
        type = 'tech'
    end
    @memo.destroy
    respond_to do |format|
      #format.html { redirect_to @back_url }
      format.js{
        if params[:user_activity_id]
          @memo = Memo.find(params[:user_activity_id].to_i)
          @replies = Memo.where(:root_id => @memo.id).order("created_at desc")
          @reply_count = @replies.count
          @replies = get_no_children_comments_all @replies
        end
        #redirect_to message_replies_forum_memo_path(@memo.forum, @memo, :user_activity_id => params[:user_activity_id])
      }
      format.html { redirect_to forums_path(:type => type) }
      format.json { head :no_content }
    end
  end

  #置顶功能
  def change_sticky
    @memo.sticky ? @memo.update_attribute(:sticky, false) : @memo.update_attribute(:sticky, true)
    respond_to do |format|
      format.html {
        if params[:index]
          case @memo.forum_id
            when 1
              type = 'feed'
            when 3
              type = 'guide'
            when 5
              type = 'tech'
          end
          redirect_to forums_path(:type => type)
        else
          redirect_to forum_memo_path(@memo.forum, @memo)
        end
      }
    end
  end

  private

  def find_memo
    return unless find_forum
    #@memo = @forum.memos.find(params[:id])
    @memo = Memo.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    render_404
    nil
  end

  def find_forum
    forum_name = params[:forum_name].strip unless params[:forum_name].nil?
    @forum = forum_name ? Forum.find_by_name(forum_name) : Forum.find(params[:forum_id])
    # @forum = Forum.find(params[:forum_id])
  rescue ActiveRecord::RecordNotFound
    render_404
    nil
  end

  def authenticate_user_edit
    find_memo
    render_403 unless @memo.editable_by? User.current
  end

  def authenticate_user_destroy
    find_memo
    render_403 unless @memo.destroyable_by? User.current
  end

  def back_memo_url
    forum_memo_path(@forum, (@memo.root.nil? ? @memo : @memo.root))
  end

  def back_memo_or_forum_url
    @memo.parent_id.nil? ? forum_url(@forum) : forum_memo_url(@forum, @memo.parent_id)
  end

end