class Api::V1::Issues::MilestonesController < Api::V1::BaseController 
  before_action :require_login, except: [:index, :show]
  before_action :require_public_and_member_above, only: [:index, :show]
  before_action :require_operate_above, only: [:create, :update, :destroy]
  before_action :load_milestone, only: [:show, :update, :destroy]

  # 里程碑列表
  def index 
    @milestones = @project.versions
    @milestones = @milestones.ransack(id_eq: params[:keyword]).result.or(@milestones.ransack(name_or_description_cont: params[:keyword]).result) if params[:keyword].present?
    @closed_milestone_count = @milestones.closed.size 
    @opening_milestone_count = @milestones.opening.size
    @milestones = params[:category] == "closed" ? @milestones.closed : @milestones.opening
    @milestones = @milestones.reorder("versions.#{sort_by} #{sort_direction}")
    if params[:only_name]
      @milestones = @milestones.select(:id, :name)
      @milestones = kaminary_select_paginate(@milestones)
    else 
      @milestones = @milestones.includes(:issues, :closed_issues, :opened_issues)
      @milestones = kaminari_paginate(@milestones)
    end
  end 

  def create 
    @milestone = @project.versions.new(milestone_params)
    if @milestone.save!
      render_ok 
    else 
      render_error(@milestone.errors.full_messages.join(","))
    end
  end

  # 里程碑详情
  def show 
    @object_result = Api::V1::Issues::Milestones::DetailIssuesService.call(@project, @milestone, query_params, current_user)
    @total_issues_count = @object_result[:total_issues_count]
    @opened_issues_count = @object_result[:opened_issues_count]
    @closed_issues_count = @object_result[:closed_issues_count]
    
    @issues = kaminari_paginate(@object_result[:data])
  end

  def update 
    @milestone.attributes = milestone_params 
    if @milestone.save! 
      render_ok 
    else 
      render_error(@milestone.errors.full_messages.join(","))
    end
  end

  def destroy 
    if @milestone.destroy! 
      render_ok 
    else 
      render_error("删除里程碑失败！")
    end
  end

  private 
  def milestone_params 
    params.permit(:name, :description, :effective_date)
  end

  def query_params 
    params.permit(:category, :author_id, :assigner_id, :sort_by, :sort_direction, :issue_tag_ids)
  end

  def load_milestone
    @milestone = @project.versions.find_by_id(params[:id])
    return render_not_found('里程碑不存在！') unless @milestone.present?
  end

  def sort_by 
    sort_by = params.fetch(:sort_by, "created_on")
    sort_by = Version.column_names.include?(sort_by) ? sort_by : "created_on"

    sort_by
  end

  def sort_direction
    sort_direction = params.fetch(:sort_direction, "desc").downcase
    sort_direction = %w(desc asc).include?(sort_direction) ? sort_direction : "desc"
    sort_direction
  end

end