class Api::Pm::IssueTagsController < Api::Pm::BaseController 

  def index 
    @issue_tags = IssueTag.pm_able
    if params[:organization_id].present?
      IssueTag.pm_org_init_data(params[:organization_id]) unless $redis_cache.hget("pm_org_init_issue_tags", params[:organization_id])
      @issue_tags = @issue_tags.where(organization_id: params[:organization_id]) 
    end 
    @issue_tags = @issue_tags.where(pm_project_id: params[:pm_project_id]) if params[:pm_project_id].present? 
    @issue_tags = @issue_tags.ransack(name_cont: params[:keyword]).result if params[:keyword].present?
    @issue_tags = @issue_tags.reorder("#{tag_sort_by} #{tag_sort_direction}")
    @issue_tags = kaminari_paginate(@issue_tags)
    render "api/v1/issues/issue_tags/index"
  end

  def create 
    return render_error("请输入正确的OrganizationID") unless Organization.exists?(id: issue_tag_create_params[:organization_id])
    return render_error("项目标记名称不能为空！") unless issue_tag_create_params[:name].present?
    @issue_tag = IssueTag.new(issue_tag_create_params.merge!(project_id: 0))
    if @issue_tag.save!
      render_ok 
    else 
      render_error("创建标记失败！")
    end
  end

  before_action :load_issue_tag, only: [:update, :destroy]

  def update 
    @issue_tag.attributes = issue_tag_update_params
    if @issue_tag.save! 
      render_ok 
    else 
      render_error("更新标记失败！")
    end
  end 
  
  def destroy 
    if @issue_tag.destroy! 
      render_ok
    else 
      render_error("删除标记失败！")
    end
  end


  private 
  def tag_sort_by
    sort_by = params.fetch(:sort_by, "created_at")
    sort_by = IssueTag.column_names.include?(sort_by) ? sort_by : "created_at"
    sort_by
  end

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

  def issue_tag_create_params 
    params.permit(:name, :description, :color, :pm_project_id, :organization_id)
  end

  def issue_tag_update_params 
    params.permit(:name, :description, :color)
  end

  def load_issue_tag 
    @issue_tag = IssueTag.pm_able.find_by_id(params[:id])
  end
end