
desc "导入导出issue、version、journal数据"
namespace :import_from_another_forge do

  def find_or_create_by(login)
    return nil unless login.present? 
    user = User.find_by(login: login)
    return user if user.present? 

    user = User.new(admin: false, login: login, mail: "#{login}@forge.com", nickname: login, platform: 'forge' , type: "User")
    user.password = "12345678"
    user.activate
    interactor = Gitea::RegisterInteractor.call({username: login, email: "#{login}@forge.com", password: "12345678"})
    gitea_user = interactor.result
    result = Gitea::User::GenerateTokenService.call(login, "12345678")
    user.gitea_token = result['sha1']
    user.gitea_uid = gitea_user[:body]['id']
    user.save! 
    UserExtension.create!(user_id: user.id) 

    return user 
  rescue 
    return nil
  end

  desc "导出数据"
  # 执行示例 bundle exec rake "import_from_another_forge:export[110]"
  # RAILS_ENV=production bundle exec rake "import_from_another_forge:export[110]"
  task :export, [:project_id] => :environment do |t, args|
    project_id = args.project_id
    project = Project.find_by_id project_id
    Axlsx::Package.new do |p|
      p.workbook.add_worksheet(:name => 'version') do |sheet|
        sheet.add_row ['id', 'name', 'description', 'effective_date', 'created_on', 'updated_on', 'status', 'creator','issues_count', 'closed_issues_count', 'percent']
        project.versions.each do |version|
          sheet.add_row [version.id, version.name, version.description, version.effective_date, version.created_on.strftime("%Y-%m-%d %H:%M:%S"), version.updated_on.strftime("%Y-%m-%d %H:%M:%S"), version.status, version.user.try(:login), version.issues_count, version.closed_issues_count, version.percent]
        end
      end
      p.workbook.add_worksheet(:name => 'issue') do |sheet|
        sheet.add_row ['id', 'project_issues_index', 'subject', 'description', 'creator', 'created_on', 'changer', 'updated_on', 'status_id', 'assigners', 'priority_id', 'issue_tags', 'version_id']
        project.issues.issue_issue.each do |issue|
          sheet.add_row [issue.id, issue.project_issues_index, issue.subject, issue.description, issue.user.try(:login), issue.created_on.strftime("%Y-%m-%d %H:%M:%S"), issue.changer.try(:login), issue.updated_on.strftime("%Y-%m-%d %H:%M:%S"), issue.status_id, issue.assigners.pluck(:login).join(","),issue.priority_id, issue.issue_tags.pluck(:name, :color).join(","), issue.fixed_version_id]
        end
      end
      issue_ids = project.issues.issue_issue
      p.workbook.add_worksheet(:name => 'journal') do |sheet|
        sheet.add_row ['id', 'journalized_type', 'journalized_id', 'creator', 'notes', 'created_on', 'parent_id', 'comments_count', 'reply_id', 'updated_on', 'operate_by']
        Journal.where(journalized_type: 'Issue', journalized_id: issue_ids).where.not(notes: nil).each do |journal|
          sheet.add_row [journal.id, journal.journalized_type, journal.journalized_id, journal.user.try(:login), journal.notes, journal.created_on.strftime("%Y-%m-%d %H:%M:%S"), journal.parent_id, journal.comments_count, journal.reply_id, journal.updated_on.strftime("%Y-%m-%d %H:%M:%S"), journal.operate_by]
        end
      end
      p.serialize('public/version_issue_journal_data.xlsx')
    end
  end


  # 执行示例 bundle exec rake "import_from_another_forge:import[filepath, 365, ceshi_org]"
  # RAILS_ENV=production bundle exec rake "import_from_another_forge:import[public/version_issue_journal_data.xlsx, 110]"
  task :import, [:attachment_uuid, :project_id] => :environment do |t, args| 
    attachment_uuid = args.attachment_uuid
    project_id = args.project_id
    a =Attachment.find_by(uuid: attachment_uuid)
    project = Project.find_by_id project_id 
    version_hash = {}
    issue_hash = {}
    journal_hash = {}
    ActiveRecord::Base.transaction do 
      doc = SimpleXlsxReader.open("#{Rails.root}/tmp/files/#{a.relative_path_filename}")
      doc.sheets.each do |sheet|
        case sheet.name
        when 'version'
          sheet.rows.each.with_index do |row, index|
            next if index == 0
            version = Version.new(project_id: project_id)
            version.name = row[1]
            version.description = row[2]
            version.effective_date = row[3]
            version.created_on = row[4]
            version.updated_on = row[5]
            version.status = row[6]
            version.user = find_or_create_by(row[7])
            version.issues_count = row[8].to_i
            version.closed_issues_count = row[9].to_i 
            version.percent = row[10].to_f 
            version.save!
            version_hash["#{row[0]}"] = version.id
          end
        when 'issue'
          sheet.rows.each.with_index do |row, index|
            next if index == 0
            issue = Issue.new(issue_classify: "issue", project_id: project_id, tracker_id: Tracker.first.id)
            issue.project_issues_index = row[1]
            issue.subject = row[2]
            issue.description = row[3]
            issue.user = find_or_create_by(row[4])
            issue.created_on = row[5]
            issue.changer = find_or_create_by(row[6])
            issue.updated_on = row[7]
            issue.status_id = row[8]
            if row[9].present?
              row[9].split(',').each do |a| 
                u = find_or_create_by(a)
                next unless u.present? 
                issue.assigners << u
              end
            end
            issue.priority_id = row[10]
            issue.issue_tags 
            if row[11].present? 
              row[11].split(',').each_slice(2).to_a.each do |t|
                tag = IssueTag.find_by(project_id: project_id, name: t[0])
                if tag.present? 
                  issue.issue_tags << tag
                else
                  tag = IssueTag.create(project_id: project_id, name: t[0], color: t[1])
                  issue.issue_tags << tag
                end
              end
            end
            issue.fixed_version_id = version_hash["#{row[12]}"]
            issue.save!
            issue_hash["#{row[0]}"] = issue.id
          end
        when 'journal'
          sheet.rows.each.with_index do |row, index|
            next if index == 0
            next if row[6].present? || row[8].present?
            journal = Journal.new
            journal.journalized_type = row[1]
            journal.journalized_id = issue_hash["#{row[2]}"]
            journal.user = find_or_create_by(row[3])
            journal.notes = row[4]
            journal.created_on = row[5]
            journal.updated_on = row[9]
            journal.parent_id = journal_hash["#{row[6]}"]
            journal.reply_id = journal_hash["#{row[8]}"]
            journal.save!
            journal_hash["#{row[0]}"] = journal.id
          end
        end
      end
    end
  end
    
  
end
