<template>
    <div
        class="screening-wrap"
    >
        <div
            v-if="title"
            class="screening-title"
        >
            <span class="title-text">{{ title }}:</span>
            <span v-if="hasSelection" class="reset-btn" @click="resetAll">{{ $t('reset') }}</span>
        </div>
        <div
            v-for="(item, index) in copyListConfig"
            :key="index"
            :class="!item.isMore ? 'show' : 'hidden'"
            class="screening-row"
        >
            <div class="row-item-title">
                {{ $t(item.title) }}:
            </div>
            <div
                :ref="(el) => { if(el) item._refEl = el }"
                class="row-item-box"
            >
                <div
                    v-for="(item1, i) in item.lists"
                    :key="item1.name"
                    :class="item.activeList && item.activeList.includes(i) ? 'active' : ''"
                    @click="currnet(item, item1, i)"
                    class="row-item"
                >
                    {{ item1[item.model || 'name'] }}
                </div>
            </div>
            <div
                v-if="item.isShow"
                @click="toggle(item)"
                class="row-more"
            >
                <i :class="item.isMore ? 'el-icon-arrow-down' : 'el-icon-arrow-up'" style="color: #000;"></i>
                <span style="margin-left: 4px;">{{ $t(item.isMore ? 'more' : 'collapse') }}</span>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUpdated, computed } from 'vue'

interface ListItem {
    title: string
    ref: string
    lists: Array<{
        name: string
        id?: string | number
    }>
    isMore?: boolean  // 改为可选
    activeList?: number[]
    valueList?: any[]
    isMultiple?: boolean
    model?: string
    value?: any
    isShow?: boolean
    _refEl?: Element
}

const props = defineProps({
    listConfig: {
        type: Array as () => ListItem[],
        default: () => []
    },
    adaptive: { // 是否自适应显示隐藏
        type: Boolean,
        default: () => true
    },
    title: {
        type: String,
        default: ''
    },
    isMultiple: {
        type: Boolean,
        default: () => false
    }
})

const emit = defineEmits(['select', 'reset'])

const copyListConfig = ref<ListItem[]>([])

const init = (data: ListItem[]) => {
    copyListConfig.value = data
    
    // 初始默认全部折叠
    for (let item of copyListConfig.value) {
        // 默认不显示更多按钮，等测量后再决定
        item.isShow = false
        // 默认折叠状态
        item.isMore = true
    }
    
    // 先初始化必要的数据属性
    copyListConfig.value.forEach((item) => {
        item.activeList = item.activeList || [0]
        item.valueList = item.valueList || []
        item.isMultiple = item.isMultiple || false
        item.model = item.model || 'name'
        item.value = item.value || ''
    })
    
    if (props.adaptive) {
        // 使用两次延迟，确保初始状态正确
        
        // 第一次延迟：确保基本DOM渲染
        setTimeout(() => {
            // 再次调整dom
            for (let item of copyListConfig.value) {
                // 在测量前先展开
                item.isMore = false
            }
            
            // 第二次延迟：测量高度并决定是否显示更多按钮
            setTimeout(() => {
                copyListConfig.value.forEach((item) => {
                    try {
                        if (item._refEl) {
                            const height = item._refEl.clientHeight
                            // 如果高度超过42px（一行+边距），则显示更多按钮并折叠
                            if (height > 42) {
                                item.isShow = true  // 显示更多按钮
                                item.isMore = true  // 恢复折叠状态
                            } else {
                                // 不超过高度，保持展开状态
                                item.isShow = false // 不显示按钮
                                item.isMore = false // 保持展开
                            }
                        }
                    } catch(e) {
                        console.log('获取高度失败', e)
                    }
                })
            }, 100)
        }, 10)
    }
}

const del = (str: any, list: any[]) => {
    list.forEach((item, index) => {
        if (item === str) {
            list.splice(index, 1)
        }
    })
}

const currnet = (item: ListItem, item1: any, index: number) => {
    if (item.isMultiple) { // 如果是多选 多选传递数组
        if (index === 0) { // 如果点击全部 清空筛选条件 清空选中条件
            item.activeList = [index]
            item.valueList = []
        } else { // 如果点击其他
            del(0, item.activeList!) // 使用!断言activeList已定义
            if (item.activeList!.includes(index)) { // 查找当前是否选中
                del(index, item.activeList!) // 切换除全部按钮选中/取消状态
                del((item1.id || item1[item.model!]), item.valueList!) // 删除筛选条件
            } else { // 添加状态和条件
                item.activeList!.push(index)
                item.valueList!.push(item1.id !== undefined ? item1.id : item1[item.model!])
            }
        }
    } else { // 单选 传递字符串
        item.activeList = [index]
        item.value = item1.id !== undefined ? item1.id : item1[item.model!]
    }

    if (item.activeList!.length === 0) { // 手动取消所有筛选条件默认选中全部
        item.activeList = [0]
    }
    emit('select', item)
}

const toggle = (item: ListItem) => {
    item.isMore = !item.isMore
}

const hasSelection = computed(() => {
    return copyListConfig.value.some(item => {
        if (!item.activeList) return false
        if (item.activeList.length > 1) return true
        return item.activeList[0] !== 0
    })
})

const resetAll = () => {
    copyListConfig.value.forEach(item => {
        item.activeList = [0]
        item.valueList = []
        item.value = ''
    })
    emit('reset')
}

onMounted(() => {
    // init()
})

onUpdated(() => {
    // init()
})

defineExpose({
    init,
    resetAll
})
</script>

<style lang="scss" scoped>

.screening-wrap {
    .screening-title {
        color: var(--info-color-333);
        font-size: 14px;
        font-weight: bold;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-right: 20px;
        
        .title-text {
            font-weight: bold;
        }
        
        .reset-btn {
            color: var(--info-primary-color);
            cursor: pointer;
            font-size: 14px;
            font-weight: normal;
            
            &:hover {
                color: var(--info-primary-color-dark);
            }
        }
    }
    padding: 15px 5px;
    .screening-row {
        .row-item-title {
            color: var(--info-color-333);
            height: 22px;
            line-height: 22px;
            padding: 0 8px;
            margin: 10px;
            min-width: 80px;
            text-align: right;
        }
        display: flex;
        width: 100%;
        .row-item {
            height: 22px;
            border: 1px solid transparent;
            line-height: 20px;
            padding: 0 8px;
            font-size: 12px;
            border-radius: 4px;
            margin: 10px;
            cursor: pointer;
            
            &:hover {
                border-color: var(--info-primary-color);
            }
        }
        .row-item-box {
            flex: 1;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
        }
        .row-more {
            height: 40px;
            line-height: 40px;
            font-size: 14px;
            color: var(--info-primary-color);
            cursor: pointer;
            width: 80px;
            display: flex !important;
            align-items: center;
        }
    }
    .show {
        height: auto;
        flex-wrap: wrap;
    }
    .hidden {
        height: 40px;
        overflow: hidden;
    }
    .active {
        background-color: var(--info-primary-color);
        color: #fff;
        border: 1px solid var(--info-primary-color);
    }
}
</style>
