class Admins::ImportUserFromExcelService < ApplicationService 
  Error = Class.new(StandardError)

  attr_reader :file, :result

  def initialize(file)
    @file = file 
    @result = { success: 0, fail: [] }
  end

  def call 
    raise Error, '文件不存在' if file.blank?
    excel = Admins::NewImportUserFromExcel.new(file)

    excel.read_each(&method(:save_user))
    PlatformStatistic.data.increment!(:users_count, result[:success])

    result 
  rescue ApplicationImport::Error => ex 
    raise Error, ex.message
  end

  private 
  def save_user(data)
    user = find_user(data)
    if user.blank? 
      create_user(data)
      result[:success] +=1
    else 
      fail_data = data.as_json
      fail_data[:data] = fail_data.values.join(",")
      fail_data[:message] = '用户已存在'
      result[:fail] << fail_data  
    end

  rescue Exception => ex 
    fail_data = data.as_json
    fail_data[:data] = fail_data.values.join(",")
    fail_data[:message] = ex.message
    result[:fail] << fail_data  
  end

  def create_user(data)
    ActiveRecord::Base.transaction do 
      username = data.login&.gsub(/\s+/, "")
      phone = data.phone&.gsub(/\s+/, "")
      password = data.password
      nickname = data.nickname&.gsub(/\s+/, "")
      email = "#{username}@example.org"
      raise Error, "无法使用以下关键词：#{username}，请重新命名" if ReversedKeyword.check_exists?(data.login)
      Register::RemoteForm.new({username: username, phone: phone, email: email, password: password, platform: 'forge'}).validate!
      user = User.new(admin: false, login: username, phone: phone, mail: email, nickname: nickname, platform: 'forge' , type: "User")
      user.password = password
      user.activate
      raise Error, user.errors.full_messages.join(",") unless user.valid?
      interactor = Gitea::RegisterInteractor.call({username: username, email: email, password: password})
      if interactor.success?
        gitea_user = interactor.result
        result = Gitea::User::GenerateTokenService.call(username, password)
        user.gitea_token = result['sha1']
        user.gitea_uid = gitea_user[:body]['id']
        UserExtension.create!(user_id: user.id) if user.save! 
      else 
        raise interactor.error, 'gitea user create error' 
      end

      Entity.create!(user_id: user.id, entity_type: 1)

      user
    end
  end

  def find_user(data)
    User.find_by(login: data.login)
  end
end