class StagesController < ApplicationController
  before_action :require_login, :check_auth, except: [:index]
  before_action :find_subject, only: [:create, :index]
  before_action :find_stage, only: [:update, :destroy, :edit, :up_position, :down_position]
  before_action :allowed, except: [:index]

  def index
    @user = current_user
    @stages = @subject.stages.includes(:shixuns)
    @myshixuns = @user.myshixuns.where(shixun_id: @subject.stage_shixuns.pluck(:shixun_id))
  end

  def create
    ActiveRecord::Base.transaction do
      begin
        @stage = Stage.new(stage_params)
        @stage.subject_id = @subject.id
        @stage.user_id = current_user.id
        @stage.position = @subject.stages.count + 1
        @stage.save!
        unless params[:shixun_id].blank?
          shixuns = Shixun.where(id: params[:shixun_id]).order("field(id, #{params[:shixun_id].join(",")})")
          shixuns.each do |shixun|
            StageShixun.create!(stage_id: @stage.id, subject_id: @subject.id, shixun_id: shixun.id, position: @stage.stage_shixuns.count + 1)
          end
        end
        @subject.update_attributes(updated_at: Time.now)
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception("章节创建失败")
        raise ActiveRecord::Rollback
      end
    end
  end

  def edit

  end

  def update
    ActiveRecord::Base.transaction do
      begin
        @stage.update_attributes!(stage_params)
        @stage.stage_shixuns.destroy_all
        unless params[:shixun_id].blank?
          params[:shixun_id].each do |shixun_id|
            shixun = Shixun.where(id: shixun_id).first
            @stage.stage_shixuns.create!(subject_id: @subject.id, shixun_id: shixun.id, position: @stage.stage_shixuns.count + 1) if shixun.present?
          end
        end
        @subject.update_attributes(updated_at: Time.now)
      rescue Exception => e
        uid_logger_error(e.message)
        tip_exception(e.message)
        raise ActiveRecord::Rollback
      end
    end
  end

  def destroy
    ActiveRecord::Base.transaction do
      @subject.stages.where("position > ?", @stage.position).update_all("position = position - 1")
      @stage.destroy
      @status = 1
    end
  end

  def up_position
    ActiveRecord::Base.transaction do
      begin
        position = @stage.position
        tip_exception("第一章不能向上移动") if @stage.position == 1
        pre_stage = @subject.stages.where(position: position - 1).first
        pre_stage.update_attributes(position: position)
        @stage.update_attributes(position: position - 1)
      rescue Exception => e
        uid_logger("stage up failed: #{e.message}")
        raise ActiveRecord::Rollback
      end
    end
  end

  def down_position
    ActiveRecord::Base.transaction do
      begin
        position = @stage.position
        rails "最后一章不能向下移动" if @stage.position == @subject.stages.count
        next_stage = @subject.stages.where(position: position + 1).first
        next_stage.update_attributes(position: position)
        @stage.update_attributes(position: position + 1)
      rescue Exception => e
        uid_logger("stage up failed: #{e.message}")
        raise ActiveRecord::Rollback
      end
    end
  end

  private
  def stage_params
    tip_exception("章节名称不能为空") if params[:name].blank?
    params.require(:stage).permit(:name, :description)
  end

  def find_subject
    @subject = Subject.find_by!(id: params[:subject_id])
  end

  def find_stage
    @stage = Stage.find_by!(id: params[:id])
    @subject = @stage.subject
  end

  def allowed
    unless current_user.manager_of_subject?(@subject)
      tip_exception("403", "")
    end
  end
end
