class Weapps::AttendancesController < ApplicationController
  before_action :require_login
  before_action :find_course, only: [:create, :index, :student_attendances, :history_attendances]
  before_action :find_attendance, except: [:create, :index, :student_attendances, :history_attendances]
  before_action :user_course_identity
  before_action :teacher_allowed, only: [:create]
  before_action :edit_auth, only: [:update, :destroy, :end]

  def create
    ActiveRecord::Base.transaction do
      attendance = @course.course_attendances.create!(create_params.merge(user_id: current_user.id))
      group_ids = params[:group_ids] || []
      group_ids = group_ids.blank? ? @course.charge_group_ids(current_user) : @course.charge_group_ids(current_user) & params[:group_ids].map(&:to_i)
      if group_ids.blank? || (params[:group_ids].blank? && @course.course_groups.where(id: group_ids).count == @course.course_groups.count)
        @course.course_attendance_groups.create!(course_group_id: 0, course_attendance: attendance)
        CreateStudentAttendanceRecordJob.perform_now(attendance.id, [0])
      else
        # group_ids = @course.charge_group_ids(current_user) & params[:group_ids].map(&:to_i)
        group_ids.each do |group_id|
          @course.course_attendance_groups.create!(course_group_id: group_id, course_attendance: attendance)
        end
        CreateStudentAttendanceRecordJob.perform_now(attendance.id, group_ids)
      end
      render_ok({attendance_id: attendance.id})
    end
  end

  def index
    tip_exception(403) if @user_course_identity >= Course::STUDENT
    current_date = Date.current
    current_end_time = Time.current.strftime("%H:%M:%S")
    @current_attendance = @course.course_attendances.where("attendance_date > '#{current_date}' or (attendance_date = '#{current_date}' and end_time > '#{current_end_time}')")
                            .order("attendance_date asc, start_time asc")

    all_attendances = @course.course_attendances.where("attendance_date < '#{current_date}' or (attendance_date = '#{current_date}' and end_time < '#{current_end_time}')")
    @all_member_attendances = CourseMemberAttendance.where(course_attendance_id: all_attendances)
    if params[:group_id].present?
      all_attendances = all_attendances.joins(:course_attendance_groups).where(course_attendance_groups: {course_group_id: [params[:group_id], 0]})
      @all_member_attendances = @all_member_attendances.joins(:course_member).where(course_members: {course_group_id: params[:group_id]})
    end

    all_attendances = all_attendances.order("attendance_date desc, start_time desc")

    data = AttendanceStatisticsService.call all_attendances, @all_member_attendances
    @all_history_count = data[:all_history_count]
    @history_attendances = data[:history_attendances]
    @avg_normal_rate = data[:avg_normal_rate]
    @avg_absence_rate = data[:avg_absence_rate]
    @avg_leave_rate = data[:avg_leave_rate]
  end

  def student_attendances
    tip_exception(403) if @user_course_identity > Course::STUDENT
    # tip_exception("学生身份的签到列表") if @user_course_identity != Course::STUDENT
    member = @course.students.find_by(user_id: current_user.id)
    if member.present?
      current_date = Date.current
      current_end_time = Time.current.strftime("%H:%M:%S")

      # 先算出该学生所在分班的签到id
      # 分班id为0 表示签到不限制分班
      group_ids = [member&.course_group_id.to_i, 0]
      all_attendance_ids = @course.course_attendance_groups.where(course_group_id: group_ids).pluck(:course_attendance_id)

      # 学生的历史签到只统计加入课堂后创建的签到
      history_attendance_ids = member.course_member_attendances.where(course_id: @course.id).pluck(:course_attendance_id)

      @history_attendances = @course.course_attendances.where(id: history_attendance_ids.uniq).
        where("attendance_date < '#{current_date}' or (attendance_date = '#{current_date}' and end_time < '#{current_end_time}')").order("id desc")
      @current_attendances = @course.course_attendances.where(id: all_attendance_ids.uniq).
        where("attendance_date = '#{current_date}' and start_time <= '#{current_end_time}' and end_time > '#{current_end_time}'")
      @history_count = @history_attendances.size

      # 当前签到如果存在快捷签到，则直接签到（不在这里处理）
      # quick_attendances = @current_attendances.where(mode: "QUICK")
      # if quick_attendances.present?
      #   student_direct_attendance quick_attendances, member
      # end

      student_attendance_ids = @history_attendances.pluck(:id)
      student_attendance_ids += @current_attendances.present? ? @current_attendances.pluck(:id) : []

      if student_attendance_ids.uniq.blank?
        @normal_count = 0
        @leave_count = 0
        @absence_count = 0
      else
        @normal_count = @course.course_member_attendances.where(course_member_id: member&.id, course_attendance_id: student_attendance_ids, attendance_status: "NORMAL").size
        @leave_count = @course.course_member_attendances.where(course_member_id: member&.id, course_attendance_id: student_attendance_ids, attendance_status: "LEAVE").size
        # 旷课只统计历史签到的
        @absence_count = @course.course_member_attendances.where(course_member_id: member&.id, course_attendance_id: @history_attendances.pluck(:id), attendance_status: "ABSENCE").size
      end

      @all_history_count = @history_attendances.size
      @history_attendances = paginate @history_attendances.includes(:course_member_attendances)
    end
  end

  def show
    @normal_count = @attendance.normal_count
    @leave_count = @attendance.leave_count
    @absence_count = @attendance.absence_count
    @all_count = @attendance.course_member_attendances.size

    a_end_time = "#{@attendance.attendance_date} #{@attendance.end_time}".to_time

    @_is_current_attendance = Time.current < a_end_time

    if @attendance.course_attendance_groups.first&.course_group_id.to_i == 0
      @group_ids = @course.course_groups.pluck(:id) + [0]
    else
      @group_ids = @attendance.course_attendance_groups.pluck(:course_group_id)
    end

    @groups = @course.course_groups.where(id: @group_ids)
    @course_members = @course.students if @_is_current_attendance

    @all_attendances = @attendance.course_member_attendances

    @user = @attendance.user
  end

  def update
    @attendance.update!(name: params[:name])
    render_ok
  end

  def destroy
    @attendance.destroy!
    render_ok
  end

  def history_attendances
    current_date = Date.current
    current_end_time = Time.current.strftime("%H:%M:%S")

    @history_attendances = @course.course_attendances.where("attendance_date < '#{current_date}' or
                            (attendance_date = '#{current_date}' and end_time < '#{current_end_time}')").order("id desc")
    @all_history_count = @history_attendances.size
    @history_attendances = paginate @history_attendances.includes(:course_member_attendances)
  end

  def end
    a_end_time = "#{@attendance.attendance_date} #{@attendance.end_time}".to_time
    tip_exception("该签到已截止") if a_end_time < Time.now

    a_start_time = "#{@attendance.attendance_date} #{@attendance.start_time}".to_time
    if a_start_time > Time.now
      @attendance.update!(end_time: Time.current, start_time: Time.current, attendance_date: Date.current)
    else
      @attendance.update!(end_time: Time.current)
    end
    render_ok
  end

  private
  def create_params
    params.permit(:name, :mode, :attendance_date, :start_time, :end_time)
  end

  def find_attendance
    @attendance = CourseAttendance.find params[:id]
    @course = @attendance.course
  end

  def edit_auth
    tip_exception(403, "") unless @user_course_identity < Course::PROFESSOR || @attendance.user_id == current_user.id
  end

  def student_direct_attendance quick_attendances, member
    quick_attendances.each do |attendance|
      current_attendance = attendance.course_member_attendances.find_by(user_id: member.user_id)
      if current_attendance.present?
        current_attendance.update!(attendance_status: "NORMAL", attendance_mode: "QUICK")
      else
        attendance.course_member_attendances.create!(course_member_id: member.id, user_id: member.user_id, course_id: attendance.course_id,
                                                     course_group_id: member.course_group_id, attendance_status: "NORMAL", attendance_mode: "QUICK")
      end
    end
  end
end