import Vue from 'vue'
import PickerView from './picker.vue'
import PopPickerView from './popPicker.vue'

const PickerConstructor = Vue.extend(PopPickerView)

let instance

const getAnInstance = () =>
  new PickerConstructor({
    el: document.createElement('div'),
  })

function Picker(options) {
  instance = getAnInstance()
  Object.assign(instance, {
    ...options,
  })
  instance.$on('confirm', (picker, value, index, indexs) => {
    if (typeof options.callback === 'function') {
      options.callback({
        type: 'confirm',
        picker,
        value,
        index,
        indexs,
      })
    }
    instance.$on('after-leave', () => instance.$destroy())
  })
  instance.$on('change', (picker, value, index) => {
    if (typeof options.callback === 'function') {
      options.callback({
        type: 'change',
        picker,
        value,
        index,
      })
    }
  })
  instance.$on('input', value => {
    instance.value = value
  })

  if (typeof options === 'string') {
    instance.title = options
  }
  document.body.appendChild(instance.$el)
  instance.isShow = false
  Vue.nextTick(() => {
    instance.isShow = true
    instance.showToolbar = true
    if (options.pickerData) {
      instance.index = options.index ? options.index : 0
      instance.defaultValue = options.defaultValue
        ? options.defaultValue
        : [options.pickerData[instance.index]]
    }
  })
}
Picker.install = vueGlobal => {
  const vueGlobalObj = vueGlobal
  vueGlobalObj.use(PickerView)
  vueGlobalObj.use(PopPickerView)
  vueGlobalObj.prototype.$picker = Picker
}

export default Picker
