import { SetupContext, ref, reactive, toRefs } from 'vue'
import { FilterColumn, FilterSelect, FilterInput, FilterButton } from './interface'

/**
 * 参考https://2x.antdv.com/components/table-cn
 */
export function useFilter<T>(context: SetupContext) {
    const state: { selectList: FilterSelect<T>[], inputList: FilterInput<T>[] } = reactive({
        selectList: [],
        inputList: [],
    })

    // 表格过滤查询，支持多条件查询
    const search = () => {
        const filters: FilterColumn<T>[] = [];

        state.selectList.forEach((item) => {
            const { key, alias, selectedValue } = item;
            if (selectedValue) {
                filters.push({
                    key: (alias ?? key).toString(),
                    filteredValue: [selectedValue.toString()],
                    onFilter: (value, record) => String(record[key]).indexOf(value) === 0
                })
            }
        })

        state.inputList.forEach((item) => {
            const { keys, alias, value } = item;
            if (value) {
                if (alias) {
                    filters.push({
                        key: alias,
                        filteredValue: [value],
                        onFilter: (value, record) => {
                            return keys.some((key) => {
                                return String(record[key])?.toLowerCase().indexOf(value.toLowerCase()) >= 0
                            })
                        }
                    })
                } else {
                    keys.forEach((key) => {
                        filters.push({
                            key: key.toString(),
                            filteredValue: [value],
                            onFilter: (value, record) => {
                                return String(record[key])?.toLowerCase().indexOf(value.toLowerCase()) >= 0
                            }
                        })
                    })
                }
            }
        })

        context.emit('search', filters);
    }

    // 重置查询
    const reset = () => {
        state.selectList.forEach((e) => {
            e.selectedValue = typeof e.selectedValue === 'string' ? '' : 0;
        });
        state.inputList.forEach((e) => (e.value = ''));
        search();
    }

    const buttonList = ref<FilterButton[]>([
        { lable: '查询', event: search },
        { lable: '重置', event: reset },
    ]);

    return {
        ...toRefs(state),
        buttonList,
        search,
        reset
    }
}