#coding=utf-8
# 执行示例  bundle exec rake public_course:student args=149,2903
# args 第一个参数是subject_id,第二个参数是课程course_id
# 第一期时间:2018-12-16 至2019-03-31
# 第二期时间:2019-04-07 至2019-07-28
#
# 这次学习很有收获,感谢老师提供这么好的资源和细心的服务🎉🎉🎉
#

desc "同步精品课数据"
namespace :public_course do
  subject_id = ENV['args'].split(",")[0] # 对应课程的id
  course_id = ENV['args'].split(",")[1] # 对应课堂的id
  status = ENV['args'].split(",")[2] # 表示相应的期数
  type = ENV['args'].split(",")[3] # 表示课程模块

  if status.to_i == 1
    start_time = '2018-12-16'
    end_time = '2019-04-01'
  elsif status.to_i == 2
    start_time = '2019-04-07'
    end_time = '2019-07-28'
  else
    # 这种情况是取所有的
    start_time = '2015-01-01'
    end_time = '2022-07-28'
  end

  task :student => :environment do
    puts "subject_id is #{subject_id}"
    puts "course_id is #{course_id}"

    user_ids = Myshixun.find_by_sql("select distinct(user_id) from myshixuns where shixun_id in (select shixun_id from stage_shixuns
                                     where stage_id in (select id from stages where subject_id=#{subject_id}))").map(&:user_id)
    puts user_ids
    if user_ids.present?
      user_ids.each do |user_id|
        puts user_id
        begin
          CourseMember.create!(course_id: course_id, user_id: user_id, role: 4)
        rescue Exception => e
          Rails.logger()
        end
      end
    end
  end

  #
  task :message => :environment do
    discusses = Discuss.find_by_sql("select content, user_id, created_on, updated_on from discusses where dis_id in (select shixun_id from stage_shixuns where
                                   stage_id in (select id from stages where subject_id=#{subject_id})) and created_at > #{start_time} and
                                   created_at<#{end_time}")
    discusses.find_each do |discuss|
      puts discuss.user_id
      puts discuss.content
      # 回复帖子
      # 讨论区发布帖子
      # Message.create!(board: @message.board, root_id: @message.root_id || @message.id,
      #                 author: current_user, parent: @message,
      #                 message_detail_attributes: {
      #                     content: params[:content]
      #                 })
    end
  end


  # 更新某个课程的某类时间
  # 执行示例  bundle exec rake public_course:student tiems=149,2903
  task :time => :environment do
    course_id = ENV['args'].split(",")[0] # 对应课堂的id
    satus = ENV['args'].split(",")[1]

    course = Course.find(course_id)

    hour = (6..24).to_a.sample(1).first
    min = rand(60)
    sec = rand(60)

    start_time = Date.parse(start_time)
    end_time = Date.parse(end_time)
    date = (start_time..end_time).to_a.sample(1).first

    time = "#{date} #{min_swith(hour)}:#{min_swith(min)}:#{min_swith(sec)}"

    puts time
    case type
    when 1
      # 讨论区

    end

  end

  def min_swith(time)
    puts time
    return time < 9 ? "0#{time}" : time
  end
end