import Vue from 'vue'
import Main from './main.vue'
import * as Options from './defaultOptions'

const GoodsConstructor = Vue.extend(Main)

let instance
let seed = 1

const Goods = function(options) {
  if (Vue.prototype.$isServer) return
  if (instance) instance.close()

  return new Promise((resolve, reject) => {
    options = options || {}
    if (!options.goodsApi) {
      options.goodsApi = process.env.BASE_API + '/warehouse-info/info/inventory'
    }
    const id = 'goods_picker_' + seed++
    options.show = true
    instance = new GoodsConstructor({ propsData: options })
    instance.id = id
    instance.$mount()
    instance.resolve = resolve
    instance.reject = reject
    instance.close = closeInstance
    document.body.appendChild(instance.$el)
  })
}

// 扩展列
Goods.columns = {
  general: Options.generalColumns
}

function closeInstance() {
  instance.$destroy()
  instance.$el.parentNode.removeChild(instance.$el)
  // instance.reject('取消了')
  instance = undefined
}

export default Goods
