<template>
  <view class="custom-checkbox">

    <CheckboxGroup v-model="defValue" checked-color="#1580FF" @change="handleChange" v-bind="$attrs" :default-cols="4">

      <Checkbox v-for="item in list" :key="item[valueKey]" :name="item[valueKey]" cell shape="button" :default-style="`
      ${checkboxStyle}
        --checkbox-bg: #f7f8fa;
        --checkbox-radius: 8rpx;
        --checkbox-active-border: 2rpx solid #1580ff;
        --checkbox-active-color: #1580ff;
 
        height: var(--checkbox-height);
 
        background-color: var(--checkbox-bg);
        border-radius: var(--checkbox-radius);
        display: flex;
        align-items: center;
        justify-content: center;
      `">
        {{ item[labelKey] }}
      </Checkbox>

    </CheckboxGroup>
  </view>
</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',
  },
  defaultCols: {
    type: Number,
    default: 3,
  },
})
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>
.custom-checkbox {
  // 定义默认变量
  --checkbox-width: 216rpx;
  --checkbox-height: 60rpx;
  --checkbox-bg: #f7f8fa;
  --checkbox-radius: 8rpx;
  color: #333;

}

:deep(.ycym-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);
}

:deep(.checkbox__icon) {
  display: none;
}



:deep(.checkbox-active) {
  border-color: #1580ff !important;

  .checkbox__label {
    color: #1580ff !important;
  }
}
</style>
