import { ref, watchEffect } from 'vue'
import { ListIitem } from "@/api/base/BaseDataModel"
import { pinyin } from 'pinyin-pro';
import { isArrayLength } from '@/utils/is';
import { useDebounceFn } from '@vueuse/shared';

interface TypeOject extends ListIitem {
    letter?: string
}

/**
 * 自定义select搜索
 * @param listItem 响应式对象数据
 * @param field 键
 */
export default function useDefinFilter(listItem: Recordable, field: string, time = 500) {
    // 显示的列表
    const typeList = ref<TypeOject[]>([])
    // 过滤的列表
    const filterList = ref<TypeOject[]>([])
    const stop = watchEffect(() => {
        if (isArrayLength(listItem[field])) {
            typeList.value = listItem[field];
            filterList.value = listItem[field].map((item: TypeOject) => {
                // 中文转拼音字母
                if (!item.letter) {
                    // 中文转拼音
                    const letter = pinyin(item.label, { toneType: "none" }).replace(/\s+/g, '')
                    item.letter = letter
                }
                return item
            });
        }
    })
    //el-select定义中文字母搜索
    const definFilter = useDebounceFn((query: string) => {
        if (filterList.value.length > 0) stop();
        if (query === '') return typeList.value = filterList.value;
        // query为input输入的模糊查询项
        const list = filterList.value.filter((item) =>
            item.label.indexOf(query) !== -1 ||
            item.value.toString().indexOf(query) !== -1 ||
            item.letter?.indexOf(query) !== -1 ||
            item.value.toString().indexOf(query.toUpperCase()) !== -1
        );
        typeList.value = list;
    }, time)

    return {
        definFilter,
        typeList
    }
}