<template>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="1000px" :modal="true" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="true" append-to-body lock-scroll :z-index="9999" destroy-on-close>
        <!-- 食谱选择模式 -->
        <div v-if="dialogType === 'recipe'" class="dialog-body">
            <div class="recipe-search">
                <div class="search-wrapper">
                    <el-input v-model="searchKeyword" placeholder="请输入食谱名称" clearable class="search-input">
                        <template #prefix>
                            <el-icon>
                                <Search />
                            </el-icon>
                        </template>
                    </el-input>
                    <el-button type="primary" class="search-btn">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                </div>
            </div>

            <div class="recipe-content">
                <div class="recipe-categories">
                    <div v-for="category in recipeCategories" :key="category.id" class="category-item" :class="{active: currentCategory === category.id}" @click.stop="selectCategory(category.id)">
                        {{ category.name }}
                    </div>
                </div>

                <div class="recipe-list">
                    <el-table ref="multipleTable" :data="recipeList" style="width: 100%" @selection-change="handleSelectionChange" border>
                        <el-table-column type="selection" width="55" />
                        <el-table-column prop="id" v-if="false" />
                        <el-table-column prop="name" label="食谱名称" min-width="200" />
                        <el-table-column prop="ingredients" label="食材名称/用量" min-width="300" show-overflow-tooltip />
                    </el-table>
                    <div class="pagination">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" :page-sizes="[10, 20, 50]" layout="total, sizes, prev, pager, next" small background @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>
            </div>

            <div class="selected-recipes">
                已选({{ selectedRecipes.length }})：
                <el-tag v-for="recipe in selectedRecipes" :key="recipe.id" closable size="small" @close.stop="removeSelectedRecipe(recipe)">
                    {{ recipe.name }}
                </el-tag>
            </div>
        </div>

        <!-- 食材选择模式 -->
        <div v-else-if="dialogType === 'food'" class="dialog-body">
            <div class="food-dialog-content">
                <div class="search-bar">
                    <el-input v-model="searchKeyword" placeholder="请输入食材名称" clearable class="search-input" />
                    <el-button type="primary" class="search-btn">
                        <el-icon>
                            <Search />
                        </el-icon>
                        查询
                    </el-button>
                </div>
                <div class="food-select-container">
                    <div class="food-categories">
                        <el-tree ref="treeRef" :data="foodCategories" :props="defaultProps" @node-click="handleNodeClick" default-expand-all />
                    </div>
                    <div class="food-list">
                        <el-table ref="foodTableRef" :data="foodList" style="width: 100%" @selection-change="handleFoodSelectionChange" :row-class-name="tableRowClassName">
                            <el-table-column type="selection" width="40" align="center" />
                            <el-table-column prop="name" label="食材名称" />
                        </el-table>
                        <div class="pagination">
                            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" :page-sizes="[20, 50, 100]" layout="total, sizes, prev, pager, next" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                        </div>
                    </div>
                </div>
                <div class="selected-tags">
                    <div class="selected-title">已选({{ selectedFoods.length }})：</div>
                    <div class="tags-container">
                        <el-tag v-for="item in selectedFoods" :key="item.name" class="selected-tag" closable @close="handleRemoveTag(item)">
                            {{ item.name }}
                        </el-tag>
                    </div>
                </div>
            </div>
        </div>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
    import { ref, computed, nextTick } from 'vue';
    import { Search } from '@element-plus/icons-vue';
    import { ElTree } from 'element-plus';
    import { ElTable } from 'element-plus';

    interface Recipe {
        id: number;
        name: string;
        categoryId: number;
        categoryName: string;
        ingredients: string;
    }

    interface Category {
        id: number;
        name: string;
    }

    interface Food {
        name: string;
    }

    interface Props {
        type ? : 'recipe' | 'food';
        title ? : string;
    }

    const props = withDefaults(defineProps < Props > (), {
        type: 'recipe',
        title: '添加食谱'
    });

    const emit = defineEmits < {
        (e: 'confirm', data: Recipe[] | Food[]): void;
        (e: 'cancel'): void;
    } > ();

    const dialogType = ref < 'recipe' | 'food' > ('recipe');
    const dialogTitle = computed(() => props.title);
    const dialogVisible = ref(false);
    const searchKeyword = ref('');
    const currentCategory = ref('');
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(1869);
    const selectedRecipes = ref < Recipe[] > ([]);
    const selectedFoods = ref < Food[] > ([]);
    const multipleTable = ref();
    const treeRef = ref < InstanceType < typeof ElTree >> ();
    const foodTableRef = ref < InstanceType < typeof ElTable >> ();

    // 食材分类树配置
    const defaultProps = {
        children: 'children',
        label: 'label'
    };

    // 食材分类数据
    const foodCategories = ref([{
            label: '调料类',
            children: [{ label: '中药' }, { label: '调料' }, { label: '盐' }]
        },
        {
            label: '油脂类',
            children: [{ label: '动物油' }, { label: '植物油' }]
        },
        {
            label: '奶及奶制品',
            children: [{ label: '奶饮料' }, { label: '饮料' }, { label: '植物奶制品' }, { label: '动物奶制品' }, { label: '动物奶' }]
        }
    ]);

    // 食材列表数据
    const foodList = ref < Food[] > ([
        { name: '苦菊1212' },
        { name: '水蛋蛋' },
        { name: '紫甘蓝' },
        { name: '三色米饭' },
        { name: '小番茄' },
        { name: '玉米粒' },
        { name: '白菜花' },
        { name: '鸡胸肉' },
        { name: '罗莎红生菜' }
    ]);

    // 模拟食谱分类数据
    const recipeCategories = ref < Category[] > ([
        { id: 11, name: '普食' },
        { id: 12, name: '软食' },
        { id: 13, name: '半流食' },
        { id: 14, name: '流食' },
        { id: 15, name: '低脂肪膳食' },
        { id: 16, name: '限制蛋白膳食' },
        { id: 17, name: '降血压食谱' },
        { id: 18, name: '肾病食谱' },
        { id: 19, name: '妊娠期食谱' },
        { id: 20, name: '月子餐' },
        { id: 21, name: '肝胆病食谱' },
        { id: 22, name: '学龄儿童生长迟缓营养餐' }
    ]);

    // 模拟食谱列表数据
    const recipeList = ref < Recipe[] > ([
        { id: 1, name: '蛋羹',categoryId:11,categoryName:"普食", ingredients: '鸡蛋（白皮）50.0000g; 盐1.0000g; 葱花1.0000g' },
        { id: 2, name: '炝炒西葫芦',categoryId:12,categoryName:"软食", ingredients: '盐1.0000g; 菜籽油5.0000ml; 西葫芦200.0000g' },
        { id: 3, name: '胡萝卜肉饼',categoryId:13,categoryName:"半流食", ingredients: '胡萝卜（红）50.0000g; 猪肉（肥、瘦）150.0000g' },
        { id: 4, name: '肉饼', categoryId:11,categoryName:"普食",ingredients: '猪肉（肥、瘦）150.0000g; 盐1.0000g; 葱花2.0000g' },
        { id: 5, name: '腌白菜',categoryId:12,categoryName:"软食", ingredients: '白菜（大白菜）150.0000g; 冰糖20.0000g' },
        { id: 6, name: '珍珠圆子', categoryId:11,categoryName:"普食",ingredients: '盐2.0000g; 酱油（味精）1.0000g; 淀粉50.0000g' },
        { id: 7, name: '豆腐虾仁汤',categoryId:13,categoryName:"半流食", ingredients: '豆腐250.0000g; 明虾50.0000g; 白菜100.0000g' },
        { id: 8, name: '番茄金针烩肉末',categoryId:11,categoryName:"普食", ingredients: '番茄（西红柿）50.0000g; 金针菇100.0000g' },
        { id: 9, name: '莴笋丝',categoryId:12,categoryName:"软食", ingredients: '莴笋笋（莴苣）100.0000g; 盐1.0000g; 油3.0000ml' },
        { id: 10, name: '清炒菜心',categoryId:11,categoryName:"普食", ingredients: '菜心200.0000g; 蒜末5.0000g; 盐1.0000g' }
    ]);

    // 食谱相关方法
    const selectCategory = (categoryId: string) => {
        currentCategory.value = categoryId;
        // TODO: 根据分类加载食谱列表
    };

    const handleSelectionChange = (selection: Recipe[]) => {
        selectedRecipes.value = selection;
    };

    const removeSelectedRecipe = (recipe: Recipe) => {
        selectedRecipes.value = selectedRecipes.value.filter((item) => item.id !== recipe.id);
        multipleTable.value ?.toggleRowSelection(recipe, false);
    };

    // 食材相关方法
    const handleNodeClick = (data: any) => {
        if (!data.children) {
            // 如果是叶子节点，加载对应分类的食材列表
            console.log('加载分类:', data.label);
        }
    };

    // 处理食材选择变化
    const handleFoodSelectionChange = (selection: Food[]) => {
        selectedFoods.value = selection.map((item) => ({
            name: item.name
        }));
    };

    // 移除标签
    const handleRemoveTag = (item: Food) => {
        selectedFoods.value = selectedFoods.value.filter((food) => food.name !== item.name);
        const foodToUnselect = foodList.value.find((food) => food.name === item.name);
        if (foodToUnselect) {
            foodTableRef.value ?.toggleRowSelection(foodToUnselect, false);
        }
    };

    const tableRowClassName = ({ row }: { row: any }) => {
        return selectedFoods.value.some((item) => item.name === row.name) ? 'selected-row' : '';
    };

    // 通用方法
    const handleSizeChange = (val: number) => {
        pageSize.value = val;
        // TODO: 重新加载数据
    };

    const handleCurrentChange = (val: number) => {
        currentPage.value = val;
        // TODO: 重新加载数据
    };

    // 打开弹窗方法
    const openDialog = (type: 'recipe' | 'food', initialData ? : Recipe[] | Food[]) => {
        dialogVisible.value = true;
        dialogType.value = type;

        if (type === 'recipe') {
            selectedRecipes.value = [];
            if (initialData) {
                selectedRecipes.value = [...(initialData as Recipe[])];
                nextTick(() => {
                    (initialData as Recipe[]).forEach((recipe) => {
                        const tableRecipe = recipeList.value.find((r) => r.id === recipe.id);
                        if (tableRecipe) {
                            multipleTable.value ?.toggleRowSelection(tableRecipe, true);
                        }
                    });
                });
            }
        } else if (type === 'food') {
            if (initialData && Array.isArray(initialData)) {
                // 确保初始数据是数组
                const initialFoods = initialData as Food[];
                selectedFoods.value = [...initialFoods];

                // 等待表格渲染完成后设置选中状态
                nextTick(() => {
                    // 先清除所有选中状态
                    foodTableRef.value ?.clearSelection();

                    // 遍历表格数据，找到匹配的项并设置选中
                    foodList.value.forEach((food) => {
                        const shouldSelect = initialFoods.some((selected) => selected.name === food.name);
                        if (shouldSelect) {
                            foodTableRef.value ?.toggleRowSelection(food, true);
                        }
                    });
                });
            } else {
                selectedFoods.value = [];
                nextTick(() => {
                    foodTableRef.value ?.clearSelection();
                });
            }
        }
    };

    // 关闭弹窗方法
    const closeDialog = () => {
        dialogVisible.value = false;
        selectedRecipes.value = [];
        selectedFoods.value = [];
    };

    // 确认选择
    const handleConfirm = () => {
        const result = dialogType.value === 'recipe' ? selectedRecipes.value : selectedFoods.value;
        emit('confirm', result);
        closeDialog();
    };

    // 取消选择
    const handleCancel = () => {
        emit('cancel');
        closeDialog();
    };

    // 暴露方法给父组件
    defineExpose({
        openDialog,
        closeDialog
    });
