<template>
  <slot />
</template>

<script setup lang="ts">
import { onMounted, onUpdated, provide, toRef, type Ref } from 'vue';
import { ArrayUtils } from '@imengyu/imengyu-utils';
import { useFieldChildValueInjector } from './FormContext';

export interface RadioBoxGroupProps {
  /**
   * 当前组选中的项目
   */
  modelValue?: string|number|boolean|undefined|null;
  /**
   * 是否禁用整组复选框，设置后会禁用全部复选框。
   * @default false
   */
  disabled?: boolean;
}
export interface RadioBoxGroupToggleOptions {
  /**
   * 是否是选中
   * @required true
   */
  checked: boolean,
  /**
   * 是否跳过禁用的复选框
   * @required true
   */
  skipDisabled: boolean,
}
export interface RadioBoxGroupContextInfo {
  value: Ref<string|number|boolean>,
  topDisabled: Ref<boolean>,
  onValueChange: (name: string|number|boolean|undefined, v: boolean) => void;
  onAddItem: (name: string, disabled: boolean) => void;
}

const props = withDefaults(defineProps<RadioBoxGroupProps>(), {
  modelValue: undefined,
  disabled: false,
});

const {
  value,
  updateValue,
} = useFieldChildValueInjector(
  toRef(props, 'modelValue'), 
  (v) => emit('update:modelValue', v)
);

provide<RadioBoxGroupContextInfo>('RadioBoxGroupContext', {
  value: value as any,
  topDisabled: toRef(props, 'disabled'),
  onValueChange,
  onAddItem: (name, disabled) => {
    allCheckNames.push(name);
    allCheckDisabled.push(disabled);
  },
});

onMounted(() => {
  ArrayUtils.clear(allCheckNames);
  ArrayUtils.clear(allCheckDisabled);
});
onUpdated(() => {
  ArrayUtils.clear(allCheckNames);
  ArrayUtils.clear(allCheckDisabled);
});

const emit = defineEmits([ 'update:modelValue' ]);

const allCheckNames = [] as string[];
const allCheckDisabled = [] as boolean[];

function onValueChange(name: string|number|boolean|undefined, checked: boolean) {
  updateValue(checked ? name as string : undefined);
}

defineOptions({
  options: {
    styleIsolation: "shared",
    virtualHost: true,
  }
})
</script>