class DiscussesController < ApplicationController
  LIMIT = 10
  before_action :require_login, only: [:create, :reply, :hidden, :reward_code, :plus, :destroy]
  before_action :find_container, only: [:index, :hidden]
  before_action :find_discuss, except: [:create, :index, :new_message, :reward_code, :forum_discusses, :plus]

  def index
    page = params[:page].to_i
    offset = page * LIMIT
    # 总数，分页使用
    if current_user.admin?
      @disscuss_count = Discuss.where(:dis_id => @container.id, :dis_type => @container.class.to_s, :root_id => nil).count
      disscusses = Discuss.where(:dis_id => @container.id, :dis_type => @container.class.to_s,
                                             :root_id => nil)
    else
      disscusses = Discuss.where("dis_id = :dis_id and dis_type = :dis_type and root_id is null and
                                      (discusses.hidden = :hidden or discusses.user_id = :user_id)",
                                 {dis_id: @container.id, dis_type: @container.class.to_s, hidden: false, user_id: current_user.id})
      @disscuss_count = disscusses.count("discusses.id")
    end
    @manger = @container.has_manager?(current_user)
    if @manger
      @discusses = disscusses.limit(LIMIT).joins("left join games on discusses.challenge_id = games.challenge_id and discusses.user_id = games.user_id")
                       .select("discusses.*, games.identifier").includes(:user, :praise_treads).offset(offset)
    else
      @discusses = disscusses.limit(LIMIT).includes(:user, :praise_treads).offset(offset)
    end

    @current_user = current_user
  end

  def forum_discusses
    page = params[:page] || 1
    limit = params[:limit] || 15
    offset = (page.to_i-1) * limit
    search = params[:search]
    tag = params[:tag_repertoire_id]
    sql, sql1, sql2 = '', '', ''
    sql1 =
      unless search.blank?
        "and d.content like '%#{search}%'"
      end

    sql2 =
      if tag
        shixun_ids = ShixunTagRepertoire.where(:tag_repertoire_id => tag).pluck(:shixun_id)
        "and d.dis_id in(#{shixun_ids.join(",")})"
      end

    sql = "select d.id from discusses d join shixuns s on d.dis_id = s.id where s.status = 2 and s.hidden = false and d.root_id is null
           and d.hidden = false #{sql1} #{sql2} order by d.created_at desc"

    memo_ids = Discuss.find_by_sql(sql).pluck(:id)
    @memo_count = memo_ids.size
    memo_ids = memo_ids[offset, limit]
    order_ids = memo_ids.size > 0 ? memo_ids.join(',') : -1
    @memos = Discuss.where(id: memo_ids).order("field(id,#{order_ids})").includes(:praise_treads, dis: :tag_repertoires, user: :user_extension)
    # @memos = memos.includes(:praise_treads, user: :user_extension).page(page).per(limit)
    # 实训标签使用最多的9个
    # @hot_tags = TagRepertoire.find_by_sql("select distinct(a.name), a.id from
    #                                       (select tr.id, tr.name, count(d.dis_id) cnt
    #                                       from tag_repertoires tr join (shixun_tag_repertoires str
    #                                       left join (shixuns s join discusses d on d.dis_id = s.id)
    #                                       on s.id = str.shixun_id) on tr.id = str.tag_repertoire_id
    #                                       group by d.dis_id order by cnt desc) a limit 9").map{|ht| ht.attributes.dup}
    tag_id = ShixunTagRepertoire.joins(:shixun).order("myshixuns_count desc").pluck(:tag_repertoire_id).uniq.first(9)
    @hot_tags = TagRepertoire.select([:id, :name]).where(id: tag_id).order("FIELD(id, #{tag_id.join(",")})").map{|ht| ht.attributes.dup} if tag_id

    @memos = DiscussesService.new.memo_list @memos
    @hot_memos = Memo.field_for_recommend.posts.hot.includes(:tag_repertoires).limit(4)
    @recommend_shixuns = DiscussesService.new.recommends
  end

  def new_message
    onclick_time = Myshixun.find(params[:myshixun_id]).try(:onclick_time)
    ids = Discuss.where(user_id: User.current.id, dis_id: params[:container_id], dis_type: params[:container_type]).
          where("parent_id is null").pluck(:id)
    @user_discuss = Discuss.where("user_id !=? and created_at >?", User.current.id, onclick_time).where(parent_id: ids,
                    dis_id: params[:container_id], dis_type: params[:container_type]).first
  end

  def create
    begin
      @discuss = Discuss.create!(:dis_id => params[:container_id], :dis_type => params[:container_type],
                                 :content => params[:content].gsub("&nbsp\;", "").strip, :user_id => current_user.id,
                                 :praise_count => 0, :position => params[:position], :challenge_id => params[:challenge_id],
                                 :hidden => !current_user.admin?) # 管理员回复的能够显示
    rescue Exception => e
      uid_logger_error("create discuss failed : #{e.message}")
      raise Educoder::TipException.new("评论异常")
    end
  end

  def reply
    begin
      @discuss = Discuss.create!(:content => params[:content].gsub("&nbsp\;", "").strip, :user_id => current_user.id,
                                 :root_id => @discuss.root_id || params[:id], :parent_id => params[:id], :praise_count => 0,
                                 :challenge_id => @discuss.challenge_id, :dis_id => @discuss.dis_id,
                                 :dis_type => @discuss.dis_type, :position => @discuss.position)
    rescue Exception => e
      uid_logger_error("reply discuss failed : #{e.message}")
      raise Educoder::TipException.new("回复评论异常")
    end
  end

  # 隐藏评论
  def hidden
    logger.info("################{current_user.id}")
    if current_user.manager_of_shixun?(@container)
      logger.info("66666666#{current_user.id}")
      @discuss.update_attribute(:hidden, params[:hidden] == "1")
      sucess_status
    else
      Educoder::TipException(403, "..")
    end
  end

  # 点/取消赞，一个用户只能点一次
  # 0 取消赞；
  def plus
    pt = PraiseTread.where(:praise_tread_object_id => params[:id], :praise_tread_object_type => params[:container_type],
                           :user_id => current_user, :praise_or_tread => 1).first
    # 如果当前用户已赞过，则不能重复赞
    if params[:type] == 1 && pt.blank?
      PraiseTread.create!(:praise_tread_object_id => params[:id], :praise_tread_object_type => params[:container_type],
                          :user_id => current_user.id, :praise_or_tread => 1)  if pt.blank?
    else
      pt.destroy if pt.present? # 如果已赞过，则删掉这条赞（取消）；如果没赞过，则为非法请求不处理
    end

    @praise_count = PraiseTread.where(:praise_tread_object_id => params[:id], :praise_tread_object_type => params[:container_type],
                                       :praise_or_tread => 1).count
  end

  # 奖励金币
  def reward_code
    unless current_user.admin?
      Educoder::TipException(403, "..")
    end

    ActiveRecord::Base.transaction do
      container_id = params[:id]
      container_type = params[:container_type]
      score = params[:score]
      user_id = params[:user_id]
      user = User.select([:id, :login, :grade]).find(user_id)

      # 金币来源记录
      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
        # Post为帖子回复类型，这个名字取的...
        when 'Memo', 'Post'
          container = Memo.find(container_id)
          score = score.to_i + container.reward.to_i
          container.update_attribute(:reward, score)
        when 'Discusses'
          container = Discuss.select([:id, :reward]).find(params[:id])
          score = score.to_i + container.reward.to_i
          container.update_attribute(:reward, score)
      end
     @code = score
    end
  end

  def destroy
    begin
      @discuss.destroy
      sucess_status
    rescue Exception => e
      uid_logger_error("destroy discuss failed: #{e.message}")
      Educoder::TipException("帖子删除异常")
    end
  end

  private
  def find_container
    @container = Shixun.select([:id, :user_id]).find_by_identifier(params[:container_identifier])
  end

  def find_discuss
    @discuss = Discuss.select([:id, :hidden, :reward, :dis_type, :dis_id, :position, :challenge_id, :root_id]).find(params[:id])
  end

end
