<script setup lang="ts">
import { CloseBold } from '@element-plus/icons-vue'
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
import PopoverFilter from './PopoverFilter.vue'
import PopoverFilterParent from './PopoverFilterParent.vue'
import { getProductSelect } from '../api'
import emitter from '/@/utils/emitter'

const isVisible = ref(false)
const productFilterInput = ref('')
const inputPlaceholder = ref('请选择推广商品')
const productFilterSelect = ref('')
const productFilterOptions = ref([])

emitter.on('PopoverFilter-sendSearchItem', (data: any) => {
  if (data.value.length === 1) {
    // 如果数组只有一个元素，直接使用该元素的值作为占位符
    inputPlaceholder.value = data.value[0]
  } else if (data.value.length === 0) {
    inputPlaceholder.value = '请选择推广商品'
  } else if (data.value.length > 1) {
    // 如果数组有多于一个元素，使用第一个元素并注明还有多少其他元素
    inputPlaceholder.value = `${data.value[0]} +${data.value.length - 1}`
  }
})

async function fetchProductSelect() {
  try {
    const response = await getProductSelect()
    productFilterOptions.value = response.data
    productFilterSelect.value = response.data[0].value
  } catch (error) {
    console.log('error:', error)
  }
}

function handleOpen() {
  isVisible.value = true
  emitter.emit('TopFilter', { isVisible, productFilterSelect })
}

function handleClose() {
  isVisible.value = false
  emitter.emit('TopFilter', isVisible)
}

function handleConfirm() {
  isVisible.value = false
  emitter.emit('TopFilter-confirm', { confirm: true })
}

const currentComponent = computed(() => {
  switch (productFilterSelect.value) {
    case 'pAsin':
      return PopoverFilterParent
    case 'sku':
    case 'asin':
      return PopoverFilter
    default:
      return null // 或者是一个默认的组件
  }
})

onMounted(() => {
  fetchProductSelect()
})

onBeforeUnmount(() => {
  emitter.all.clear()
})
</script>

<template>
  <div style="max-width: 350px">
    <el-popover :visible="isVisible" placement="bottom-start" :width="1200">
      <template #reference>
        <el-input v-model="productFilterInput" @click="handleOpen" style="width: 350px" :placeholder="inputPlaceholder">
          <template #prepend>
            <el-select v-model="productFilterSelect" placeholder="Select" style="width: 100px">
              <el-option v-for="item in productFilterOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </template>
        </el-input>
      </template>
      <div class="flex justify-between">
        <div class="pb-3 font-bold text-slate-950 text-base">搜索</div>
        <el-icon class="cursor-pointer" @click="handleClose">
          <CloseBold />
        </el-icon>
      </div>
      <component :is="currentComponent"></component>
      <div class="flex justify-end mt-2">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" color="#3c58af" @click="handleConfirm">应用</el-button>
      </div>
    </el-popover>
  </div>
</template>

<style scoped></style>
