<script lang="ts" setup>
import Utils from '@/common/utils'
import GoodsCategoryApi from '@/pages/gds/goods-category/goods-category-api.ts'
import { bizType } from '@/pages/gds/goods-category/constants.ts'
import Strings from '@/common/utils/strings.ts'

const props = withDefaults(
  defineProps<{
    defaultBizType: typeof bizType[number]['val']
    disabled?: boolean
    defaultValue: {
      id?: string
      categoryName?: string
    }
  }>(),
  {
    disabled: false,
  },
)
const dataList = Utils.resetAble(reactive<GoodsCategoryTypes.SearchGoodsCategoryResult[]>([]))
const loading = ref(false)
const model = defineModel<string>()
const currentValue = reactive({
  id: props.defaultValue.id,
  categoryName: props.defaultValue.categoryName,
})

function loader(keywords: string) {
  loading.value = true
  GoodsCategoryApi
    .paging({
      bizType: props.defaultBizType,
      keywords,
    })
    .then(res => {
      if (!Strings.isBlank(currentValue.id)) {
        const findIndex = res.data.records.findIndex(it => it.id === currentValue.id)
        if (findIndex < 0) {
          res.data.records.unshift({
            id: currentValue.id!,
            categoryName: currentValue.categoryName!,
          })
        }
      }
      dataList.$reset(res.data.records)
    })
    .finally(() => loading.value = false)
}

function changeHandle(value: string) {
  const val = (dataList as GoodsCategoryTypes.SearchGoodsCategoryResult[]).filter(it => it.id === value)
  currentValue.id = val[0].id
  currentValue.categoryName = val[0].categoryName!
}

</script>

<template>
  <ElSelect
    v-model="model"
    :loading="loading"
    :remote-method="loader"
    clearable
    filterable
    placeholder="请输入文字搜索"
    remote
    remote-show-suffix
    :disabled="disabled"
    @change="changeHandle"
  >
    <ElOption v-for="it in dataList" :key="it.id" :label="it.categoryName" :value="it.id"/>
  </ElSelect>
</template>

<style lang="stylus" scoped>

</style>
