/**
 * 仅包装 Page，向页面 data 注入 staticUrl（供 wxml {{staticUrl}}）
 * 禁止包装 Component：会破坏 Vant 等第三方组件注册，表现为 wx://not-found / 白屏
 */
const env = require('../config/env.js')

function mergeStaticData(options) {
  if (!options) options = {}
  const data = options.data || {}
  if (typeof data === 'function') {
    const orig = data
    options.data = function () {
      const d = orig.call(this) || {}
      if (d.staticUrl == null) d.staticUrl = env.static_url
      return d
    }
  } else {
    if (data.staticUrl == null) data.staticUrl = env.static_url
    options.data = data
  }
  return options
}

function install() {
  if (typeof Page !== 'function' || Page.__staticUrlPatched) return
  const rawPage = Page
  function PatchedPage(options) {
    return rawPage(mergeStaticData(options))
  }
  PatchedPage.__staticUrlPatched = true
  // 保留原生静态属性
  try {
    Object.keys(rawPage).forEach(function (k) {
      try { PatchedPage[k] = rawPage[k] } catch (e) { /* ignore */ }
    })
  } catch (e) { /* ignore */ }
  Page = PatchedPage
}

module.exports = { install, static_url: env.static_url }
install()
