# encoding=utf-8
class DiscussesService
  include ApplicationHelper
  include GamesHelper

  # “讨论区”的所有评论
  def self.index params, current_user
    page = params[:page].to_i
    offset = page * 15
    search = params[:search]
    tag = params[:tag_repertoire_id]
    sql, sql1, sq2 = '', '', ''
    tidding_count = unviewed_tiddings(current_user) if current_user.present?
    sql1 =
        if search
          "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}"

    memo_ids = Discuss.find_by_sql(sql).map(&:id)
    Rails.logger.info("############memo_ids: #{memo_ids}")
    memos = Discuss.field_for_list.where(:id => memo_ids).order("created_at desc")
    memo_count = memos.count
    memos = memos.offset(offset).limit(15)
    # 实训标签使用最多的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}
    memos = memo_list memos
    user_info = format_for_current_user current_user
    hot_memos = Memo.field_for_recommend.posts.hot.limit(4)
    hot_memos =
        hot_memos.map do |hm|
          replies_count = Memo.where(:root_id => hm.id).count
          hm.attributes.dup.merge({replies_count: replies_count})
        end

    my_memos_count = Memo.user_posts(current_user.id).count
    {memo_list: memos, memo_count: memo_count, hot_memos: hot_memos, hot_tags: hot_tags,
     my_memos_count: my_memos_count, tidding_count: tidding_count, current_user: user_info,
     recommend_shixuns: recommends}
  end

  # 添加评论
  def create(params, current_user)
    begin
      Discuss.create!(
        dis_id: params[:shixun_id], dis_type: 'Shixun', 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?
      )
      # 发送手机通知
      Trustie::Sms.send(mobile:'18173242757', send_type:'discuss', name:'管理员')
    rescue Exception => e
      raise(e.message)
    end
  end

  # 回复评论
  def reply(params, current_user)
    begin
      base_dicuss params[:id]
      Discuss.create!(
        content: params[:content].gsub('&nbsp\;', '').strip, user_id: current_user.id, parent_id: params[:id],
        root_id: @discuss.root_id || params[:id], praise_count: 0, challenge_id: @discuss.challenge_id,
        dis_id: @discuss.dis_id, dis_type: @discuss.dis_type, position: @discuss.position, hidden: !current_user.admin?
      )
    rescue Exception => e
      raise(e.message)
    end
  end

  # 隐藏评论功能
  def hidden(params, current_user)
    discuss = Discuss.select([:id, :hidden, :dis_id]).find(params[:id])
    shixun = Shixun.find(discuss.try(:dis_id))
    if current_user.manager_of_shixun?(shixun)
      if params[:hidden] == "1"
        discuss.update_attribute(:hidden, true)
      elsif params[:hidden] == "0"
        discuss.update_column("hidden", false)
      end
    else
      raise("你没有权限")
    end
  end

  # 点/取消赞
  # 一个用户只能一次
  def plus params, current_user
    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

    return {: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 params, current_user
    # 仅admin操作
    unless current_user.admin?
      raise("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
      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
      return {:code => score}
    end
  end

  # 基本查询
  def base_dicuss id
    @discuss = Discuss.select([:id, :hidden, :reward, :dis_type, :dis_id, :position, :challenge_id, :root_id]).find(id)
  end

  protected
  def memo_list memos
    memos.map do |m|
      user = User.find(m.user_id)
      praise_count = m.praise_tread.where(:praise_or_tread => 1).count
      replies_count = Discuss.where(:root_id => m.id).count
      shixun_tag = m.dis.tag_repertoires.map(&:name)
      m.attributes.dup.except("user_id", "dis_id", "dis_type", "root_id").merge({
                                                                                    subject: (message_content m.content),
                                                                                    username: user.show_name,
                                                                                    login: user.login,
                                                                                    praise_count: praise_count,
                                                                                    replies_count: replies_count,
                                                                                    image_url: url_to_avatar(user),
                                                                                    shixun_tag: shixun_tag,
                                                                                    tpm_url: "/shixuns/#{m.dis.identifier}/shixun_discuss"
                                                                                })
    end
  end

  def format_for_current_user current_user
    {username: current_user.show_name, login: current_user.login, user_id: current_user.id, image_url: url_to_avatar(current_user), admin: current_user.admin?}
  end

  def recommends
    hot_shixuns = Shixun.field_for_recommend.published.order("myshixuns_count desc").limit(2)
    newest_shixuns = Shixun.field_for_recommend.published.order("created_at desc").limit(2)
    recommend_shixuns = []
    hot_shixuns.each do |hs|
      recommend_shixuns << {:id => hs.id, :name => hs.name, :identifier => hs.identifier, :myshixuns_count => hs.myshixuns_count, :image_url => url_to_avatar(hs)}
    end
    newest_shixuns.each do |ns|
      recommend_shixuns << {:id => ns.id, :name => ns.name, :identifier => ns.identifier, :myshixuns_count => ns.myshixuns_count, :image_url => url_to_avatar(ns)}
    end
    return recommend_shixuns
  end

  # 将数据库对象转换成哈希对象
  def object_to_hash objects
    objects.map{|o| o.attributes.dup}
  end

  def unviewed_tiddings current_user
    new_tidings_count = current_user.tidings.where("created_at > '#{current_user.onclick_time.onclick_time}'").count
    new_pri_message_count = current_user.private_messages.where("created_at > '#{current_user.onclick_time.onclick_time}'").count
    count = new_tidings_count + new_pri_message_count
    return count
  end

end