<script>
import create from '../utils/create'
import { Input } from 'view-design'
import _ from 'lodash/object'
import Cleave from 'cleave.js'
import 'cleave.js/src/addons/phone-type-formatter.cn'
import { getSelection, setSelection } from '../utils'

export default create({
  name: 'phone-input',
  mixins: [Input],
  props: {
    value: {
      required: false,
      validator (val) {
        return typeof val === 'string' || val === '' || val === null
      }
    },
    cleave: {
      type: Object,
      default: {}
    }
  },
  data () {
    return {
      currentValue: this.value,
      anElement: null
    }
  },
  computed: {
    options () {
      let initCleave = {
        onValueChanged: this.changeHandler
      }
      return _.assign(initCleave, this.cleave)
    }
  },
  methods: {
    changeHandler (event) {
      if (this.anElement) {
        let rawValue = event.target.rawValue
        let targetValue = event.target.value
        let selection = getSelection(this.anElement.element)
        this.currentValue = rawValue.toUpperCase()
        this.$nextTick(() => {
          this.anElement.element.value = targetValue.toUpperCase()
          setSelection(this.anElement.element, selection)
        })
        this.$emit('input', this.currentValue, event)
      }
    }
  },
  mounted () {
    let el = this.$el
    let element = el.tagName === 'INPUT' ? el : el.querySelector('input')
    this.anElement = new Cleave(element, this.options)
    this.anElement.element.addEventListener('paste', this.handlePaste)
    this.$nextTick(() => {
      element.value = this.anElement.properties.result
    })
  },
  watch: {
    value (val) {
      this.currentValue = val
      this.anElement.setRawValue(val)
      this.$emit('input', this.currentValue)
    }
  }
})
</script>
