<template>
    <div :class="['s-checkbox-group',{column:props.layout==='column'},{row:props.layout==='row'}]">
        <div class="s-checkbox-group__option" v-for="item in state.options" :key="item.key">
            <input type="checkbox" :id="item.key" :checked="item.checked" @input="(e)=>{update(e,item)}">
            <label :for="item.key">{{ item.label }}</label>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { computed, PropType, reactive } from "vue"
const emit = defineEmits(["update"]) // 返回value和对应的option数组

type CheckboxOption={
    label: string,
    value: string|number,
    key?:string,
    checked?:boolean
}
type CheckboxGroupProp={
    value:Array<string|number>, // 选中的值
    name:string, // 名称
    layout:"row" | "column"
    options:CheckboxOption[] // 可选列表
}

const props = defineProps({
  value: {
    type: Array,
    default: () => []
  },
  name: String,
  options: {
    type: Array as PropType<CheckboxOption[]>,
    default: () => []
  },
  layout: {
    type: String,
    default: "column"
  }
})

// 初始化选项
function initOptions () {
  return props.options.length
    ? props.options.map(op => {
      if (!op.key) {
        op.key = op.value.toString()
      }
      if (props.value.length) {
        op.checked = !!props.value.includes(op.value)
      } else {
        op.checked = false
      }
      return op
    })
    : []
}

// 响应式状态
const state = reactive({
  options: initOptions()
})

// 选中的选项
const selectedOptions = computed(() => state.options.filter(op => op.checked))

// 更新与传递
const update = (e:Event, item:CheckboxOption) => {
  const targetChecked = (e.target as HTMLInputElement).checked
  const target = state.options.find(op => op.key === item.key)
  if (target) {
    target.checked = targetChecked
    emit("update", selectedOptions.value.map(op => op.value), selectedOptions)
  }
}
</script>

<style lang="less">
.s-checkbox-group{
  &.row .s-checkbox-group__option{
    display: inline-block;
    margin-right: @itemSpace
  }
  &.column .s-checkbox-group__option{
    height: @listHeight;
    line-height: @listHeight;
  }
}

</style>
