module AliyunVod::Service::Base
  def request(method, params)
    params = AliyunVod::Sign.format_params(params.compact) # 多层hash需要预先处理，保证值为string
    params[:Signature] = AliyunVod::Sign.generate(params, method: method.to_s.upcase)

    Rails.logger.info("[AliyunVod] request => method: #{method}, params: #{params}")

    response = Faraday.public_send(method, AliyunVod.base_url, params)
    result = JSON.parse(response.body)

    Rails.logger.info("[AliyunVod] response => status: #{response.status}, result: #{result}")

    if response.status != 200
      message =
        case result['Code']
        when 'InvalidFileName.Extension' then '不支持的视频格式'
        when 'IllegalCharacters' then '视频名称包含非法字符'
        else raise AliyunVod::Error, result['Message']
        end
      raise AliyunVod::Error, message if message.present?
    end

    result
  rescue => ex
    ::Util.logger_error(ex)
    raise AliyunVod::Error, ex.message
  end

  def base_params
    {
      AccessKeyId: AliyunVod.access_key_id,
      Format: 'JSON',
      Version: '2017-03-21',
      SignatureMethod: 'HMAC-SHA1',
      SignatureVersion: '1.0',
      SignatureNonce: signature_nonce,
      Timestamp: timestamp,
      UserData: user_data
    }
  end

  def user_data
    { MessageCallback: { CallbackURL: AliyunVod.callback_url } }
  end

  def timestamp
    Time.now.utc.iso8601
  end

  def signature_nonce
    chars = ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a
    chars.sample(16).join('')
  end
end