namespace :import_educoder_cource_repo do
  desc "sync outer repository to gitlink"
  task done: :environment do
    data = ImportRepo.all
    if ENV['name'].present?
      data = data.where("name like '%#{ENV['name']}%'")
    end
    data.each_with_index do |row, index|
      puts index
      root_repo = Repository.find_by(mirror_url: row.git_url)
      next if root_repo.blank?
      root_project = root_repo.project

      begin
        user = User.find_by(phone: row.myshixun_user_phone) || User.find_by(mail: row.myshixun_user_mail)
        unless user.present?
          username = generate_user_login('p')
          email = row.myshixun_user_mail.blank? ? "#{username}@gitlink.org.cn" : row.myshixun_user_mail
          phone = row.myshixun_user_phone
          password = "a12345678"
          user = User.new(nickname: row.myshixun_user_name, login: username, mail: email, password: password, type: 'User', phone: phone)
          interactor = Gitea::RegisterInteractor.call({ username: username, email: email, password: password })
          gitea_user = interactor.result
          result = Gitea::User::GenerateTokenService.call(username, password)
          user.gitea_token = result['sha1']
          user.gitea_uid = gitea_user[:body]['id']
          user.save!
          UserExtension.create!(user_id: user.id)
          puts "import_user batch success: phone #{phone} email: #{email}"
        end

        repo = Repository.find_by(mirror_url: row.myshixun_git_url)
        next if repo.present? && repo.project.present?
        mirror_params = {
          user_id: user.id,
          auth_username: "xxqfamous@gmail.com",
          auth_password: "eHhxMTIzNDU2Nzg5NTIx",
          name: root_project.name,
          description: root_project.description,
          repository_name: root_project.identifier,
          project_category_id: root_project.project_category_id,
          project_language_id: root_project.project_language_id,
          clone_addr: row.myshixun_git_url
        }
        Projects::MigrateService.call(user, mirror_params)

        puts "sync outer repository to gitlink Success repo: #{row.myshixun_git_url}"
      rescue Exception => e
        puts "sync outer repository to gitlink Error repo: #{row.myshixun_git_url}, error:#{e}"
      end
    end
  end

  desc "batch forked project"
  task forked: :environment do
    data =ImportRepo.all
    if ENV['name'].present?
      data = data.where("name like '%#{ENV['name']}%'")
    end
    puts data.to_sql
    data.each_with_index do |row, index|
      begin
        puts index
        user = User.find_by(phone: row.myshixun_user_phone) || User.find_by(mail: row.myshixun_user_mail)
        next if user.blank?
        root_repo = Repository.find_by(mirror_url: row.git_url)
        next if root_repo.blank?
        root_project = root_repo.project
        repo = Repository.find_by(mirror_url: row.myshixun_git_url)
        # 学员项目未导入就跳过
        next if repo.blank?
        # 已绑定的跳过
        next if repo.project.forked_from_project_id.present?
        # 绑定fork关系
        ForkUser.create(project_id: root_project.id, fork_project_id: repo.project.id, user_id: repo.project.user_id)
        # 处理时间防止列表刷屏
        new_date = root_project.created_on > Time.now - 30.days ? Time.now - 1.years + rand(5..90).day + rand(5..60).hour : root_project.created_on
        root_project.update_columns(created_on: new_date, updated_on: new_date, forked_count: (root_project.forked_count.to_i + 1))
        # fork时间同样处理在创建时间之后
        new_date2 = new_date + rand(5..50).day + rand(5..30).hour
        repo.project.update_columns(created_on: new_date2, updated_on: new_date2, forked_from_project_id: root_project.id)
        puts "forked project success username: #{user.id}:#{repo.project.id}"
      rescue Exception => e
        puts "forked project error username: #{username}"
      end
    end
  end

  # 生成邀请码
  CODES = %W(0 1 2 3 4 5 6 7 8 9)
  def generate_user_login type
    code = CODES.sample(8).join
    code = type + code.to_s
    return generate_user_login(type) if User.where(login: code).present?
    code
  end
end