<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"
      :style="checkboxStyle"
    >
      {{ 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: () => [],
  },
  width: {
    type: [String, Number],
    default: '216rpx',
  },
  height: {
    type: [String, Number],
    default: '60rpx',
  },
})
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]
  },
)

// 计算复选框样式
const checkboxStyle = computed(() => {
  const width = typeof props.width === 'number' ? `${props.width}rpx` : props.width
  const height = typeof props.height === 'number' ? `${props.height}rpx` : props.height
  return {
    '--checkbox-width': width,
    '--checkbox-height': height,
  }
})
</script>

<style lang="scss" scoped>
:deep(.custom-checkbox) {
  // 定义默认变量
  --checkbox-width: 216rpx;
  --checkbox-height: 60rpx;
  --checkbox-bg: #f7f8fa;
  --checkbox-radius: 8rpx;

  .checkbox {
    width: var(--checkbox-width);
    height: var(--checkbox-height);
    min-width: var(--checkbox-width);
    background-color: var(--checkbox-bg);
    border-radius: var(--checkbox-radius);
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2rpx solid var(--checkbox-bg);
  }
  .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>
