namespace :import_user do
  desc "import_user batch"
  task done: :environment do
    doc = SimpleXlsxReader.open("#{Rails.root}/public/import_user.xlsx")
    data = doc.sheets.first.rows
    num = 0
    data.each_with_index do |row, index|
      next if index == 0
      begin
        puts "index=====#{index}, mail: #{row[0]} phone: #{row[1]}"
        user = User.find_by(mail: row[0])
        user = User.find_by(phone: row[1]) unless user.present?
        if user.present?
          num += 1
        else
          username = generate_user_login('p')
          email = row[0]
          email = "#{username}@example.org" if email.blank?
          phone = row[1]
          company_name = row[3]
          user_type = row[4].to_s =="0" ? 3 : 4
          created_on = row[5].to_s
          password = "abc11111111"
          user = User.new(nickname: row[2], login: username, mail: email, password: password, type: 'User', phone: phone, company_name: company_name)
          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.user_type = user_type if company_name.present? && company_name.include?("大学")
          user.created_on = created_on if created_on.present?
          user.updated_on = created_on if created_on.present?
          user.save!
          UserExtension.create!(user_id: user.id)
          puts "import_user batch success: #{row[5]} username: #{row[0]}"
        end
      rescue Exception => e
        puts "import_user batch error: #{row[5]} username: #{row[0]}, #{e.message}"
      end
    end
    puts "import_user user.present?: #{num}"
  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