

namespace :upgrade_issue_generate_data do
  # 执行示例  bundle exec rake upgrade_issue_generate_data:project_issues_index
  # 线上环境执行示例  RAILS_ENV=production bundle exec rake upgrade_issue_generate_data:project_issues_index
  desc "upgrade_issue_generate_data: fix issue project_issues_index"

  task project_issues_index: :environment do
    puts "____________fix start________________"

    Issue.issue_issue.update_all(project_issues_index: nil)
    count = 0
    Issue.issue_issue.where(project_issues_index: nil).group(:project_id).count.each do |pid, count| 
      p = Project.find_by_id(pid)
      next if p.nil?
      issues = p.issues.order(created_on: :asc)
      issues.find_each.with_index do |issue, index|
        count += 1
        issue.update_column(:project_issues_index, index+1)
      end
    end
    puts "____________fix end_______total:#{count}_________"
  end

  # 执行示例  bundle exec rake upgrade_issue_generate_data:project_init_issue_tags_and_status
  # 线上环境执行示例  RAILS_ENV=production bundle exec rake upgrade_issue_generate_data:project_init_issue_tags_and_status
  desc "upgrade_issue_generate_data: fix project init issue_tags"

  task project_init_issue_tags_and_status: :environment do
    puts "____________fix start________________"
    IssuePriority.init_data
    IssueStatus.init_data
    IssueTag.order(created_at: :desc).find_each do |it| 
      it.reset_counter_field
    end
    IssueTag.where(user_id: nil).destroy_all
    count = 0
    Project.order(created_on: :desc).find_each do |project| 
      count += 1
      IssueTag.init_data(project.id)
    end
    puts "____________fix end____total:#{count}__________"
  end

  # 执行示例  bundle exec rake upgrade_issue_generate_data:build_assigners_and_participants
  # 线上环境执行示例  RAILS_ENV=production bundle exec rake upgrade_issue_generate_data:build_assigners_and_participants
  desc "upgrade_issue_generate_data: fix issue assigners and participants"

  task build_assigners_and_participants: :environment do
    puts "____________fix start________________"
    count = 0
    Issue.order(created_on: :desc).find_each do |issue| 
      count += 1
      issue.issue_assigners.find_or_create_by(assigner_id: issue.assigned_to_id)
      issue.issue_participants.find_or_create_by(participant_id: issue.assigned_to_id, participant_type: 'assigned')
      issue.issue_participants.find_or_create_by(participant_id: issue.author_id, participant_type: 'authored')
    end
    puts "____________fix end____total:#{count}__________"
  end
end