import { computed, defineComponent, ref, watch } from 'vue';
import type { PropType } from 'vue';
import { TextBoxEditorController } from '@ibiz-template/controller';
import { debounce } from 'lodash-es';
import { useNamespace } from '@ibiz-template/vue-util';
import '@/styles/components/editor/ibiz-input-box/ibiz-input-box.scss';

export default defineComponent({
  props: {
    value: [String, Number],
    controller: {
      type: TextBoxEditorController,
      required: true,
    },
    data: {
      type: Object as PropType<IData>,
      required: true,
    },
    disable: {
      type: Boolean,
    },
  },
  emits: {
    change: (_value: string) => true,
  },
  setup(props, { emit }) {
    const ns = useNamespace('input-box');

    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 | number>('');

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

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

    return {
      ns,
      rows,
      type,
      currentVal,
      handleChange,
    };
  },
  render() {
    return (
      <div
        class={`${this.ns.b()} ${this.ns.is(
          'textarea',
          Object.is(this.type, 'textarea'),
        )}`}
      >
        <i-input
          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.disable}
        ></i-input>
      </div>
    );
  },
});