</script>

<style lang="scss" scoped>
    :deep(.el-dialog) {
        .el-dialog__header {
            margin: 0;
            padding: 20px 20px 0;

            .el-dialog__title {
                font-size: 16px;
                font-weight: 600;
                color: #303133;
            }
        }

        .el-dialog__body {
            padding: 20px;
        }

        .el-dialog__headerbtn {
            top: 20px;
        }
    }

    .dialog-body {
        .recipe-search {
            margin-bottom: 20px;

            .search-wrapper {
                display: flex;
                gap: 12px;
                align-items: center;

                .search-input {
                    flex: 1;

                    :deep(.el-input__wrapper) {
                        box-shadow: 0 0 0 1px #dcdfe6 inset;

                        &:hover {
                            box-shadow: 0 0 0 1px #c0c4cc inset;
                        }

                        &.is-focus {
                            box-shadow: 0 0 0 1px #409eff inset;
                        }
                    }

                    :deep(.el-input__prefix) {
                        color: #909399;
                    }
                }

                .search-btn {
                    min-width: 80px;

                    .el-icon {
                        margin-right: 4px;
                    }
                }
            }
        }

        .recipe-content {
            display: flex;
            gap: 12px;
            height: 480px;
            border: 1px solid #e4e7ed;
            border-radius: 4px;

            .recipe-categories {
                width: 240px;
                flex: 0 0 240px;
                border-right: 1px solid #e4e7ed;
                overflow-y: auto;

                .category-item {
                    padding: 12px 20px;
                    cursor: pointer;
                    color: #606266;
                    font-size: 14px;

                    &:hover {
                        background-color: #f5f7fa;
                    }

                    &.active {
                        background-color: #f0f7ff;
                        color: #409eff;
                    }
                }
            }

            .recipe-list {
                flex: 1;
                display: flex;
                flex-direction: column;
                overflow: hidden;
                background-color: #fff;

                :deep(.el-table) {
                    flex: 1;
                    overflow-y: auto;

                    .el-table__header {
                        th {
                            background-color: #f5f7fa;
                            color: #606266;
                            font-weight: 500;
                            padding: 8px 0;
                        }
                    }

                    .el-table__body {
                        td {
                            padding: 8px 0;
                        }
                    }

                    .cell {
                        color: #606266;
                    }
                }

                .pagination {
                    padding: 12px 20px;
                    display: flex;
                    justify-content: flex-end;
                    background-color: #fff;
                    border-top: 1px solid #e4e7ed;
                }
            }
        }

        .selected-recipes {
            margin-top: 16px;
            padding: 12px 16px;
            border-top: 1px solid #e4e7ed;
            color: #606266;
            font-size: 14px;
            min-height: 44px;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
            align-items: center;
        }
    }

    .food-dialog-content {
        .search-bar {
            margin-bottom: 16px;
            display: flex;
            align-items: center;
            gap: 12px;

            .search-input {
                flex: 1;
                min-width: 0;
            }

            .search-btn {
                flex-shrink: 0;
                min-width: 80px;
            }
        }

        .food-select-container {
            display: flex;
            gap: 16px;
            min-height: 400px;
            margin-bottom: 16px;

            .food-categories {
                width: 200px;
                border: 1px solid #e4e7ed;
                border-radius: 4px;
                overflow-y: auto;
            }

            .food-list {
                flex: 1;
                display: flex;
                flex-direction: column;

                :deep(.el-table) {
                    flex: 1;

                    .selected-row {
                        background-color: #f0f7ff;
                    }
                }

                .pagination {
                    margin-top: 16px;
                    display: flex;
                    justify-content: flex-end;
                }
            }
        }

        .selected-tags {
            border-top: 1px solid #e4e7ed;
            padding-top: 16px;
            min-height: 32px;
            display: flex;
            align-items: center;
            gap: 8px;
            flex-wrap: wrap;

            .selected-title {
                color: #606266;
                margin-bottom: 0;
                margin-right: 8px;
                white-space: nowrap;
            }

            .tags-container {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                align-items: center;

                .selected-tag {
                    margin-right: 0;
                    margin-bottom: 0;
                }
            }
        }
    }

    .dialog-footer {
        display: flex;
        justify-content: center;
        gap: 12px;

        .el-button {
            min-width: 100px;
        }
    }
</style>