<template>
  <v-input 
    v-bind="inputAttrs" 
    :model-value="inputValue"
  >
    <div class="checkGroup" :class="inline ? 'd-flex flex-wrap align-top' : 'd-inline-block'">
      <v-checkbox
        v-for="item in items"
        hide-details
        :key="item.id || item.code"
        :label="item.codeValue"
        :value="item.code"
        v-model="localValue"
        v-bind="checkboxAttrs"
        :class="inline ? 'mr-4' : ''"
      />
    </div>
  </v-input>
</template>

<script setup>
import { ref, onMounted, useAttrs, computed, watch } from 'vue';
import Request from '@/commons/request';

// 定义组件名称
defineOptions({
  name: "VtkCheckbox",
  inheritAttrs: false,
});

// 定义 props
const props = defineProps({
  /**
   * 字典来源：
   * - 若为静态数据，格式如："0:否/1:是"
   * - 若为字典键，格式如："DISABLE_TYPE"
   */
  list: {
    type: String,
    required: true,
  },
  /**
   * 是否横向排列
   */
  inline: {
    type: Boolean,
    default: false,
  },
  /**
   * 绑定值
   */
  modelValue: {
    type: [Array, String],
    default: () => []
  }
});

// 定义 emits
const emit = defineEmits(['update:modelValue']);

// 本地选中值
const localValue = ref([]);

// 防止递归更新的标志位
const isUpdatingLocal = ref(false);
const isUpdatingModel = ref(false);

// 同步外部 modelValue 到本地值
watch(() => props.modelValue, (newVal) => {
  if (isUpdatingModel.value) {
    isUpdatingModel.value = false;
    return;
  }
  
  isUpdatingLocal.value = true;
  if (Array.isArray(newVal)) {
    localValue.value = [...newVal];
  } else if (typeof newVal === 'string') {
    localValue.value = newVal ? [newVal] : [];
  } else {
    localValue.value = [];
  }
}, { immediate: true });

// 同步本地值到外部 modelValue
watch(localValue, (newVal) => {
  if (isUpdatingLocal.value) {
    isUpdatingLocal.value = false;
    return;
  }
  
  isUpdatingModel.value = true;
  emit('update:modelValue', newVal);
}, { deep: true });

// 获取透传属性
const attrs = useAttrs();

// 分离传递给 input 和传递给 checkbox 的属性
const inputAttrs = computed(() => {
  const { list, inline, modelValue, ...rest } = attrs;
  return rest;
});

const checkboxAttrs = computed(() => {
  // 移除表单验证相关属性，避免重复应用
  const { 
    list, 
    inline, 
    modelValue,
    error, 
    'error-messages': errorMessages, 
    rules, 
    hint, 
    'persistent-hint': persistentHint,
    ...rest 
  } = attrs;
  return rest;
});

// 为 v-input 提供一个值
const inputValue = computed(() => {
  return localValue.value && localValue.value.length > 0 ? localValue.value : null;
});

// 响应式数据
const items = ref([]);

// 处理静态数据（如 "0:否/1:是"）
const statc = () => {
  props.list.split('/').forEach(it => {
    const [code, codeValue] = it.split(':');
    items.value.push({ code, codeValue });
  });
};

// 请求远程字典数据
const miscs = async () => {
  try {
    const res = await Request.getForm(`dict/misc/list/${props.list}`);
    items.value = res.data || [];
  } catch (error) {
    console.error('[VtkCheckbox] Failed to load dictionary:', error);
    items.value = [];
  }
};

// 组件挂载时初始化数据
onMounted(() => {
  if (props.list.includes(':')) {
    statc();
  } else {
    miscs();
  }
});
</script>

<style scoped>
:deep(.v-checkbox .v-selection-control) {
  margin: 0;
  padding: 0;
  min-height: 32px;
}

:deep(.v-input__details) {
  padding-inline: 16px;
}
</style>