import type { Ref } from 'vue';
import { ref, computed, getCurrentInstance, watch } from 'vue';
import { isEqual, isUndefined } from 'lodash-es';

interface UseRuleEvent {
  emitData?: Ref<any[]>;
  key: string;
  changeEvent: string;
}

export function useRuleEvent({ key = 'value', changeEvent = 'change', emitData }: UseRuleEvent) {
  const instance = getCurrentInstance();
  const props = instance?.props;
  const emit = instance?.emit;
  const changeValue = ref();
  const modelValue = computed({
    get() {
      return changeValue.value;
    },
    set(value) {
      if (!isEqual(value, changeValue.value)) {
        changeValue.value = value;
        emit?.('update:value', value);
        // nextTick(() => {
        //   emit?.(changeEvent, value, ...(emitData?.value || []));
        // });
      }
    },
  });

  watch(
    () => props[key],
    () => {
      if (!isUndefined(props[key])) {
        modelValue.value = props[key];
      }
    },
    {
      immediate: true,
    }
  );

  return { modelValue };
}
