<script setup lang="ts">
import type { CheckCardProps } from './props'
import { checkCardEmits } from './props'
import type { CheckCardItem } from './types'
import CardItem from './components/CardItem.vue'

const props = withDefaults(defineProps<CheckCardProps>(), {
  modelValue: '',
  multiple: false,
  disabled: false,
  bordered: true,
  arrow: true
})
const emits = defineEmits(checkCardEmits)

const onItemClick = (item: CheckCardItem) => {
  // 是否禁用
  if (props.disabled || item.disabled) {
    return
  }

  // 是否多选
  if (props.multiple) {
    item.checked = !item.checked
    updateModelValue()
  } else {
    // 单选
    const select = props.items?.find(x => x.checked)
    select && (select.checked = false)
    item.checked = !item.checked
    updateModelValue()
  }
}

/* 修改modelValue */
const updateModelValue = () => {
  const value =
    props.items
      ?.filter(x => x.checked)
      .map(x => x.value)
      .join(',') || ''
  emits('update:modelValue', value)
}
watch(
  () => props.modelValue,
  () => {
    if (props.modelValue) {
      const value = props.modelValue.split(',').filter(x => x)
      props.items?.forEach(item => {
        item.checked = value.includes(item.value)
      })
      updateModelValue()
    }
  },
  {
    immediate: true
  }
)
</script>

<template>
  <el-row v-if="row" v-bind="row === true ? {} : row">
    <el-col v-for="(item, index) in items" :key="index + '-' + item.value" v-bind="item.col || {}">
      <CardItem
        :item="item"
        :checked="item.checked"
        :disabled="disabled || item.disabled"
        :bordered="bordered || item.bordered"
        :arrow="arrow"
        @click="onItemClick(item)"
      >
        <template #default="slotProps">
          <slot name="item" v-bind="slotProps || {}">
            <span class="item-text">{{ item.value }}</span>
          </slot>
        </template>
      </CardItem>
    </el-col>
  </el-row>
  <template v-else>
    <div class="check-card-container">
      <CardItem
        v-for="(item, index) in items"
        :key="item.key ?? index + '-' + item.value"
        :item="item"
        :checked="item.checked"
        :disabled="disabled || item.disabled"
        :bordered="bordered || item.bordered"
        :arrow="arrow"
        @click="onItemClick(item)"
      >
        <template #default="slotProps">
          <slot name="item" v-bind="slotProps || {}">
            <span class="item-text">{{ item.value }}</span>
          </slot>
        </template>
      </CardItem>
    </div>
  </template>
</template>

<style scoped lang="scss">
.check-card-container {
  display: flex;
  flex-wrap: wrap;
}
.item-text {
  display: inline-block;
  padding: 5px 8px 3px 8px;
}
</style>
