<template>
  <CheckboxGroup v-model="defValue" checked-color="#1580FF" @change="handleChange" v-bind="$attrs">
    <Checkbox
      v-for="item in list"
      :key="item[valueKey]"
      :name="item[valueKey]"
      cell
      shape="button"
      class="custom-checkbox"
      custom-label-class="min-w-[152rpx]! h-[76rpx]! rounded-[8rpx]! checkbox-item-border bg-[#f7f8fa]!"
    >
      {{ item[labelKey] }}
    </Checkbox>
  </CheckboxGroup>
</template>

<script lang="ts" setup>
import Checkbox from './Checkbox.vue'
import CheckboxGroup from './CheckboxGroup.vue'
const props = defineProps({
  list: {
    type: Array,
    default: () => [],
  },
  labelKey: {
    type: String,
    default: 'name',
  },
  valueKey: {
    type: String,
    default: 'code',
  },
  defaultValue: {
    type: Array<string>,
    default: () => [],
  },
})
defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})

const emits = defineEmits(['change'])
const defValue = ref<string[]>([])

// 只在初始化时设置默认值
onMounted(() => {
  if (props.defaultValue?.length) {
    defValue.value = [...props.defaultValue]
  }
})

const handleChange = (val: unknown) => {
  defValue.value = val as string[]
  emits('change', val)
}
watch(
  () => props.defaultValue,
  (newVal) => {
    defValue.value = [...newVal]
  },
)
</script>

<style lang="scss" scoped>
:deep(.custom-checkbox) {
  .checkbox {
    width: 216rpx;
    height: 60rpx;
    background-color: #f7f8fa;
    border-radius: 8rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2rpx solid #f7f8fa;
  }
  .checkbox__icon {
    display: none;
  }
}

:deep(.checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;

  padding: 32rpx 16rpx 16rpx;
}
:deep(.checkbox-active) {
  border-color: #1580ff !important;
  .checkbox__label {
    color: #1580ff !important;
  }
}
</style>
