import { defineComponent } from 'vue';
import {
  getGridDropdownProps,
  getGridEditorEmits,
  useGridCellEditor,
  useNamespace,
} from '@ibiz-template/vue-util';

export const IBizGridDropdown = defineComponent({
  name: 'IBizGridDropdown',
  props: getGridDropdownProps(),
  emits: getGridEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('grid-dropdown');
    const {
      isInfoMode,
      autoFocus,
      componentRef,
      onOperateChange,
      onChange,
      onBlur,
    } = useGridCellEditor(props, {
      emit,
    });

    const onDropDownChange = async (val: unknown, name?: string) => {
      await onChange(val, name);
      // 单选时失焦触发行编辑失焦
      if (!props.controller.multiple) {
        onBlur();
      }
    };

    return {
      ns,
      isInfoMode,
      autoFocus,
      componentRef,
      onOperateChange,
      onDropDownChange,
    };
  },
  render(h) {
    return (
      <grid-editor
        disabled={this.disabled}
        readonly={this.readonly}
        ref='componentRef'
        class={`${this.ns.b()}`}
      >
        {h('IBizDropdown', {
          props: {
            ...this.$props,
            readonly: this.isInfoMode,
            disabled: this.disabled,
            autoFocus: this.autoFocus,
          },
          on: {
            change: this.onDropDownChange,
            operate: this.onOperateChange,
          },
        })}
      </grid-editor>
    );
  },
});
