class JobsController < ApplicationController
  before_action :require_login, except: [:index, :show]
  before_action :authorization_manage, except: [:index, :show, :apply]

  def index
    @jobs = Job.published.includes(:user)

    if params[:q].present?
      @jobs = @jobs.where("name like :q OR company like :q", q: "%#{params[:q]}%")
    end

    if params[:city].present?
      @jobs = @jobs.where(city: params[:city])
    end

    @jobs_count = @jobs.count
    @jobs = @jobs.order("updated_at desc").page(params[:page] || 1).per(params[:per_page] || 15)
  end

  def create
    job = current_user.jobs.build(job_params)
    job.company = current_user.school_name
    
    ActiveRecord::Base.transaction do
      job_classify = save_job_classify(params)

      job.job_classify_id = job_classify.id
      job.save!
      render_ok
    end
  rescue Exception => e
    uid_logger(e.message)
    tip_exception(e.message)
  end

  def update
    job = current_user.jobs.find(params[:id])
   
    ActiveRecord::Base.transaction do
      job_classify = save_job_classify(params)
      job.assign_attributes(job_params)
      job.job_classify_id = job_classify.id
      is_changed = job.changed?
      job.state = "drafted" if is_changed

      job.save!
      render_ok({changed: is_changed})
    end
  rescue Exception => e
    uid_logger(e.message)
    tip_exception(e.message)
  end

  def change
    job = current_user.jobs.find(params[:id])

    if job.send("may_#{params[:change]}?") && ["off", "online", "del"].include?(params[:change])
      job.send("#{params[:change]}!")
      render_ok
    else
      render_error("操作失败，当前状态#{job.state}")
    end
  end

  # 应聘职位
  def apply
    @job = Job.published.find_by(id: params[:id])
    return normal_status(-2, "该职位已下线") if @job.nil?
    return normal_status(-2, "请先完善你的简历") if current_user.resume.nil?

    apply_job = ApplyJob.find_or_initialize_by(user_id: current_user.id, job_id: @job.id)

    if apply_job.persisted?
      return normal_status(-2, "您已经提交过了，请耐心等待")
    else
      if apply_job.save
        render_ok
      else
        render_error apply_job.errors.full_messages.first
      end
    end

    
  end

 # 查看应聘人员
  def applyed_users
    job = current_user.jobs.find(params[:id])
    @applyed_users_count = job.apply_jobs.count
    @applyed_users = job.apply_jobs.includes([user: :resume], :job).page(params[:page] || 1).per(params[:per_page] || 15).order("created_at desc")
  end

  def show
    @job = Job.find(params[:id])
  end



  private

  def job_params
    params.require(:job).permit(:name, :num, :city, :address, :job_category, :min_salary, :max_salary, :education, :work_year, :description, :introduce)
  end

  def authorization_manage
    if current_user.identity == '学生'
      render json: { status: 403, message: '您没有权限进行该操作' }
    elsif current_user.pro_certification? == false
      render json: { status: 403, message: '请先进行职业认证' }
    end
  end

  def save_job_classify(params)
    job_classify = JobClassify.find_or_initialize_by(name: params[:job][:job_classify]) do |d|
      d.position = 1
    end
    unless job_classify.persisted?
      parent_classify = JobClassify.find_or_initialize_by(name: params[:job][:job_classify_root], parent_id: 0) do |d|
        d.position = JobClassify.root.order('position desc').first.position + 1
      end
      parent_classify.save!
      job_classify.parent_id = parent_classify.id
      job_classify.save!
    end
    job_classify
  end
end
