// 选中的可能是 可能是 多选: [id1,id2] 或者 'id1,id2' 单选 'id1' 单选 number这种不考虑处理了
<script setup lang="ts" generic="T extends string | number[] | number">
import { useTagsStore } from '@/stores/tags'
import { storeToRefs } from 'pinia'
import type { TagItemDto } from '@/api/tag/types'
import type { SelectTagProps } from './types'
import { TagTypeEnum } from '@/constants'
import { push } from 'notivue'

const {
  maxSelectedTags = 1,
  filterTagsFn,
  tagType = TagTypeEnum.CULTURE_TAG,
} = defineProps<SelectTagProps>()
const emit = defineEmits<{
  selected: [tag?: TagItemDto]
}>()

const tagsStore = useTagsStore()
const {
  tagList: cultureTagList,
  relatedScenariosTagList,
  yearRecommendTagList,
} = storeToRefs(tagsStore)

const tagList = computed<TagItemDto[]>(() => {
  if (tagType === TagTypeEnum.CULTURE_TAG) {
    return cultureTagList.value
  } else if (tagType === TagTypeEnum.SCENE_TAG) {
    return relatedScenariosTagList.value
  } else if (tagType === TagTypeEnum.YEAR_TAG) {
    return yearRecommendTagList.value
  }
  return []
})

const filterTags = computed(() => {
  if (filterTagsFn) {
    return filterTagsFn(tagList.value)
  }

  return tagList.value
})

const modelValue = defineModel<T>({ required: true })

const isArrayOfModelValue = Array.isArray(modelValue.value)

// 把v-model转成一个 array类型的 方便后续操作的操作
const arryrOfModelValue = computed({
  get() {
    if (isArrayOfModelValue) {
      return (modelValue.value as number[]).filter((tagId) => {
        return filterTags.value.some((tag) => tag.id === tagId)
      })
    }
    return (modelValue.value as string)
      .split(',')
      .filter(Boolean)
      .map(Number)
      .filter((tagId) => filterTags.value.some((tag) => tag.id === tagId))
  },
  set(value) {
    if (isArrayOfModelValue) {
      modelValue.value = value as T
    } else {
      modelValue.value = value.join(',') as T
    }
  },
})
// 选中的标签
const selectedTags = computed(() => {
  const selectedTags: TagItemDto[] = []
  arryrOfModelValue.value.forEach((tagId) => {
    const tag = filterTags.value.find((tag) => tag.id === tagId)
    if (tag) {
      selectedTags.push(tag)
    }
  })
  return selectedTags
})

const searchKeyword = ref('')

const filteredRecommendedTags = computed(() => {
  if (!searchKeyword.value) {
    return filterTags.value
  }
  return filterTags.value.filter((tag) =>
    tag.title.toLowerCase().includes(searchKeyword.value.toLowerCase()),
  )
})

const addTag = (tagId: number) => {
  if (arryrOfModelValue.value.length >= maxSelectedTags)
    return push.warning(`最多只能选择 ${maxSelectedTags} 个标签`)
  // 不能直接push 触发不了computed 的 set
  arryrOfModelValue.value = [...arryrOfModelValue.value, tagId]
  push.success('标签添加成功')
  emit('selected', filterTags.value.find((tag) => tag.id === tagId)!)
}

const removeTag = (tagId: number) => {
  const index = arryrOfModelValue.value.indexOf(tagId)
  if (index > -1) {
    // 不能直接splice 触发不了computed 的 set
    arryrOfModelValue.value = [...arryrOfModelValue.value.filter((_, i) => i !== index)]
  }
  emit('selected', undefined)
}

const toggleTag = (tagId: number) => {
  if (arryrOfModelValue.value.includes(tagId)) {
    removeTag(tagId)
  } else {
    addTag(tagId)
  }
}
</script>

<template>
  <div class="tag-selector">
    <!-- 已选标签区域 -->
    <div class="selected-tags">
      <!-- 添加标签按钮 -->

      <el-popover placement="top" :width="300" trigger="click">
        <template #reference>
          <el-button class="button-new-tag" size="small"> + 添加标签 </el-button>
        </template>
        <!-- 暂时不加搜索输入框 -->
        <!-- <div class="search-section mb-4">
          <el-input
            v-model="searchKeyword"
            placeholder="Enter键添加标签"
            class="search-input"
            clearable
            @keyup.enter="addTagFromSearch"
          >
            <template #suffix>
              <span class="text-gray-400 text-sm"
                >{{ searchKeyword.length }} / {{ maxTagLength }}</span
              >
            </template>
          </el-input>
        </div> -->

        <!-- 推荐标签区域 -->
        <div class="recommended-section">
          <div class="section-title mb-3 text-gray-600 text-sm">官方标签列表</div>

          <div class="tags-grid">
            <el-tag
              v-for="tag in filteredRecommendedTags"
              :key="tag.id"
              :type="arryrOfModelValue.includes(tag.id) ? 'primary' : 'info'"
              :effect="arryrOfModelValue.includes(tag.id) ? 'dark' : 'plain'"
              class="tag-item cursor-pointer mr-2 mb-2"
              @click="toggleTag(tag.id)"
            >
              {{ tag.title }}
            </el-tag>
          </div>
        </div>
      </el-popover>
      <div class="flex flex-wrap gap-2 mt-2">
        <el-tag
          v-for="tag in selectedTags"
          :key="tag.id"
          closable
          type="primary"
          @close="removeTag(tag.id)"
        >
          {{ tag.title }}
        </el-tag>
      </div>
    </div>
  </div>
</template>
