<template>
  <el-popover
    append-to="body"
    trigger="click"
    popper-style="width: 440px;"
    ref="popoverRef"
    @hide="handleCancel"
  >
    <template #reference>
      <slot></slot>
    </template>
    <div>
      <div class="h-32px leading-32px pl-12px bg-bg-tertiary flex justify-between items-center">
        <span>{{ title }}</span>
        <el-input
          spellcheck="false"
          v-model="search"
          style="width: 200px"
          placeholder="search..."
          size="small"
        />
      </div>
      <div class="my-12px flex flex-wrap gap-x-12px gap-y-8px">
        <div
          style="width: calc(50% - 6px)"
          class="shrink-0"
          v-for="item in getOptions || []"
          :key="item.value"
        >
          <div
            class="w-full h-20px border-dashed border-1px border-border grid place-items-center cursor-pointer hover:bg-bg-primary"
            :class="
              selectedList.includes(item.value)
                ? 'bg-accent-blue hover:bg-accent-blue! text-white'
                : ''
            "
            @click="handleSelect(item.value)"
          >
            {{ item.label }}
          </div>
        </div>
        <div v-if="!getOptions?.length" class="w-full h-120px grid place-items-center">无数据~</div>
      </div>
      <div class="w-full flex justify-end">
        <el-button size="small" @click="handleCancel">取消</el-button>
        <el-button size="small" type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>
  </el-popover>
</template>

<script setup lang="ts">
import type { PopoverInstance } from 'element-plus'
import type { OptionType } from './type'

import { computed, ref } from 'vue'

const emit = defineEmits<{
  (e: 'confirm', value?: OptionType[]): void
}>()
const props = defineProps<{
  title?: string
  multiple?: boolean
  options?: OptionType[]
  selected?: string | string[]
}>()

const selectedList = ref<string[]>([])
const search = ref('')
const popoverRef = ref<PopoverInstance>()
// 搜索
const getOptions = computed(() => {
  if (!search.value) {
    return props.options
  }
  return props.options?.filter((item) => item.label.includes(search.value))
})

// 选中处理
const handleSelect = (value: string) => {
  if (selectedList.value.includes(value)) {
    selectedList.value = selectedList.value.filter((item) => item !== value)
    return
  }
  if (props.multiple) {
    selectedList.value = [...selectedList.value, value]
  } else {
    selectedList.value = [value]
  }
}

// 取消
const handleCancel = () => {
  popoverRef.value?.hide()
  selectedList.value = []
}

// 确定
const handleConfirm = () => {
  const result = props.options?.filter((item) => selectedList.value.includes(item.value))
  handleCancel()
  setTimeout(() => {
    emit('confirm', result)
  }, 500)
}
</script>

<style lang="less" scoped></style>
