<script setup lang="ts">
import { computed } from 'vue'
import { NCheckbox } from 'naive-ui'

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any }>()

// Label布局：上下结构(vertical) 或 左右结构(horizontal)
const labelLayout = computed(() => props.df.label_layout || 'vertical')

function getVal(record: any, fieldname: string) {
  const v = record[fieldname]
  return Array.isArray(v) ? v : []
}

function toggle(record: any, fieldname: string, optionValue: string, checked: boolean) {
  if (!Array.isArray(record[fieldname])) record[fieldname] = []
  const list: string[] = record[fieldname]
  if (checked) {
    if (!list.includes(optionValue)) list.push(optionValue)
  } else {
    const idx = list.indexOf(optionValue)
    if (idx > -1) list.splice(idx, 1)
  }
}
</script>

<template>
  <div :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx.t(df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    <div class="multicheck-container">
      <n-checkbox 
        v-for="option in (ctx.getSelectOptions ? ctx.getSelectOptions(df) : [])"
        :key="option.value"
        :checked="getVal(record, df.fieldname).includes(option.value)"
        @update:checked="(c) => toggle(record, df.fieldname, option.value, c)"
        :disabled="!canEdit"
      >
        {{ option.label }}
      </n-checkbox>
    </div>
  </div>
</template>

<style scoped>
.field-wrapper :deep(.multicheck-container) {
  flex: 1;
}
</style>


