class CommitLogsController < ApplicationController

  def create
    tip_exception "未认证" unless params[:token].to_s == "7917908927b6f1b792f2027a08a8b24a2de42c1692c2fd45da0dee5cf90a5af5"
    ref = params[:ref]
    user_name = params[:pusher][:login]
    user_mail = params[:pusher][:email]
    user = User.find_by(mail: user_mail)
    user = User.find_by(login: user_name) if user.blank?

    repository_id = params[:repository][:id]
    repository_name = params[:repository][:name]
    repository_full_name = params[:repository][:full_name]
    owner_name = repository_full_name.split("/")[0]
    owner = User.find_by(login: owner_name)
    project = Project.where(identifier: repository_name).where(user_id: owner&.id)&.first
    project = Project.where(identifier: repository_name).where(gpid: repository_id)&.first if project.blank?
    # project.update_column(:updated_on, Time.now) if project.present?
    params[:commits].each do |commit|
      commit_id = commit[:id]
      message = commit[:message]
      commit_log = CommitLog.create(user: user, project: project, repository_id: repository_id,
                       name: repository_name, full_name: repository_full_name,
                       ref: ref, commit_id: commit_id, message: message)
      commit_log.project_trends.create(user_id: user.id, project_id: project&.id, action_type: "create") if user.id !=2
      # 统计数据新增
      CacheAsyncSetJob.perform_later("project_common_service", {commits: 1}, project.id)

      commit_user = User.find_by(mail: commit[:committer][:email]) rescue nil 
      commit_user = User.find_by(login: commit[:committer][:name]) if commit_user.blank? rescue nil
      next if commit_user.blank?

      # 触发变更issue状态的job
      close_issue_content = message.to_s.scan(/\b(Close|Closes|Closed|Closing|close|closes|closed|closing)\s*(#\d+(,\s*#\d+)*)?\b/)
      ChangeIssueStatusByMessageJob.perform_later(commit_id, project, commit_user, close_issue_content[0][1], 5) if close_issue_content[0].present? && close_issue_content[0][1].present?
      solve_issue_content = message.to_s.scan(/\b(Fix|Fixes|Fixed|Fixing|fix|fixes|fixed|fixing|Resolve|Resolves|Resolved|Resolving|resolve|resolves|resolved|resolving|Implement|Implements|Implemented|Implementing|implement|implements|implemented|implementing)\s*(#\d+(,\s*#\d+)*)?\b/)
      ChangeIssueStatusByMessageJob.perform_later(commit_id, project, commit_user, solve_issue_content[0][1], 3) if solve_issue_content[0].present? && solve_issue_content[0][1].present?
    end
    # c
    if project.present?
      if repository_full_name.to_s.include?("openkylin")
        project.update_column(:updated_on, Time.now - rand(1..100).minutes)
      else
        project.update_column(:updated_on, Time.now)
      end
    end
  end
end
