import Vue from 'vue'
import DatePickerView from './datetime-picker.vue'
import PopDatePickerView from './pop-datetime-picker.vue'

function isObj(x) {
  const type = typeof x
  return x !== null && (type === 'object' || type === 'function')
}

const defaultOptions = {
  title: '选择日期',
  type: 'date',
}

const currentOptions = {
  ...defaultOptions,
}
let instance = {}

function createInstance() {
  const datePicker = new (Vue.extend(PopDatePickerView))({
    el: document.createElement('div'),
  })
  document.body.appendChild(datePicker.$el)
  instance = datePicker
  return instance
}

function destroy() {
  if (Object.keys(instance).length === 0) return
  instance.isShow = false
  instance.$on('after-leave', () => instance.$destroy())
}

function functionCheck(target, targetStr, callback) {
  if (typeof target === 'function') {
    callback()
  } else {
    console.error(`type check failed for "${targetStr}"  Expected Function!`)
  }
}

function DatePicker(options = {}) {
  const datePicker = createInstance()
  if (!isObj(options)) {
    console.error('type check failed for "options". Expected Object!')
  } else {
    const opt = {
      ...currentOptions,
      ...options,
    }
    Object.assign(datePicker, opt)
    datePicker.isShow = true
    datePicker.$on('cancel', () => {
      functionCheck(opt.cancel, 'cancel', () => {
        opt.cancel()
        destroy()
      })
    })
    datePicker.$on('confirm', innerValue => {
      functionCheck(opt.confirm, 'confirm', () => {
        opt.confirm(innerValue)
        destroy()
      })
    })
    datePicker.$on('change', picker => {
      functionCheck(opt.change, 'change', () => {
        opt.change(picker)
      })
    })

    return datePicker
  }
}
DatePicker.close = () => {
  destroy()
}
/**
 * TODO:经过create.js的封装，组件都会有默认的install方法，Vue.use的作用就是全局注册该组件。
 * 外层注册DatePickerView是为了在组件内全局注册，从而使pop-datetime-picker可以引入。install函数内使用传入的全局对象注册，从而使得宿主环境可以直接标签式引入组件。
 * 疑问： DatePickerView组件只在pop-datetime-picker组件内局部引用的时候，会无法注册。待解决！

*/
// 组件全局注册datetime-picker
Vue.use(DatePickerView)

DatePicker.install = vueGlobal => {
  /* eslint no-param-reassign: ["error", { "props": false }] */
  // 宿主环境注册datetime-picker
  vueGlobal.use(DatePickerView)
  vueGlobal.prototype.$datetime = DatePicker
}

export default DatePicker
