<template>
    <van-popup v-model:show="show" position="bottom" :close-on-click-overlay="false" safe-area-inset-bottom @close="handleClose">
        <div class="container">
            <div class="header-placeholder">
                <div class="header">
                    <span class="reset" @click="handleReset">重置</span>
                    <span class="confirm" @click="handleConfirm">确认</span>
                </div>
            </div>
            <van-cascader v-model="activeId" :show-header="false" :options="treeList" :field-names="fieldNames" />
        </div>
    </van-popup>
</template>
<script setup>
import { selectTagsList } from '@/api/publish'
const emits = defineEmits(["confirm", "close"])

const activeId = ref(null)
const fieldNames = {
    text: 'title',
    value: 'id',
    children: 'children'
}

const treeList = ref([])
const dataList=ref([])
const getList = async () => {
    const res = await selectTagsList()
    treeList.value = res.data
    dataList.value=dealTreeData(res.data)
}
getList()


const dealTreeData = (data) => {
    let arrTree = []
    data.forEach((ele) => {
        let obj = { ...ele }
        delete obj.children
        arrTree.push(obj)
        if (ele?.children?.length) {
            arrTree.push(...dealTreeData(ele.children))
        }
    });
    return arrTree;
}



const handleConfirm = () => {
    const item = dataList.value.filter(item => item.id == activeId.value)[0]
    emits('confirm', item)
    show.value = false
}
const handleReset = () => {
    activeId.value = null
}
const handleClose = () => {
    emits('close')
}

const show = ref(false)
const open = () => {
    show.value = true
}
const close = () => {
    show.value = false
}
defineExpose({
    open,
    close
})
</script>
<style lang="scss" scoped>
.container {
    max-height: 50vh;

    .header-placeholder {
        height: 55px;

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 16px;
            position: fixed;
            width: calc(100vw - 40px);
            height: 55px;
            background-color: #ffffff;
            color: #545454;
            padding: 0 20px;

            .confirm {
                color: #0e7ce3;
            }
        }
    }


    ::v-deep(.van-sidebar-item) {
        text-align: center;
    }
}
</style>