import { defineComponent, ref, watch } from 'vue';
import {
  getEditorEmits,
  getInputNumberProps,
  useNamespace,
} from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-input-number/ibiz-input-number.scss';
import { isNilOrEmpty } from 'qx-util';

export const IBizInputNumber = defineComponent({
  name: 'IBizInputNumber',
  props: getInputNumberProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('input-number');

    const c = props.controller;

    const currentVal = ref<number | null | string>('');

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          const number = isNilOrEmpty(newVal) ? '' : Number(newVal);
          currentVal.value = Number.isNaN(number) ? '' : number;
        }
      },
      { immediate: true },
    );

    let hiddenupdownbutton = false;

    if (c.editorParams) {
      if (c.editorParams.hiddenupdownbutton) {
        try {
          hiddenupdownbutton = JSON.parse(c.editorParams.hiddenupdownbutton);
        } catch {
          hiddenupdownbutton = false;
        }
      }
    }

    const handleChange = (e: number | null) => {
      emit('change', e);
    };

    const inputRef = ref();

    if (props.autoFocus) {
      watch(inputRef, newVal => {
        if (newVal) {
          const input = newVal.$el.getElementsByTagName('input')[0];
          input.focus();
        }
      });
    }

    return {
      ns,
      c,
      currentVal,
      handleChange,
      inputRef,
      hiddenupdownbutton,
    };
  },
  render(h) {
    return (
      <div
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
          this.hiddenupdownbutton ? this.ns.m('hiddenupdownbutton') : '',
          this.controller.model.unitName ? this.ns.m('showUnitName') : '',
        ]}
      >
        {[
          this.readonly && this.currentVal,
          !this.readonly &&
            h('IInputNumber', {
              ref: 'inputRef',
              props: {
                ...this.c.customProps,
                value: this.currentVal,
                placeholder: this.controller.placeHolder,
                precision:
                  this.c.model.precision === -1
                    ? undefined
                    : this.c.model.precision,
                disabled: this.disabled,
              },
              on: {
                'on-change': this.handleChange,
              },
            }),
          this.controller.model.unitName &&
            h('i', { class: this.ns.e('unit'), slot: 'suffix' }, [
              this.controller.model.unitName,
            ]),
        ]}
      </div>
    );
  },
});
