# encoding: utf-8
class StatisticsController < ApplicationController
  layout "statictis"

  # before_filter :allowed_user
  before_filter :find_rate

  def index
    render file: 'public/react/build/index.html', :layout => false
  end

  # 用户活跃度(按月份的)
  def user_active_for_months
    @start_time = params[:start_time] || "2016-03-01"
    @end_time = params[:end_time] || Time.now.strftime("%Y-%m-%d")

    sql = "select a.x_count, ceil(if(count(*)<1000, count(*)+#{@base_score.to_i}, count(*))*#{@rate.to_i}) as y_count from (SELECT user_id, DATE_FORMAT(created_at,'%Y-%m') as x_count FROM `user_actions` where
           created_at between '#{@start_time} 00:00:00' and '#{@end_time} 23:59:59' group by x_count, user_id order by created_at) a group by a.x_count"

    count_datas = UserActions.find_by_sql(sql)
    respond_to do |format|
      format.xls{
        filename = "用户活跃度_#{Time.now}.xls"
        send_data(user_list_xls(count_datas), :type => 'application/octet-stream', :filename => filename_for_content_disposition(filename))
      }
    end

  end

  # 用户数据
  def user_datas
    t1 = Time.now - 24*3600
    shixuns_count = Shixun.where("created_at > ?", t1).count
    tainings_count = EvaluateRecord.where("created_at > ?", t1).count
    homeworks_count = StudentWork.where("created_at > ?", t1).count
    courses_count = Course.where("created_at > ?", t1).count
    messages_count = Message.where("created_on > ?", t1).count + JournalsForMessage.where("created_on > ?", t1).count
    render :json => {:shixuns_count => shixuns_count, :tainings_count => tainings_count, :homeworks_count => homeworks_count,
                     :courses_count => courses_count, :messages_count => messages_count}
  end

  # 每个月情况: 取当前日期最近的30天
  def per_month
    end_time = Time.now.strftime("%Y-%m-%d ") + "23:59:59"
    start_time = (Time.now - 30*24*3600).strftime("%Y-%m-%d ") + "00:00:00"

    sql = "SELECT DATE_FORMAT(last_login_on,'%Y-%m-%d') as x_count, ceil(if(count(*)<1000, count(*)+#{@base_score}, count(*))*#{@rate}) as y_count FROM `users` where
           last_login_on between '#{start_time}' and '#{end_time}' group by DAYOFMONTH(last_login_on) order by last_login_on"
    count_datas = User.connection.select_all(sql)

    # list = []
    # # 格式转换
    # 31.times do |i|
    #   if count_datas.select{|cd| cd["x_count"].to_i == (i+1)}.present?
    #     list << {:x_count => i+1, :y_count => count_datas.select{|cd| cd["x_count"].to_i == (i+1)}.first["y_count"]}
    #   else
    #     list << {:x_count => i+1, :y_count => 0}
    #   end
    # end
    #
    # list.sort_by do |p|
    #   p['x_count']
    # end

    render :json => {:data => count_datas}
  end

  # 每周情况
  def per_week
    t1 = Time.now
    swap = (t1 - params[:day].to_i*24*3600).strftime("%Y-%m-%d ")
    start_time = swap + "00:00:00"
    end_time = swap + "23:59:59"
    sql = "SELECT FROM_UNIXTIME( UNIX_TIMESTAMP( last_login_on ),  '%H' ) AS x_count, ceil(if(count(*)<1000, count(*)+#{@base_score/24}, count(*))*#{@rate}) AS y_count
          FROM users WHERE last_login_on  between '#{start_time}' AND '#{end_time}' GROUP BY x_count"
    count_datas = User.connection.select_all(sql)
    # 24.times do |i|
    #   if count_datas.select{|cd| cd["lt"].to_i == i}.present?
    #     list << {:lt => i, :y_count => count_datas.select{|cd| cd["x_count"].to_i == (i+1)}.first["y_count"]}
    #   else
    #     list << {:x_count => i+1, :y_count => 0}
    #   end
    # end

    render :json => {:data => count_datas}
  end

  # 学校数据
  # 以学校为单位,学校名称、该学校下的学生数、老师数、对应总实训个数、所有实训的累计时长、所有学生在线总时长(表格数据提供)
  def school_datas
    limit = 10
    offset = (params[:page].to_i - 1) * limit
    sql = "SELECT count(*) as users_count, ue.school_id school_id, s.name school_name FROM `user_extensions` ue, schools s
           where ue.school_id =s.id and ue.school_id is not null
           group by ue.school_id order by users_count desc limit #{limit} offset #{offset}"
    data = []
    UserExtensions.find_by_sql(sql).each do |ue|
      students_count = UserExtensions.where(:identity => 0, :school_id => ue.school_id).count
      teachers_count = UserExtensions.where(:identity => 1, :school_id => ue.school_id).count
      shixuns_count = Shixun.find_by_sql("select count(s.id) as shixun_count from users u right join shixuns s on u.id=s.user_id and
                                          s.status in (2, 3) inner join user_extensions ue on u.id=ue.user_id and ue.school_id=#{ue.school_id}").first.try(:shixun_count)
      shixun_total_time = (Game.find_by_sql("select sum(g.end_time-g.open_time) cost_time from users u left join games g on u.id=g.user_id inner join user_extensions ue on
                                             u.id=ue.user_id and ue.school_id=#{ue.school_id}").first.try(:cost_time).to_i / (24*60*60.0)).ceil
      students_online_time = (Game.find_by_sql("select sum(g.cost_time) cost_time from users u left join games g on u.id=g.user_id inner join user_extensions ue on
                                                u.id=ue.user_id and ue.school_id=#{ue.school_id}").first.try(:cost_time).to_i / (24*60*60.0)).ceil
      data << {:school_name => ue.school_name, :students_count => students_count, :teachers_count => teachers_count, :shixuns_count => shixuns_count,
               :shixun_total_time => shixun_total_time, :students_online_time => students_online_time}
    end
    render :json => {:data => data}
  end

  # 用户增长数
  def user_info
    sql = "SELECT DATE_FORMAT(created_on,'%Y-%m') as x_count, ceil(if(count(*)<1000, count(*)+#{@base_score}, count(*))*#{@rate}) as y_count FROM `users` where
           created_on between '#{@start_time}-01 00:00:00' and '#{@end_time}-31 23:59:59' group by x_count order by created_on"
    users = User.find_by_sql(sql)
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "sheet"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["时间","增涨总数"])
    count_row = 1
    users.each do |user|
      sheet1[count_row, 0] = user['x_count']
      sheet1[count_row, 1] = user['y_count']
      count_row += 1
    end
    book.write xls_report
    send_data(xls_report.string, :type => "text/excel;charset=utf-8; header=present",
              :filename => filename_for_content_disposition("用户增长数.xls"))
  end

  def top_schools
    sql = "SELECT DATE_FORMAT(created_at,'%Y-%m') as time  from user_extensions where created_at between '#{@start_time}-01 00:00:00' and '#{@end_time}-31 23:59:59' group by time"
    times = UserExtensions.connection.select_all(sql)

    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "sheet"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["时间","高校1","增加总数","高校2","增加总数","高校3","增加总数"])
    count_row = 1
    times.each do |time|
      sql2 = "select count(*) as count, s.name from user_extensions ue, schools s where ue.school_id=s.id and ue.created_at between '#{time['time']}-01 00:00:00' and '#{time['time']}-31 23:59:59'
              group by school_id order by count desc limit 3"
      user = UserExtensions.find_by_sql(sql2)
      if user.length > 2
        sheet1[count_row, 0] = time['time']
        sheet1[count_row, 1] = user[0]['name']
        sheet1[count_row, 2] = user[0]['count']
        sheet1[count_row, 3] = user[1]['name']
        sheet1[count_row, 4] = user[1]['count']
        sheet1[count_row, 5] = user[2]['name']
        sheet1[count_row, 6] = user[2]['count']
        count_row += 1
      end
    end
    book.write xls_report
    send_data(xls_report.string, :type => "text/excel;charset=utf-8; header=present",
              :filename => filename_for_content_disposition("学校增长top3.xls"))
  end

  # 每个学校的活跃用户数
  def school_active_user_count
    sql = "SELECT ceil(if(count(users.id)<1000, count(users.id)+#{@base_score}, count(users.id))*#{@rate}) as y_count, s.name as s_name FROM users, schools s, user_extensions ue WHERE
           last_login_on between '#{Time.parse(@start_time)}' and '#{Time.parse(@end_time)}' AND users.id=ue.user_id AND s.id = ue.school_id GROUP BY ue.school_id ORDER BY y_count DESC"
    datas = User.find_by_sql(sql)
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "学校用户活跃数"
    sheet1.row(0).concat(["序号","学校","活跃用户数"])
    count_row = 1
    datas.each_with_index do |data, index|
      sheet1[count_row,0] = index + 1
      sheet1[count_row,1] = data.s_name
      sheet1[count_row,2] = data.y_count
      count_row += 1
    end
    book.write xls_report
    send_data(xls_report.string, :type => "text/excel;charset=utf-8; header=present",
              :filename => filename_for_content_disposition("学校活跃用户数.xls"))
  end

  def settings
    unless User.curren.admin?
      render_403
    end
    render file: 'public/react/build/index.html', :layout => false
  end

  def set_rate
    rate = Statistic.first
    if rate
      rate.update_column(:rate, params[:rate])
    else
      Statistic.create(:rate => params[:rate])
    end
  end

  def allowed_user
    unless (User.current.admin? || User.current.login == "forge01")
      render_403
    end
  end

  def find_rate
    @rate = params[:rate] || 1
    @base_score = params[:base_score] || 0
    @start_time = params[:start_time] || Time.now.strftime('%Y-%m-%d %H:%M:%S')
    @end_time = params[:end_time] || Time.now.strftime('%Y-%m-%d %H:%M:%S')
  end

  def user_list_xls users
    xls_report = StringIO.new
    book = Spreadsheet::Workbook.new
    sheet1 = book.create_worksheet :name => "sheet"
    blue = Spreadsheet::Format.new :color => :blue, :weight => :bold, :size => 10
    sheet1.row(0).default_format = blue
    sheet1.row(0).concat(["时间","数目"])
    count_row = 1
    users.each do |user|
      sheet1[count_row, 0] = user['x_count']
      sheet1[count_row, 1] = user['y_count']
      count_row += 1
    end
    book.write xls_report
    xls_report.string
  end
end