<template>
    <van-popup v-model:show="showPublish" round position="bottom" closeable>
        <div class="popbox">
            <div class="title">发布图组</div>
            <van-form @submit="handleSubmit" required colon>
                <van-field v-model="formData.organizeName" is-link readonly name="picker" label="选择组织"
                    placeholder="请选择组织" @click="showOrganize = true" :rules="[{ required: true, message: '请选择组织' }]" />
                <div class="btn">
                    <van-button round type="primary" native-type="submit" size="small">立即发布</van-button>
                </div>
            </van-form>
        </div>

    </van-popup>
    <van-popup v-model:show="showOrganize" round position="bottom">
        <van-cascader v-model="formData.organizeName" title="请选择组织" :options="options" :field-names="fieldNames"
            @close="showOrganize = false" @finish="onFinish" />
    </van-popup>
</template>

<script setup>
import useUserStore from '@/store/user'
import { publishPicture } from '@/api/publish'
import { selectAppUserOrganizeList } from '@/api/prefecture'
import { showLoadingToast, closeToast, showToast } from 'vant'

const emits = defineEmits(["refresh"])
const userStore = useUserStore()

const dataList = ref([])
const options = ref([])
const getList = async () => {
    const data = {
        userId: userStore.userinfo.user.id,
        sysCode: import.meta.env.VITE_APP_SYSTEM_CODE,
        moduleCode: 'practice-mediaCatalog'
    }
    const res = await selectAppUserOrganizeList(data)
    dataList.value = res.data
    options.value = buildTree(res.data)
}

const formData = ref({
    materialId: null,
    organizeId: '',
    organizeName: '',
    collect: 1
})
const showOrganize = ref(false)
const fieldNames = {
    text: 'organName',
    value: 'id',
    children: 'children',
};

const buildTree = (items) => {
    const tree = []
    const lookup = {}

    // 初始化lookup对象，方便后续快速查找  
    items.forEach(item => {
        lookup[item.id] = { ...item, id: item.id.toString(), children: [] };
    });

    // 构建树  
    items.forEach(item => {
        if (item.superiorId == 0) {
            // superiorId=0的项是顶级项  
            tree.push(lookup[item.id]);
        } else {
            // 否则，添加到对应父节点的children数组中  
            if (!lookup[item.superiorId]) {
                // 如果父节点不存在（理论上不应该发生，除非数据有误），可以创建一个空的占位符  
                lookup[item.superiorId] = { children: [] };
            }
            lookup[item.superiorId].children.push(lookup[item.id]);
        }
    });
    tree.push({
        id: '0',
        organName: '无组织',
        children: []
    })

    return removeEmptyChildren(tree)
}

const removeEmptyChildren = (nodes) => {
    nodes.forEach(node => {
        if (node.children.length === 0) {
            delete node.children;
        } else {
            removeEmptyChildren(node.children);
        }
    });
    return nodes
}

// 全部选项选择完毕后，会触发 finish 事件
const onFinish = ({ selectedOptions }) => {
    showOrganize.value = false;
    console.log(selectedOptions)
    formData.value.organizeId = selectedOptions[selectedOptions.length - 1].id
    formData.value.organizeName = selectedOptions[selectedOptions.length - 1].organName
};

const handleSubmit = async () => {
    showLoadingToast({
        message: '发布中',
        forbidClick: true,
        duration: 0
    })
    await publishPicture(formData.value)
    closeToast()
    showToast('发布成功')
    showPublish.value = false
    emits('refresh')
}

const showPublish = ref(false)
const open = (e) => {
    console.log(e)
    formData.value.materialId = e.materialId
    showPublish.value = true
    getList()
}
const close = () => {
    showPublish.value = false
}
defineExpose({
    open,
    close
})
</script>

<style lang="scss" scoped>
.popbox {
    padding: 20px;

    .title {
        font-size: 18px;
        font-weight: bold;
        margin-bottom: 20px;
    }

    .btn {
        width: 100%;
        display: flex;
        justify-content: center;
        margin-top: 20px;

        .van-button {
            width: 100%;
        }
    }
}
</style>