module Api::V1::Issues::Concerns::Checkable 

  def check_issue_status(status_id)
    raise ApplicationService::Error, "IssueStatus不存在！" unless IssueStatus.find_by_id(status_id).present?
  end

  def check_issue_priority(priority_id)
    raise ApplicationService::Error, "IssuePriority不存在！" unless IssuePriority.find_by_id(priority_id).present? 
  end

  def check_milestone(milestone_id)
    raise ApplicationService::Error, "Milestone不存在！" unless Version.find_by_id(milestone_id).present?
  end

  def check_root_issue(issue, root_id)
    raise ApplicationService::Error, "父工作项与当前工作项已存在父子关系！" if Issue.full_children_issues(issue).map{|i| i.id}.include?(root_id)
  end

  def check_issue_tags(issue_tag_ids)
    raise ApplicationService::Error, "请输入正确的标记ID数组！" unless issue_tag_ids.is_a?(Array)
    raise ApplicationService::Error, "最多可选择3个标记" if issue_tag_ids.size > 3
    issue_tag_ids.each do |tid|
      raise ApplicationService::Error, "请输入正确的标记ID！" unless IssueTag.exists?(id: tid)
    end
  end

  def check_assigners(assigner_ids)
    raise ApplicationService::Error, "请输入正确的负责人ID数组！" unless assigner_ids.is_a?(Array)
    raise ApplicationService::Error, "最多可选择5个负责人" if assigner_ids.size > 5
    assigner_ids.each do |aid|
      raise ApplicationService::Error, "请输入正确的负责人ID！" unless User.exists?(id: aid)
    end 
  end

  def check_attachments (attachment_ids)
    raise ApplicationService::Error, "请输入正确的附件ID数组！" unless attachment_ids.is_a?(Array)
    attachment_ids.each do |aid|
      raise ApplicationService::Error, "请输入正确的附件ID！" unless Attachment.where_id_or_uuid(aid).exists?
    end
  end

  def check_atme_receivers(receivers_login)
    raise ApplicationService::Error, "请输入正确的用户标识数组！" unless receivers_login.is_a?(Array)
    receivers_login.each do |rlogin|
      raise ApplicationService::Error, "请输入正确的用户标识！" unless User.exists?(login: rlogin)
    end 
  end

  def check_parent_journal(parent_id)
    raise ApplicationService::Error, "ParentJournal不存在！" unless Journal.find_by_id(parent_id).present? 
  end

  def check_blockchain_token_num(user_id, project_id, blockchain_token_num, now_blockchain_token_num=0)
    return if project_id.zero?
    left_blockchain_token_num = Blockchain::BalanceQueryOneProject.call({"user_id": user_id, "project_id": project_id}) rescue 0
    raise ApplicationService::Error, "用户Token不足。" if blockchain_token_num.to_i > (left_blockchain_token_num+now_blockchain_token_num).to_i
  end
end
