class UpdateHomeworkPublishSettingService < ApplicationService
  attr_reader :homework, :params

  def initialize(homework, params)
    @params = params
    @homework = homework
  end

  def call
    puts params
    course = homework.course
    # 作业未发布时，unified_setting参数不能为空
    if homework.publish_time.nil? || homework.publish_time > Time.now
      tip_exception("缺少统一设置的参数") if params[:unified_setting].nil?
      if params[:unified_setting] || course.course_groups_count == 0
        tip_exception("发布时间不能为空") if params[:publish_time].blank?
        tip_exception("截止时间不能为空") if params[:end_time].blank?
        tip_exception("发布时间不能早于当前时间") if params[:publish_time].to_time <= Time.now
        tip_exception("截止时间不能早于当前时间") if params[:end_time].to_time <= Time.now
        tip_exception("截止时间必须晚于发布时间") if params[:publish_time].to_time >= params[:end_time].to_time
        tip_exception("截止时间不能晚于课堂结束时间（#{course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}）") if
          course.end_date.present? && params[:end_time].to_time > course.end_date.end_of_day

        homework.unified_setting = 1
        homework.homework_group_settings.destroy_all
        homework.publish_time = params[:publish_time]
        # 截止时间为空时取发布时间后一个月
        homework.end_time = params[:end_time]

      else
        tip_exception("分班发布设置不能为空") if params[:group_settings].blank?
        # 创建作业的分班设置
        homework.create_homework_group_settings

        setting_group_ids = []

        params[:group_settings].each do |setting|
          tip_exception("分班id不能为空") if setting[:group_id].length == 0
          tip_exception("发布时间不能为空") if setting[:publish_time].blank?
          tip_exception("截止时间不能为空") if setting[:end_time].blank?
          tip_exception("发布时间不能早于当前时间") if setting[:publish_time].to_time <= Time.now
          tip_exception("截止时间不能早于当前时间") if setting[:end_time].to_time <= Time.now
          tip_exception("截止时间不能早于发布时间") if setting[:publish_time].to_time > setting[:end_time].to_time
          tip_exception("截止时间不能晚于课堂结束时间（#{course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}）") if
            course.end_date.present? && setting[:end_time] > course.end_date.end_of_day


          publish_time = setting[:publish_time] == "" ? Time.now : setting[:publish_time]
          # 截止时间为空时取发布时间后一个月
          end_time = setting[:end_time]
          HomeworkGroupSetting.where(homework_common_id: homework.id, course_group_id: setting[:group_id]).
            update_all(publish_time: publish_time, end_time: end_time)
          setting_group_ids << setting[:group_id]
        end

        # 未设置的分班：发布时间和截止时间都为nil
        HomeworkGroupSetting.where.not(course_group_id: setting_group_ids).where(homework_common_id: homework.id).
          update_all(publish_time: nil, end_time: nil)

        # 记录已发布需要发消息的分班
        publish_group_ids = HomeworkGroupSetting.where(homework_common_id: homework.id).group_published.pluck(:course_group_id)

        homework.unified_setting = 0
        homework.publish_time = homework.min_group_publish_time
        homework.end_time = homework.max_group_end_time
      end

      # 如果作业立即发布则更新状态、发消息
      if homework.publish_time <= Time.now and homework_detail_manual.comment_status == 0
        homework_detail_manual.comment_status = 1
        send_tiding = true
      end

      # 作业在"提交中"状态时
    else
      # 实训作业截止时间已过也可修改截止时间，其他作业暂不支持修改
      if (homework.homework_type == "practice" || homework.end_time > Time.now) && homework.unified_setting
        tip_exception("截止时间不能为空") if params[:end_time].blank?
        tip_exception("截止时间必须晚于发布时间") if params[:end_time].to_time <= homework.publish_time
        # tip_exception("截止时间不能早于当前时间") if params[:end_time].to_time <= Time.now
        tip_exception("截止时间不能晚于课堂结束时间（#{course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}）") if
          course.end_date.present? && params[:end_time].to_time > course.end_date.end_of_day

        homework.end_time = params[:end_time]

      elsif !homework.unified_setting
        homework.create_homework_group_settings
        tip_exception("分班发布设置不能为空") if params[:group_settings].reject(&:blank?).blank?
        params[:group_settings].each do |setting|
          group_settings = HomeworkGroupSetting.where(homework_common_id: homework.id, course_group_id: setting[:group_id])

          tip_exception("分班id不能为空") if setting[:group_id].length == 0
          tip_exception("发布时间不能为空") if setting[:publish_time].blank?
          tip_exception("截止时间不能为空") if setting[:end_time].blank?
          # 如果该发布规则 没有已发布的分班则需判断发布时间
          tip_exception("发布时间不能早于等于当前时间") if setting[:publish_time].to_time <= Time.now && group_settings.group_published.count == 0

          # tip_exception("截止时间不能早于等于当前时间") if setting[:end_time].to_time <= Time.now && group_settings.none_end.count > 0
          tip_exception("截止时间不能早于发布时间") if setting[:publish_time].to_time > setting[:end_time].to_time
          tip_exception("截止时间不能晚于课堂结束时间（#{course.end_date.end_of_day.strftime("%Y-%m-%d %H:%M")}）") if
            course.end_date.present? && setting[:end_time].to_time > course.end_date.end_of_day

          group_settings.none_published.update_all(publish_time: setting[:publish_time])
          # 实训作业截止时间已过也可修改截止时间，其他作业暂不支持修改
          if homework.homework_type == "practice"
            group_settings.update_all(end_time: setting[:end_time])
          else
            group_settings.none_end.update_all(end_time: setting[:end_time])
          end
        end

        homework.end_time = homework.max_group_end_time
      end
    end
    if homework.end_time > Time.now && homework.homework_detail_manual.try(:comment_status) > 1
      homework.homework_detail_manual.update_attributes!(comment_status: 1)
    end

    homework.save!
    UpdateShixunWorkScoreJob.perform_later(homework.id)
    HomeworkCommonPushNotifyJob.perform_later(homework.id, publish_group_ids) if send_tiding
  end

  private
  def tip_exception(status = -1, message)
    raise Educoder::TipException.new(status, message)
  end
end