<script lang="ts" setup>
import { computed } from 'vue';

import { preferences, updatePreferences } from '@vben-core/preferences';
import { capitalizeFirstLetter } from '@vben-core/toolkit';

import Preferences from './preferences-sheet.vue';

/**
 * preferences 转成 vue props
 * preferences.widget.aiAssistant=>widgetAiAssistant
 */
const attrs = computed(() => {
  const result: Record<string, any> = {};
  for (const [key, value] of Object.entries(preferences)) {
    for (const [subKey, subValue] of Object.entries(value)) {
      result[`${key}${capitalizeFirstLetter(subKey)}`] = subValue;
    }
  }
  return result;
});

/**
 * preferences 转成 vue listener
 * preferences.widget.aiAssistant=>@update:widgetAiAssistant
 */
const listen = computed(() => {
  const result: Record<string, any> = {};
  for (const [key, value] of Object.entries(preferences)) {
    if (typeof value === 'object') {
      for (const subKey of Object.keys(value)) {
        result[`update:${key}${capitalizeFirstLetter(subKey)}`] = (val: any) =>
          updatePreferences({ [key]: { [subKey]: val } });
      }
    } else {
      result[key] = value;
    }
  }
  return result;
});
</script>
<template>
  <Preferences v-bind="attrs" v-on="listen" />
</template>
