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

export const IBizGridPicker = defineComponent({
  name: 'IBizGridPicker',
  props: getGridDataPickerProps(),
  emits: getGridEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('grid-picker');
    const provider = ref();
    ibiz.register.editor.get(props.controller.model).then(value => {
      provider.value = value;
    });

    const multiple = ['ADDRESSPICKUP_AC', 'ADDRESSPICKUP'].includes(
      props.controller.model.editorType,
    );

    const { isInfoMode, componentRef, onOperateChange, onChange, onBlur } =
      useGridCellEditor(props, { emit });

    const onPickerChange = async (val: unknown, name?: string) => {
      // 最后一次值变更是自身的值变更，name为空，此时执行保存
      await onChange(val, name);
      if (!multiple && !name) {
        onBlur();
      }
    };

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