<template>
    <el-input v-model="keyword"
              :placeholder="$t('pleaseInput')"
              size="small"
              :prefix-icon="Search"
              @keyup.enter="fuzzyMatching"
              @input="fuzzyMatching">
    </el-input>
</template>
<script lang="ts">
import { Search } from '@element-plus/icons-vue'
import { ref, defineComponent } from 'vue'
import {
    getFieldValue
} from '../../script/util'

export default defineComponent({
    name: 'FuzzyMatching',
    props: {
        totalData: {
            type: Array,
            default: () => []
        },
        field: {
            type: String,
            default: 'name'
        }
    },
    emits: ['getfuzzyMatching'],
    setup (props, { emit }) {
        const keyword = ref<string>('')
        let timer: any = null
        const filterResult = () => {
            // 定义匹配正则
            let reg = new RegExp(keyword.value, 'gim')
            // 需要匹配正则的field用逗号隔开
            let fieldArray = props.field.split(',')
            // 每项数据只要有一个字段符合正则就滤出
            return props.totalData.filter((item: any) => {
                return fieldArray.some((key) => {
                    let value = String(getFieldValue(item, key))
                    return value.match(reg)
                })
            })
        }
        const fuzzyMatching = () => {
            let result: any[] = []
            // 防止连续输入 执行，如果 半秒之后不输入在执行
            clearTimeout(timer)
            timer = setTimeout(() => {
                result = filterResult()
                emit('getfuzzyMatching', result, keyword.value)
                timer = null
            }, 500)
        }
        return {
            keyword,
            fuzzyMatching,
            filterResult,
            Search
        }
    }
})
</script>
<style lang="scss" scoped>
</style>
