class Api::V1::Issues::Milestones::DetailIssuesService < ApplicationService 
  include ActiveModel::Model

  attr_reader :project, :category, :author_id, :assigner_id, :issue_tag_ids, :sort_by, :sort_direction, :current_user
  attr_accessor :queried_issues, :total_issues_count, :closed_issues_count, :opened_issues_count

  validates :category, inclusion: {in: %w(all opened closed), message: "请输入正确的Category"}
  validates :sort_by, inclusion: {in: ['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 :current_user, presence: true

  def initialize(project, milestone, params, current_user=nil)
    @project = project 
    @milestone = milestone
    @category = params[:category] || 'all'
    @author_id = params[:author_id]
    @assigner_id = params[:assigner_id]
    @issue_tag_ids = params[:issue_tag_ids].present? ? params[:issue_tag_ids].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? 
    begin
      issue_query_data 

      return {data: queried_issues, total_issues_count: @total_issues_count, closed_issues_count: @closed_issues_count, opened_issues_count: @opened_issues_count}
    rescue
      raise Error, "服务器错误，请联系系统管理员！"
    end
  end

  private 
  def issue_query_data
    issues = @milestone.issues.issue_issue

    # author_id 
    issues = issues.where(author_id: author_id) if author_id.present? 

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

    issues = issues.ransack(issue_tags_value_cont: issue_tag_ids.sort!.join(",")).result unless issue_tag_ids.blank?

    @total_issues_count = issues.distinct.size
    @closed_issues_count = issues.closed.distinct.size 
    @opened_issues_count = issues.opened.distinct.size

    case category 
    when 'closed'
      issues = issues.closed 
    when 'opened'
      issues = issues.opened
    end

    scope = issues.includes(:priority, :issue_status, :user, :show_assigners, :version, :show_issue_tags, :comment_journals).references(:assigners)

    scope = scope.reorder("#{sort_by} #{sort_direction}").distinct

    @queried_issues = scope
  end

end