<template>
  <div class="space-y-3">
    <div class="text-sm font-semibold text-mosquito-ink">{{ title }}</div>
    <div class="space-y-2">
      <label
        v-for="field in fields"
        :key="field.key"
        class="flex items-center gap-2 text-xs text-mosquito-ink/80"
      >
        <input
          type="checkbox"
          class="h-4 w-4"
          :checked="isChecked(field.key)"
          :disabled="field.required"
          @change="onToggle(field.key, ($event.target as HTMLInputElement).checked)"
        />
        <span>{{ field.label }}</span>
        <span v-if="field.required" class="rounded-full bg-mosquito-accent/10 px-2 py-0.5 text-[10px] font-semibold text-mosquito-brand">
          必选
        </span>
      </label>
    </div>
    <div class="flex items-center justify-between text-xs text-mosquito-ink/70">
      <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="selectAll">全选</button>
      <button class="mos-btn mos-btn-secondary !py-1 !px-2 !text-xs" @click="clearOptional">仅保留必选</button>
      <button
        data-test="export-button"
        class="mos-btn mos-btn-accent !py-1 !px-3 !text-xs"
        @click="emit('export')"
      >
        导出
      </button>
    </div>
  </div>
</template>

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

export type ExportField = {
  key: string
  label: string
  required?: boolean
}

const props = defineProps<{
  title: string
  fields: ExportField[]
  selected: string[]
}>()

const emit = defineEmits<{
  (event: 'update:selected', value: string[]): void
  (event: 'export'): void
}>()

const requiredKeys = computed(() => props.fields.filter((field) => field.required).map((field) => field.key))

const normalizeSelection = (next: string[]) => {
  const merged = new Set([...requiredKeys.value, ...next])
  return props.fields.map((field) => field.key).filter((key) => merged.has(key))
}

const isChecked = (key: string) => normalizeSelection(props.selected).includes(key)

const onToggle = (key: string, checked: boolean) => {
  if (requiredKeys.value.includes(key)) {
    emit('update:selected', normalizeSelection(props.selected))
    return
  }
  const next = checked
    ? [...props.selected, key]
    : props.selected.filter((item) => item !== key)
  emit('update:selected', normalizeSelection(next))
}

const selectAll = () => {
  emit('update:selected', normalizeSelection(props.fields.map((field) => field.key)))
}

const clearOptional = () => {
  emit('update:selected', normalizeSelection([]))
}
</script>
