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 = ['ADDRESSPICKUP_AC', 'ADDRESSPICKUP'].includes(
      props.controller.model.editorType,
    );
    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 (
      <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.readonly || this.isInfoMode,
              disabled: this.disabled,
            },
            on: {
              change: this.onChange,
              operate: this.onOperateChange,
            },
          })}
      </grid-editor>
    );
  },
});
