class TaskBanksController < ApplicationController
  before_action :require_login
  before_action :find_bank, :bank_visit_auth
  before_action :bank_visit_auth
  before_action :bank_admin, only: [:update]

  def show
    @bank_attachments = @bank.attachments
  end

  def update
    ActiveRecord::Base.transaction do
      begin
        @bank.update_attributes(gtask_bank_params)
        Attachment.associate_container(params[:attachment_ids], @bank.id, @bank.class) if params[:attachment_ids]
        normal_status(0, "更新成功")
      rescue Exception => e
        uid_logger(e.message)
        tip_exception(e.message)
        raise ActiveRecord::Rollback
      end
    end
  end

  private

  def find_bank
    @bank = GtaskBank.find_by!(id: params[:id])
  end

  def bank_admin
    tip_exception(403, "无权限") unless @bank.user_id == current_user.id || current_user.admin_or_business?
  end

  def gtask_bank_params
    tip_exception("name参数不能为空") if params[:gtask_bank][:name].blank?
    tip_exception("description参数不能为空") if params[:gtask_bank][:description].blank?
    if @bank.task_type == 2
      tip_exception("base_on_project参数不能为空") if params[:gtask_bank][:base_on_project].nil?
      tip_exception("min_num参数不能为空") if params[:gtask_bank][:min_num].blank?
      tip_exception("max_num参数不能为空") if params[:gtask_bank][:max_num].blank?
      tip_exception("最小人数不能小于1") if params[:gtask_bank][:min_num].to_i < 1
      tip_exception("最大人数不能小于最小人数") if params[:gtask_bank][:max_num].to_i < params[:gtask_bank][:min_num].to_i
    end
    if @bank.task_type == 1
      params.require(:gtask_bank).permit(:name, :description)
    else
      params.require(:gtask_bank).permit(:name, :description, :min_num, :max_num, :base_on_project)
    end
  end
end
