class Cooperative::BaseController < ApplicationController
  include Base::PaginateHelper
  include Cooperative::RenderHelper
  include Base::ErrorRescueHandler

  layout 'cooperative'

  skip_before_action :verify_authenticity_token

  before_action :laboratory_exist!, :require_login, :require_cooperative_manager!

  after_action :rebind_event_if_ajax_render_partial

  helper_method :current_laboratory, :current_setting_or_default

  private

  def current_laboratory
    @_current_laboratory ||= (Laboratory.find_by_subdomain(request.subdomain) || Laboratory.first)
    # @_current_laboratory ||= Laboratory.find 1
  end

  def current_setting_or_default(name)
    current_laboratory.public_send(name) || default_setting.public_send(name)
  end

  def laboratory_exist!
    return if current_laboratory.present?

    redirect_to '/403'
  end

  def require_login
    return if User.current.logged?

    redirect_to "/login?back_url=#{CGI::escape(request.fullpath)}"
  end

  def require_cooperative_manager!
    return if current_user.blank? || !current_user.logged?
    return if current_user.admin_or_business?
    return if current_laboratory.laboratory_users.exists?(user_id: current_user.id)

    render_forbidden
  end

  # 触发after ajax render partial hooks，执行一些因为局部刷新后失效的绑定事件
  def rebind_event_if_ajax_render_partial
    return if request.format.symbol != :js
    return if response.content_type != 'text/javascript'

    path = Rails.root.join('app/views/cooperative/shared/after_render_js_hook.js.erb')
    return unless File.exists?(path)

    append_js = ERB.new(File.open(path).read).result
    response.body += append_js
  end

end