<template>
    <el-dialog :model-value="visible" title="营养宣教模板" width="480px" @close="$emit('update:visible', false)" append-to-body class="consultant-template-dialog">
        <div class="dialog-header-row">
            <el-input v-model="searchValue" placeholder="请输入模板名称" size="small" class="search-input" @keyup.enter="handleSearch" />
            <el-button type="primary" size="small" class="search-btn" @click="handleSearch">确定</el-button>
        </div>
        <el-tree :data="treeData" :props="defaultProps" node-key="id" default-expand-all class="template-tree" highlight-current :expand-on-click-node="false" :show-checkbox="false" @node-click="handleNodeClick" />
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="handleConfirm">确定</el-button>
                <el-button @click="handleCancel">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref, watch, onMounted } from 'vue';
    import { queryTemplateList } from '@/api/patients/nutritionEducation';
import { json } from 'stream/consumers';

    const props = defineProps({
        visible: Boolean
    });
    const emit = defineEmits(['update:visible', 'select']);

    const searchValue = ref('');
    const treeData = ref<any[]>([]);
    const defaultProps = {
        children: 'children',
        label: 'label'
    };

    const handleSearch = async () => {
        await fetchTemplates();
    };

    const handleConfirm = () => {
        // 只传递有 template 字段的节点 
        emit('select', selectedTemplate.value || '');
        emit('update:visible', false);
    };

    const handleCancel = () => {
        emit('update:visible', false);
    };

    const selectedTemplate = ref<any>(null);

    const fetchTemplates = async () => {
        // Fetch template list from API
        const res = await queryTemplateList();
        treeData.value = res.data;        

    };

    const handleNodeClick = (data: any) => {
        selectedTemplate.value = data;
    };

    watch(() => props.visible, (val) => {
        if (val) fetchTemplates();
    });

    onMounted(() => {
        if (props.visible) fetchTemplates();
    });
</script>

<style scoped>
    .consultant-template-dialog .el-dialog__body {
        padding-top: 10px;
        padding-bottom: 0;
    }

    .dialog-header-row {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
    }

    .search-input {
        flex: 1;
        margin-right: 8px;
    }

    .search-btn {
        min-width: 60px;
    }

    .template-tree {
        margin: 12px 0 24px 0;
        min-height: 180px;
        max-height: 260px;
        overflow-y: auto;
        background: #fff;
        border: none;
    }

    .dialog-footer {
        display: flex;
        justify-content: center;
        gap: 16px;
        padding-bottom: 8px;
    }
</style>