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

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

    const { isInfoMode, componentRef, onOperateChange, onChange } =
      useGridCellEditor(
        async (val: unknown, name?: string) => {
          await props.rowDataChange(val, name);
          // 最后一次值变更是自身的值变更，name为空，此时执行保存
          if (!multiple && !name) {
            await props.rowSave();
            isInfoMode.value = true;
          }
        },
        props.rowSave,
        {
          isDelaySave: true,
        },
      );

    return {
      ns,
      isInfoMode,
      componentRef,
      provider,
      onOperateChange,
      onChange,
    };
  },
  render(h) {
    return (
      <div
        ref='componentRef'
        class={`${this.ns.b()} ibiz-grid-editor`}
        onDblclick={evt => evt.stopPropagation()}
        onClick={evt => evt.stopPropagation()}
      >
        {this.provider &&
          h(this.provider.formEditor, {
            props: {
              ...this.$props,
              infoMode: this.isInfoMode,
            },
            on: {
              change: this.onChange,
              operate: this.onOperateChange,
            },
          })}
      </div>
    );
  },
});
