class ChangeIssueStatusByMessageJob < ApplicationJob
  queue_as :notify

  # Close, Closes, Closed, Closing, close, closes, closed, closing
  # Fix, Fixes, Fixed, Fixing, fix, fixes, fixed, fixing
  # Resolve, Resolves, Resolved, Resolving, resolve, resolves, resolved, resolving
  # Implement, Implements, Implemented, Implementing, implement, implements, implemented, implementing
  # 以上关键词后接 issue_id 例如：Closes #234 Closes #123, #245, #992


  def get_pm_issue_data(user, org, pm_project_id, issue_id)
    url = "#{EduSetting.get("pms_server_url")}/api/pms/#{org.login}/pmsProjectIssues/#{issue_id}?pmProjectId=#{pm_project_id}"

    headers = {
      'Cookie' => "autologin_trustie=#{Token.get_or_create_permanent_login_token(user, 'autologin')&.value}",
    }
    
    response = RestClient.get(url, headers)

    puts response.body
    return JSON.parse(response.body)["code"].to_i == 200
  rescue 
    return false
  end


  def perform(commitsha, project, user, tag_issue_id_content, status_id=1)
    Rails.logger.info "需要操作的issue_id内容为 #{tag_issue_id_content}"
    tag_issue_id_content = tag_issue_id_content.gsub(/\s+/, '')
    tag_issue_id_content.to_s.split(",").each do |tag_issue|
      issue_id = tag_issue.gsub('#', '')
      issue = project.issues.issue_issue.where(project_issues_index: issue_id).where.not(id: issue_id).take || Issue.issue_issue.find_by_id(issue_id)
      next unless issue.present? # issue不存在 跳过
      next if issue.project.present? && !issue.project.member?(user) # issue归属项目，用户没有修改issue的权限，跳过
      next if issue.pm_project_id.nil? && project.id.to_i != issue.project&.id.to_i
      next if issue.pm_project_id.present? && !get_pm_issue_data(user, project.owner, issue.pm_project_id, issue.id) # issue是组织下工作项，不具备组织的访问权限，跳过

      issue_project = issue.project || Project.new(id: 0, user_id: 0, name: 'pm_mm', identifier: 'pm_mm', is_public:true)
      if issue.pm_project_id.present?
        Api::Pm::Issues::UpdateService.call(issue_project, issue, {status_id: status_id}, user, "Project##{project.id}@#{commitsha}")
      else
        Api::V1::Issues::UpdateService.call(issue_project, issue, {status_id: status_id}, user, "Project##{project.id}@#{commitsha}")
      end
    end
  end
end