<template>
    <el-input v-model="tableSearch.filter" clearable placeholder="搜索当前表格" @keyup="searchInTable" @clear="searchInTable">
        <template #prefix><sc-iconify icon="ep:search"></sc-iconify></template>
    </el-input>
</template>

<script setup>
import XEUtils from "xe-utils";

const props = defineProps({
    renderOpts: { type: Object, default: () => {} },
    params: { type: Object, default: () => {} }
})

const tableSearch = ref({
    filter: ""
})

const searchInTable = () => {
    const filterName = XEUtils.toValueString(tableSearch.value.filter).trim().toLowerCase();
    const tableData = XEUtils.clone(props.params.$grid?.getData(), true);
    if (filterName) {
        const filterRE = new RegExp(filterName.replace(/([.?*+^$[\]\\(){}|-])/gi, "\\$1"), "gi");
        const searchColumns = props.params.$grid?.getColumns()?.filter(col => col.field);

        const data = tableData?.map(item => {
            searchColumns?.forEach(col => XEUtils.set(
                item,
                col.field,
                props.params.$grid?.getCellLabel(item, col.field)
            ));
            return item;
        })?.filter(item => searchColumns?.some(col => XEUtils.toValueString(XEUtils.get(item, col.field)).toLowerCase().includes(filterName)))?.map(row => {
            const item = Object.assign({}, row);
            searchColumns?.filter(col => col.type === "html").forEach(col => {
                XEUtils.set(
                    item,
                    col.field,
                    XEUtils.toValueString(XEUtils.get(item, col.field)).replace(filterRE, match => `<span class="keyword-lighten">${match}</span>`)
                )
            });
            return item;
        })
        props.params.$grid?.reloadData(data);
    } else props.params.$grid?.reloadData(tableData);
}
</script>

<style scoped>
    .el-input {width: 180px;}
</style>