<template>
  <popover-filter :clearable="modelValue && modelValue.length" :label="label" :text="text" :width="width"
    @clear="clear">
    <el-input v-if="filterable" v-model="keyword" :placeholder="placeholder" class="mb-2" clearable />
    <el-checkbox v-if="list.length && keyword.trim()===''" v-model="allChecked" label="全部" />
    <el-checkbox-group v-if="list.length" v-model="modelValue">
      <div v-for="item in showList" :key="item.value">
        <el-checkbox :label="item.value" :value="item.value">
          <slot name="item" :item="item">{{ item.label }}</slot>
        </el-checkbox>
      </div>
    </el-checkbox-group>
  </popover-filter>
</template>
<script setup>
import { computed, ref } from 'vue';
import { useVModels } from '@vueuse/core';

import PopoverFilter from './popover-filter-item.vue';

const emits = defineEmits(['update:modelValue']);
const props = defineProps({
  filterable: { type: Boolean, default: false },
  list: { type: Array, default: () => [] },
  label: { type: String, default: '' },
  text: { type: String, default: '' },
  width: { type: [Number, String], default: 280 },
  modelValue: { type: Array, default: () => [] },
  placeholder: { type: String, default: '' },
  filterMethod: { type: Function, default: null }
})
const { modelValue } = useVModels(props, emits);

const clear = () => modelValue.value = []
const keyword = ref('');
const showList = computed(() => {
  if (keyword.value.trim() === '') {
    return props.list
  }
  if (typeof props.filterMethod === 'function') {
    return props.list.filter(item => props.filterMethod(item, keyword.value.trim()))
  }
  return props.list.filter(i => new RegExp(keyword.value.trim(), 'i').test(i.label) || new RegExp(keyword.value.trim(), 'i').test(i.value))
})

const allChecked = computed({
  get() {
    return modelValue.value.length === props.list.length && props.list.length > 0
  },
  set(value) {
    if (value) {
      modelValue.value = props.list.map(item => item.value)
    } else {
      modelValue.value = []
    }
  }
})
const text = computed(() => props.text || (props.modelValue.length ? `已选择${props.modelValue.length}项` : ''))
</script>
<style lang="scss" scoped></style>
