import { computed, defineComponent, ref, watch } from 'vue';
import { debounce } from 'lodash-es';
import {
  getEditorEmits,
  getInputProps,
  useNamespace,
} from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-input/ibiz-input.scss';

export const IBizInput = defineComponent({
  name: 'IBizInput',
  props: getInputProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('input');
    const c = props.controller;
    const editorModel = c.model;

    // 文本域默认行数，仅在 textarea 类型下有效
    const rows = ref(2);
    if (editorModel.editorType === 'TEXTAREA_10') {
      rows.value = 10;
    }

    // 类型
    const type = computed(() => {
      switch (editorModel.editorType) {
        case 'TEXTBOX':
          return 'text';
        case 'PASSWORD':
          return 'password';
        case 'TEXTAREA':
        case 'TEXTAREA_10':
          return 'textarea';
        default:
          return 'string';
      }
    });

    const currentVal = ref<string>('');

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          if (!newVal) {
            currentVal.value = '';
          } else {
            currentVal.value = newVal;
          }
        }
      },
      { immediate: true },
    );

    // 值变更
    const handleChange = debounce((e: IData) => {
      emit('change', e.target.value);
    }, 500);

    const inputRef = ref();

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

    return {
      ns,
      rows,
      type,
      currentVal,
      handleChange,
      inputRef,
    };
  },
  render() {
    return (
      <div
        class={`${this.ns.b()} ${this.ns.is(
          'textarea',
          Object.is(this.type, 'textarea'),
        )}`}
      >
        {this.infoMode ? (
          this.currentVal
        ) : (
          <i-input
            ref='inputRef'
            value={this.currentVal}
            placeholder={this.controller.placeHolder}
            readonly={this.controller.model.readOnly}
            type={this.type}
            rows={this.rows}
            on-on-change={this.handleChange}
            class={this.ns.b('input')}
            disabled={this.disabled}
          ></i-input>
        )}
      </div>
    );
  },
});
