class Admins::JobClassifiesController < Admins::BaseController

  def index
    @page = 'job_classifies'
    @data = JobClassify.root.includes(:childrens).order('position')
  end

  def children
    @page = 'job_classifies'
    @data = JobClassify.find(params[:id]).childrens.order('position')
    render layout: false
  end

  def change
    job_classify = JobClassify.find(params[:id])
    job_classify.parent_id = params[:parent_id] if params[:parent_id].present?
    job_classify.position = params[:position].to_i
    job_classify.save
    render_ok
  end

  def edit
    @job_classify = JobClassify.find(params[:id])
  end

  def update
    job_classify = JobClassify.find(params[:id])
    if job_classify.parent_id != 0
      # 如与其它子类重名，则迁移职位到新分类并删除掉其分类
      is_exist_some = JobClassify.where(name: params[:job_classify][:name]).where.not(id: job_classify.id).first
      if is_exist_some
        job_classify.jobs.update_all(job_classify_id: is_exist_some.id)
        job_classify.destroy
        @message = "已存在分类：#{is_exist_some.name}，新分类将迁移到：#{is_exist_some.parent.name}"
        return
      end
    end
    job_classify.update(name: params[:job_classify][:name])
  end

  def create
    parent_classify = JobClassify.find_or_initialize_by(name: params[:parent_name], parent_id: 0) do |d|
      d.position = JobClassify.root.order('position desc').first&.position.to_i + 1
    end
    ActiveRecord::Base.transaction do
      parent_classify.save!
      children_classify = JobClassify.find_or_initialize_by(name: params[:name]) do |d|
        d.position = parent_classify.childrens.order('position desc').first&.position.to_i + 1
      end

      children_classify.parent_id = parent_classify.id

      if children_classify.persisted?
        raise "#{children_classify.name}已存在"
      else
        children_classify.save!
      end
    end
  rescue => e
    render json: {message: e}, status: 403
  end

  def destroy
    @job_classify = JobClassify.find(params[:id])
  end
end
