<script lang="ts">
import { defineComponent, computed, ref, createVNode, resolveComponent } from 'vue-demi'
import { formatAmt } from '../../../utils/format'
import { isEmpty } from '../../../utils/validate'

export default defineComponent({
  name: 'YnetInputAmt',
  props: {
    modelValue: {
      type: [String, Number],
      default: ''
    },
    decimal: {
      type: Number,
      default: 2
    }
  },
  emits: ['update:modelValue', 'focus', 'blur'],
  setup (props, { emit, attrs, slots }) {
    const focus = ref(false)
    const amtReg = computed(() => props.decimal > 0 ? new RegExp(`(\\.\\d{${props.decimal}}).+$`) : /\..*$/)

    const amount = computed({
      set (val: string|number) {
        const value = isEmpty(val) ? val : String(val).replace(/[^-.\d+]/g, '').replace(amtReg.value, props.decimal > 0 ? '$1' : '')
        emit('update:modelValue', value)
      },
      get (): string| number {
        const value = props.modelValue
        if (focus.value || isEmpty(value)) {
          return value
        }
        const val = formatAmt(value, props.decimal)
        const num = val.replace(/,/g, '')
        if (num !== value) {
          emit('update:modelValue', num)
          return val
        }
        return val
      }
    })

    function triggerFocus (trigger: boolean) {
      focus.value = !!trigger
      emit(trigger ? 'focus' : 'blur')
    }

    const onFocus = () => triggerFocus(true)
    const onBlur = () => triggerFocus(false)
    const updateModelValue = ($event: string) => { amount.value = $event }

    return () => createVNode(resolveComponent('el-input'), {
      modelValue: amount.value,
      type: 'text',
      ...attrs,
      'onUpdate:modelValue': updateModelValue,
      onFocus,
      onBlur
    }, slots)
  }
})
</script>
