/*
sdResource filter
处理图片等受身份保护的资源，有两种模式：
默认 —— 用ajax请求获取内容，然后转成blob url
ajax:false —— 把token追加到url后面（需要自己保证token的有效性）
*/
import Vue from 'vue'
import loginService from '@/login/login-service'
import axios from './axios-instance'

function getProtectResource(url, opt) {
  if (typeof url === 'undefined') {
    return
  }

  if (opt?.ajax === false) {
    return url + '?access_token=' + encodeURIComponent(loginService.getTokens().access_token)
  }
  if (typeof this.sdObjectURLs[url] === 'undefined') {
    // 没请求过这个地址，先塞一个占位的值，再发请求
    this.$set(this.sdObjectURLs, url, null)
    axios({
      url,
      responseType: 'blob',
    }).then((res) => {
      const blobUrl = URL.createObjectURL(res.data)
      this.$set(this.sdObjectURLs, url, blobUrl)
    })
  }

  return this.sdObjectURLs[url]
}
// eslint-disable-next-line vue/require-name-property
Vue.mixin({
  data: function() {
    return {
      sdObjectURLs: {},
    }
  },
  beforeCreate() {
    if (!this.$options.filters) {
      this.$options.filters = {}
    }

    this.$options.filters.sdResource = (...args) => {
      return getProtectResource.apply(this, args)
    }
  },
  beforeDestroy() {
    // 销毁所有ObjectURL
    for (const url in this.sdObjectURLs) URL.revokeObjectURL(this.sdObjectURLs[url])
  },
})
