class Api::Pm::SprintIssues::ListService < ApplicationService

  include ActiveModel::Model 

  attr_reader :category, :pm_project_id, :pm_issue_type, :assigner_id, :priority_id, :status_id, :keyword, :current_user
  attr_reader :status_ids, :pm_issue_types
  attr_reader :sort_by, :sort_direction
  attr_accessor :queried_issues

  validates :category, inclusion: { in: %w[linked unlink], message: '请输入正确的Category'}
  validates :sort_by, inclusion: { in: %w[issues.status_id issues.created_on issues.updated_on issue_priorities.position] , message: '请输入正确的SortBy'}, allow_blank: true
  validates :sort_direction, inclusion: { in: %w[asc desc], message: '请输入正确的SortDirection'}, allow_blank: true

  validates :pm_project_id, :current_user, presence: true

  def initialize(params, current_user = nil)
    @category = params[:category] || "unlink"
    @pm_project_id = params[:pm_project_id]
    @pm_issue_type = params[:pm_issue_type]
    @assigner_id = params[:assigner_id]
    @priority_id = params[:priority_id]
    @status_id = params[:status_id]
    @keyword = params[:keyword]
    @status_ids = params[:status_ids].present? ? params[:status_ids].split(',') : []
    @pm_issue_types = params[:pm_issue_types].present? ? params[:pm_issue_types].split(',') : []
    @sort_by = params[:sort_by].present? ?  params[:sort_by] : 'issues.updated_on'
    @sort_direction = (params[:sort_direction].present? ? params[:sort_direction] : 'desc').downcase
    @current_user = current_user
  end

  def call 
    raise Error, errors.full_messages.join(', ') unless valid? 

    issue_query_data

    @queried_issues
  end

  private
  def issue_query_data
     issues = @category == "unlink" ? Issue.where(pm_project_id: @pm_project_id, pm_sprint_id: [nil, 0]) : Issue.where(pm_project_id: @pm_project_id).where.not(pm_sprint_id: [nil, 0])

     issues = issues.where(pm_issue_type: @pm_issue_type) if @pm_issue_type.present?

     issues = issues.joins(:assigners).where(users: {id: @assigner_id}) if @assigner_id.present?

     issues = issues.where(priority_id: @priority_id) if @priority_id.present?

     issues = issues.where(status_id: @status_id) if @status_id.present? 

     # status_ids 
     issues = issues.where(status_id: @status_ids) unless @status_ids.blank?

     # pm_issue_types
     issues = issues.where(pm_issue_type: @pm_issue_types) unless @pm_issue_types.blank?

     issues = issues.ransack(subject_cont: @keyword).result if @keyword.present?

     scope = issues.includes(:priority, :issue_status, :user, :show_assigners, :show_issue_tags, :version, :comment_journals)
     scope = scope.reorder("#{sort_by} #{sort_direction}").distinct

     @queried_issues = scope
 
  end
end