<template>
    <div class="prescription-template-form">
        <!-- 返回按钮 -->
        <div class="header-actions">
            <el-button @click="handleBack" class="back-btn">返回</el-button>
        </div>

        <!-- 基本信息 -->
        <el-card shadow="hover" class="form-section">
            <template #header>
                <span class="section-title">基本信息</span>
            </template>
            <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="模板名称" prop="templateName" required>
                            <el-input v-model="form.templateName" placeholder="请输入" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="模板类型" prop="templateType" required>
                            <el-select v-model="form.templateType" placeholder="请选择模板类型" style="width: 100%"
                                :disabled="isEditMode">
                                <el-option label="个人模板" :value="0">
                                    <span style="float: left">个人模板</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">仅个人可见</span>
                                </el-option>
                                <el-option label="基础公共模板" :value="1">
                                    <span style="float: left">基础公共模板</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">全院通用</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="处方科室" prop="prescriptionDept" required>
                            <el-select v-model="form.prescriptionDept" placeholder="请选择处方科室" style="width: 100%"
                                :loading="deptLoading" clearable>
                                <el-option v-for="dept in prescriptionDepartments" :key="dept.deptId"
                                    :label="dept.deptName" :value="dept.deptId">
                                    <span style="float: left">{{ dept.deptName }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ dept.deptCategory ||
                                        '科室'
                                    }}</span>
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="模板描述" prop="templateDescription">
                    <el-input v-model="form.templateDescription" type="textarea" :rows="4" placeholder="请输入" />
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 营养产品配置 -->
        <el-card shadow="hover" class="form-section">
            <template #header>
                <span class="section-title">营养产品配置</span>
            </template>

            <!-- type=2 普通营养产品表格 -->
            <div v-if="contentType !== '3'" class="product-table-container">
                <el-table :data="productList" border style="width: 100%" class="product-table"
                    :header-cell-style="{ padding: '15px 12px' }" :cell-style="{ padding: '12px 12px' }">
                    <el-table-column prop="productName" label="营养产品" width="200" align="center">
                        <template #header>
                            <span class="important-label product-label">营养产品</span>
                        </template>
                        <template #default="{ row }">
                            <el-select v-model="row.productId" placeholder="请选择营养产品" size="small" style="width: 100%;"
                                filterable clearable :loading="loading"
                                @change="(value) => handleProductChange(value, row)">
                                <el-option v-for="product in nutritionOptions" :key="product.id"
                                    :label="`${product.productName} (${product.productSpec || ''})`"
                                    :value="product.id">
                                    <span style="float: left">{{ product.productName }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ product.brand
                                        }}</span>
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量" width="120" align="center">
                        <template #header>
                            <span class="important-label quantity-label">数量</span>
                        </template>
                        <template #default="{ row }">
                            <div class="quantity-input">
                                <el-input v-model="row.quantity" size="small" style="width: 60px;" />
                                <span class="unit">袋</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dosagePerTime" label="用量/次" width="140" align="center">
                        <template #default="{ row }">
                            <div class="dosage-input">
                                <el-input v-model="row.dosagePerTime" size="small" style="width: 60px;" />
                                <span class="unit">g</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="mealTime" label="餐次时间" width="160" align="center">
                        <template #default="{ row }">
                            <div class="meal-time-checkboxes">
                                <el-checkbox-group v-model="row.mealTime" size="small">
                                    <el-checkbox label="08:00" />
                                    <el-checkbox label="08:30" />
                                    <el-checkbox label="12:00" />
                                    <el-checkbox label="12:30" />
                                    <el-checkbox label="18:00" />
                                    <el-checkbox label="18:30" />
                                </el-checkbox-group>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="frequency" label="频次" width="120" align="center">
                        <template #default>
                            <span class="fixed-text">一天次</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dailyDosage" label="用量/日" width="140" align="center">
                        <template #default>
                            <span class="fixed-text">g</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="usageDays" label="使用天数" width="140" align="center">
                        <template #default="{ row }">
                            <div class="usage-days-input">
                                <el-button size="small" @click="decreaseUsageDays(row)"
                                    class="counter-btn">-</el-button>
                                <el-input v-model.number="row.usageDays" size="small"
                                    style="width: 50px; text-align: center;" />
                                <el-button size="small" @click="increaseUsageDays(row)"
                                    class="counter-btn">+</el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="specification" label="规格" width="140" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.specification" placeholder="自动填充" size="small" readonly />
                        </template>
                    </el-table-column>
                    <!-- type=2 时显示的额外字段 -->
                    <el-table-column v-if="contentType === '2'" prop="preparationVolumePerTime" label="制剂液量/次"
                        width="170" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.preparationVolumePerTime" placeholder="请输入" size="small">
                                <template #append>ml</template>
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="contentType === '2'" prop="preparationConcentrationPerTime" label="制剂浓度/次"
                        width="170" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.preparationConcentrationPerTime" placeholder="请输入" size="small">
                                <template #append>%</template>
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="contentType === '2'" prop="energyDensityPerTime" label="能量密度/次" width="200"
                        align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.energyDensityPerTime" placeholder="请输入" size="small">
                                <template #append>kcal/ml</template>
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="usage" label="用法" width="160" align="center">
                        <template #default="{ row }">
                            <el-select v-model="row.usage" placeholder="请选择用法" size="small" style="width: 100%;"
                                clearable :loading="dictLoading">
                                <el-option v-for="dict in usageDictOptions" :key="dict.dictValue"
                                    :label="dict.dictLabel" :value="dict.dictValue" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" width="160" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.remark" placeholder="请输入" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="dailyCalorie" label="每日热量" width="140" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.dailyCalorie" placeholder="0" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额" width="120" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.amount" placeholder="0.00" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="140" align="center" fixed="right">
                        <template #default="{ $index }">
                            <el-button type="danger" size="small" @click="removeProduct($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 暂无数据状态 -->
                <div v-if="productList.length === 0" class="empty-state">
                    <div class="empty-text">暂无数据</div>
                </div>

                <!-- 新增营养产品按钮 - 始终显示 -->
                <div class="add-product-button" style="margin-top: 20px;">
                    <el-button type="primary" @click="addProduct">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        新增营养产品
                    </el-button>
                </div>
            </div>

            <!-- type=3 分组营养产品 -->
            <div v-else class="grouped-product-container">
                <!-- 统一的分组产品表格 -->
                <el-table :data="groupedProductList" border style="width: 100%" class="unified-group-table">
                    <el-table-column type="index" label="组号" width="80" align="center">
                        <template #header>
                            <span class="important-label">组号</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="营养产品" min-width="300" align="center">
                        <template #header>
                            <span class="important-label product-label">营养产品</span>
                        </template>
                        <template #default="{ row, $index }">
                            <div class="product-group">
                                <div v-for="(product, productIndex) in row.products" :key="productIndex"
                                    class="product-row" style="margin-bottom: 5px">
                                    <el-select v-model="product.productId" placeholder="请选择营养产品" size="small"
                                        style="flex: 1;" filterable clearable :loading="loading"
                                        @change="(value) => handleGroupedProductChange(value, product)">
                                        <el-option v-for="option in nutritionOptions" :key="option.id"
                                            :label="`${option.productName} (${option.productSpec || ''})`"
                                            :value="option.id">
                                            <span style="float: left">{{ option.productName }}</span>
                                            <span style="float: right; color: #8492a6; font-size: 13px">{{
                                                option.brand
                                                }}</span>
                                        </el-option>
                                    </el-select>
                                    <div class="action-buttons">
                                        <el-button class="icon-btn" @click="addProductToGroup($index)">
                                            <el-icon>
                                                <Plus />
                                            </el-icon>
                                        </el-button>
                                        <el-button class="icon-btn"
                                            @click="removeProductFromGroup($index, productIndex)"
                                            :disabled="row.products.length <= 1">
                                            <el-icon>
                                                <Minus />
                                            </el-icon>
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="数量" min-width="120" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.quantity" size="small" style="width: 60px;" />
                                    <span class="unit">袋</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="用量/次" min-width="150" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.dosagePerTime" size="small" style="width: 60px;" />
                                    <span class="unit">g</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="mealTime" label="餐次时间" min-width="160" align="center">
                        <template #default="{ row }">
                            <div class="meal-time-checkboxes">
                                <el-checkbox-group v-model="row.mealTime" size="small">
                                    <el-checkbox label="08:00" />
                                    <el-checkbox label="08:30" />
                                    <el-checkbox label="12:00" />
                                    <el-checkbox label="12:30" />
                                    <el-checkbox label="18:00" />
                                    <el-checkbox label="18:30" />
                                </el-checkbox-group>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="frequency" label="频次" min-width="100" align="center">
                        <template #default>
                            <span class="fixed-text">一天次</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="dailyDosage" label="用量/日" min-width="120" align="center">
                        <template #default>
                            <span class="fixed-text">g</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="usageDays" label="使用天数" min-width="120" align="center">
                        <template #default="{ row }">
                            <div class="usage-days-input">
                                <el-button size="small" @click="decreaseUsageDays(row)"
                                    class="counter-btn">-</el-button>
                                <el-input v-model.number="row.usageDays" size="small"
                                    style="width: 50px; text-align: center;" />
                                <el-button size="small" @click="increaseUsageDays(row)"
                                    class="counter-btn">+</el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="规格" min-width="120" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.specification" placeholder="自动填充" size="small"
                                        readonly />
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <!-- type=2 时显示的额外字段 -->
                    <el-table-column v-if="contentType === '2'" label="制剂液量/次" min-width="170" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.preparationVolumePerTime" placeholder="请输入"
                                        size="small" />
                                    <span class="unit">ml</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="contentType === '2'" label="制剂浓度/次" min-width="170" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.preparationConcentrationPerTime" placeholder="请输入"
                                        size="small" />
                                    <span class="unit">%</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column v-if="contentType === '2'" label="能量密度/次" min-width="170" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.energyDensityPerTime" placeholder="请输入" size="small" />
                                    <span class="unit">kcal/ml</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="用法" min-width="140" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-select v-model="product.usage" placeholder="请选择用法" size="small"
                                        style="width: 100%;" clearable :loading="dictLoading">
                                        <el-option v-for="dict in usageDictOptions" :key="dict.dictValue"
                                            :label="dict.dictLabel" :value="dict.dictValue" />
                                    </el-select>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" min-width="140" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.remark" placeholder="请输入" size="small" />
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="每日热量" min-width="120" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.dailyCalorie" placeholder="0" size="small" />
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="金额" min-width="100" align="center">
                        <template #default="{ row }">
                            <div class="dosage-group">
                                <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
                                    <el-input v-model="product.amount" placeholder="0.00" size="small" />
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120" align="center" fixed="right">
                        <template #default="{ $index }">
                            <el-button type="danger" size="small" @click="removeGroup($index)"
                                :disabled="groupedProductList.length <= 1">
                                删除组
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 暂无数据状态 -->
                <div v-if="groupedProductList.length === 0" class="empty-state">
                    <div class="empty-text">暂无数据</div>
                    <div class="add-product-link" @click="addProduct">+ 添加营养产品组</div>
                </div>

                <!-- 添加分组按钮 -->
                <div class="add-group-button" style="margin-top: 20px;">
                    <el-button type="primary" @click="addProduct">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        新增分组
                    </el-button>
                </div>
            </div>

            <!-- 底部操作栏 -->
            <div class="product-actions">
                <div class="left-actions">
                    <el-button v-if="contentType !== '3'" type="primary" plain
                        @click="batchAddProducts">批量添加营养产品</el-button>
                    <el-button v-if="contentType !== '3'" type="danger" plain @click="deleteSelected">删除</el-button>
                </div>
                <div class="cost-display">
                    费用: <span class="cost-amount">0.00</span>
                </div>
            </div>
        </el-card>

        <!-- 营养耗材配置 -->
        <el-card shadow="hover" class="form-section" v-if="contentType === '3' || contentType === '4'">
            <template #header>
                <span class="section-title">营养耗材配置</span>
            </template>

            <!-- 营养耗材表格 -->
            <div class="supplies-table-container">
                <el-table :data="suppliesList" border style="width: 100%" class="supplies-table"
                    :header-cell-style="{ padding: '15px 12px' }" :cell-style="{ padding: '12px 12px' }">
                    <el-table-column type="index" label="编号" width="100" align="center" />
                    <el-table-column prop="suppliesName" label="耗材" min-width="180" align="center">
                        <template #header>
                            <span class="important-label supplies-label">耗材</span>
                        </template>
                        <template #default="{ row }">
                            <el-select v-model="row.suppliesId" placeholder="请选择耗材" size="small" style="width: 100%;"
                                filterable clearable :loading="loading"
                                @change="(value) => handleSuppliesChange(value, row)">
                                <el-option v-for="consumable in nutritionConsumable" :key="consumable.id"
                                    :label="`${consumable.consumable} (${consumable.specification || ''})`"
                                    :value="consumable.id">
                                    <span style="float: left">{{ consumable.consumable }}</span>
                                    <span style="float: right; color: #8492a6; font-size: 13px">{{ consumable.groupNo ||
                                        '耗材'
                                    }}</span>
                                </el-option>
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column prop="specification" label="规格" min-width="120" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.specification" placeholder="自动填充" size="small" readonly />
                        </template>
                    </el-table-column>
                    <el-table-column prop="dosagePerTime" label="用量/次" min-width="100" align="center">
                        <template #header>
                            <span class="important-label dosage-label">用量/次</span>
                        </template>
                        <template #default="{ row }">
                            <el-input v-model="row.dosagePerTime" size="small" placeholder="请输入" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="frequency" label="频次" min-width="90" align="center">
                        <template #header>
                            <span class="important-label frequency-label">频次</span>
                        </template>
                        <template #default="{ row }">
                            <el-input v-model="row.frequency" size="small" placeholder="请输入" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="dailyDosage" label="用量/日" min-width="100" align="center">
                        <template #header>
                            <span class="important-label daily-dosage-label">用量/日</span>
                        </template>
                        <template #default="{ row }">
                            <el-input v-model="row.dailyDosage" size="small" placeholder="请输入" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="usageDays" label="使用天数" min-width="120" align="center">
                        <template #header>
                            <span class="important-label usage-days-label">使用天数</span>
                        </template>
                        <template #default="{ row }">
                            <div class="usage-days-input">
                                <el-button size="small" @click="decreaseSuppliesUsageDays(row)"
                                    class="counter-btn">-</el-button>
                                <el-input v-model.number="row.usageDays" size="small"
                                    style="width: 50px; text-align: center;" />
                                <el-button size="small" @click="increaseSuppliesUsageDays(row)"
                                    class="counter-btn">+</el-button>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量" min-width="80" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.quantity" size="small" placeholder="请输入" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" min-width="120" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.remark" placeholder="请输入" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="amount" label="金额" min-width="90" align="center">
                        <template #default="{ row }">
                            <el-input v-model="row.amount" placeholder="0.00" size="small" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center" fixed="right">
                        <template #default="{ $index }">
                            <el-button type="danger" size="small" @click="removeSupplies($index)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- 暂无数据状态 -->
                <div v-if="suppliesList.length === 0" class="empty-state">
                    <div class="empty-text">暂无数据</div>
                </div>
            </div>

            <!-- 底部操作栏 -->
            <div class="supplies-actions">
                <div class="cost-display">
                    耗材费用: <span class="supplies-cost-amount">0.00</span>
                </div>
            </div>
        </el-card>

        <!-- 营养分析 -->
        <el-card shadow="hover" class="form-section">
            <template #header>
                <span class="section-title">营养分析</span>
            </template>

            <!-- 分析选项卡 -->
            <el-tabs v-model="activeTab" class="nutrition-tabs">
                <el-tab-pane label="三大营养素分析" name="nutrition">
                    <div class="nutrition-analysis">
                        <!-- 营养设定 -->
                        <div class="calorie-info">
                            <span>营养设定: {{ totalNutrition.totalCalorie.toFixed(2) }}kcal/d</span>
                        </div>

                        <!-- 分析内容 -->
                        <div class="analysis-content">
                            <!-- 营养成分表 -->
                            <div class="nutrition-table">
                                <el-table :data="nutritionData" border style="width: 100%">
                                    <el-table-column prop="nutrient" label="三大营养素" width="120" align="center" />
                                    <el-table-column prop="mass" label="质量(g)" width="100" align="center" />
                                    <el-table-column prop="calorieRatio" label="热量占比" width="100" align="center" />
                                    <el-table-column prop="reference" label="参考值" width="100" align="center" />
                                </el-table>
                            </div>

                            <!-- 饼图 -->
                            <div class="chart-container">
                                <div class="chart-title">三大营养素元素质量占比</div>
                                <div class="pie-chart">
                                    <div class="chart-placeholder">
                                        <svg width="200" height="200" viewBox="0 0 200 200">
                                            <circle cx="100" cy="100" r="80" fill="none" stroke="#00bcd4"
                                                stroke-width="20" stroke-dasharray="0 502"
                                                transform="rotate(-90 100 100)" />
                                            <circle cx="100" cy="100" r="80" fill="none" stroke="#ffc107"
                                                stroke-width="20" stroke-dasharray="0 502"
                                                transform="rotate(-90 100 100)" />
                                            <circle cx="100" cy="100" r="80" fill="none" stroke="#2196f3"
                                                stroke-width="20" stroke-dasharray="0 502"
                                                transform="rotate(-90 100 100)" />
                                            <circle cx="100" cy="100" r="30" fill="white" />
                                        </svg>
                                    </div>
                                </div>
                                <div class="chart-legend">
                                    <div class="legend-item">
                                        <span class="legend-color protein"></span>
                                        <span>蛋白质 {{ nutritionData[0].calorieRatio }}</span>
                                    </div>
                                    <div class="legend-item">
                                        <span class="legend-color fat"></span>
                                        <span>脂肪 {{ nutritionData[1].calorieRatio }}</span>
                                    </div>
                                    <div class="legend-item">
                                        <span class="legend-color carb"></span>
                                        <span>碳水化合物 {{ nutritionData[2].calorieRatio }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="营养数据分析" name="data">
                    <div class="data-analysis">
                        <RightCard :nutritionProducts="nutritionProductsForAnalysis" />
                    </div>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 提交按钮 -->
        <div class="submit-section">
            <el-button type="primary" size="large" @click="handleSubmit" :loading="submitting" :disabled="submitting">
                {{ submitting ? (isEditMode ? '修改中...' : '提交中...') : (isEditMode ? '修改' : '提交') }}
            </el-button>
        </div>

        <!-- 批量添加营养产品对话框 -->
        <el-dialog v-model="batchDialogVisible" title="批量添加营养产品" width="800px" :close-on-click-modal="false">
            <div class="batch-add-content">
                <div class="search-section">
                    <el-input v-model="searchKeyword" placeholder="搜索营养产品名称、品牌或规格..." prefix-icon="Search" clearable
                        style="margin-bottom: 20px;" />
                </div>

                <div class="product-selection">
                    <el-checkbox-group v-model="selectedProducts" class="product-checkbox-group">
                        <div v-for="product in filteredNutritionOptions" :key="product.id" class="product-item">
                            <el-checkbox :label="product.id">
                                <div class="product-info">
                                    <div class="product-name">{{ product.productName }}</div>
                                    <div class="product-details">
                                        <span>品牌: {{ product.brand || '未知' }}</span>
                                        <span>规格: {{ product.productSpec || '未知' }}</span>
                                        <span>厂商: {{ product.manufacturer || '未知' }}</span>
                                    </div>
                                </div>
                            </el-checkbox>
                        </div>
                    </el-checkbox-group>
                </div>

                <div v-if="filteredNutritionOptions.length === 0" class="no-products">
                    <el-empty description="暂无匹配的营养产品" />
                </div>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="batchDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmBatchAdd">
                        确定添加 ({{ selectedProducts.length }})
                    </el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, Collection, Minus } from '@element-plus/icons-vue'
import { listAllNutrition } from '@/api/warehouse/productNutrition/index'
import { NutritionVO } from '@/api/warehouse/productNutrition/types'
import { getDicts } from '@/api/system/dict/data/index'
import { DictDataVO } from '@/api/system/dict/data/types'
import { addEnteralNutritionTemplate, updateEnteralNutritionTemplate, getEnteralNutritionTemplate } from '@/api/parameter/basicPublicTemplate/enteralNutritionTemplate/index'
import { EnteralNutritionTemplateForm, EnteralNutritionTemplateVO } from '@/api/parameter/basicPublicTemplate/enteralNutritionTemplate/types'
import { listDept } from '@/api/system/dept/index'
import { DeptVO } from '@/api/system/dept/types'
import { listAll as listAllSupplies } from '@/api/warehouse/suppliesManage/index'
import { SuppliesManageVO } from '@/api/warehouse/suppliesManage/types'
import { listAllNutritionConsumable } from '@/api/patients/nutritionConsumable/index'
import { NutritionConsumableVO } from '@/api/patients/nutritionConsumable/types'
import RightCard from '@/views/patients/enteralNutrition/components/RightCard.vue'

const router = useRouter()
const route = useRoute()

// 表单数据
const form = reactive({
    templateName: '',
    prescriptionDept: '',
    templateDescription: '',
    templateType: 1  // 默认为基础公共模板
})

const contentType = ref();

// 编辑模式相关状态
const isEditMode = ref(false)
const templateId = ref<string | number>('')

// 表单验证规则
const rules = {
    templateName: [
        { required: true, message: '请输入模板名称', trigger: 'blur' }
    ],
    prescriptionDept: [
        { required: true, message: '请选择处方科室', trigger: 'change' }
    ],
    templateType: [
        { required: true, message: '请选择模板类型', trigger: 'change' }
    ]
}

// 科室数据存储（从后端获取）
const prescriptionDepartments = ref<DeptVO[]>([])
const deptLoading = ref(false)

// 营养产品列表
const productList = ref([])

// 分组营养产品列表（用于type=3的情况）
const groupedProductList = ref([])

// 当前组号计数器
const currentGroupNo = ref(1)



// 营养产品选项列表（从后端获取的所有营养产品）
const nutritionOptions = ref<NutritionVO[]>([])

// 营养耗材列表
const suppliesList = ref([])

// 耗材选项列表（从后端获取的所有耗材）
const suppliesOptions = ref<SuppliesManageVO[]>([])

// 营养耗材数据（从后端获取的营养耗材数据）
const nutritionConsumable = ref<NutritionConsumableVO[]>([])

// 加载状态
const loading = ref(false)

// 字典数据存储（用法字典）
const usageDictOptions = ref<DictDataVO[]>([])
const dictLoading = ref(false)

// 提交状态管理
const submitting = ref(false)

// 计算总营养成分
const totalNutrition = computed(() => {
    let totalCalorie = 0
    let totalProtein = 0
    let totalFat = 0
    let totalCarbohydrate = 0

    // 根据contentType选择不同的产品列表
    const allProducts = contentType.value === '3'
        ? groupedProductList.value.flatMap(group => group.products)
        : productList.value

    allProducts.forEach(product => {
        if (product.productId && product.dailyDosage) {
            const selectedProduct = nutritionOptions.value.find(p => p.id === product.productId)
            if (selectedProduct) {
                const dailyDosage = parseFloat(product.dailyDosage) || 0

                // 使用新的计算公式：calorie / 100 * 用量/日
                totalCalorie += (selectedProduct.calorie || 0) / 100 * dailyDosage

                // 营养成分计算使用原有逻辑 (营养成分按100g计算)
                const multiplier = dailyDosage / 100
                totalProtein += (selectedProduct.protein || 0) * multiplier
                totalFat += (selectedProduct.fat || 0) * multiplier
                totalCarbohydrate += (selectedProduct.carbohydrate || 0) * multiplier
            }
        }
    })

    return {
        totalCalorie,
        totalProtein,
        totalFat,
        totalCarbohydrate
    }
})

// 营养分析数据
const nutritionData = computed(() => {
    const { totalCalorie, totalProtein, totalFat, totalCarbohydrate } = totalNutrition.value

    const proteinCalorie = totalProtein * 4 // 蛋白质每克4千卡
    const fatCalorie = totalFat * 9 // 脂肪每克9千卡
    const carbCalorie = totalCarbohydrate * 4 // 碳水化合物每克4千卡

    const totalMacroCalorie = proteinCalorie + fatCalorie + carbCalorie

    return [
        {
            nutrient: '蛋白质',
            mass: totalProtein.toFixed(1),
            calorieRatio: totalMacroCalorie > 0 ? ((proteinCalorie / totalMacroCalorie) * 100).toFixed(1) + '%' : '0%',
            reference: '10% - 15%'
        },
        {
            nutrient: '脂肪',
            mass: totalFat.toFixed(1),
            calorieRatio: totalMacroCalorie > 0 ? ((fatCalorie / totalMacroCalorie) * 100).toFixed(1) + '%' : '0%',
            reference: '20% - 30%'
        },
        {
            nutrient: '碳水化合物',
            mass: totalCarbohydrate.toFixed(1),
            calorieRatio: totalMacroCalorie > 0 ? ((carbCalorie / totalMacroCalorie) * 100).toFixed(1) + '%' : '0%',
            reference: '50% - 65%'
        }
    ]
})

// 为RightCard组件准备营养产品数据
const nutritionProductsForAnalysis = computed(() => {
    const products: Array<{
        name: string,
        productCode: string,
        type: string,
        protein?: number,
        fat?: number,
        carbohydrate?: number,
        dosePerTime?: number,
        quantity?: number
    }> = []

    // 根据contentType选择不同的产品列表
    const allProducts = contentType.value === '3'
        ? groupedProductList.value.flatMap(group => group.products)
        : productList.value

    allProducts.forEach(product => {
        if (product.productId && product.dailyDosage) {
            const selectedProduct = nutritionOptions.value.find(p => p.id === product.productId)
            if (selectedProduct) {
                const dailyDosage = parseFloat(product.dailyDosage) || 0

                products.push({
                    name: selectedProduct.productName || '未知产品',
                    productCode: selectedProduct.productCode || '无编码',
                    type: '肠内',
                    protein: selectedProduct.protein || 0,
                    fat: selectedProduct.fat || 0,
                    carbohydrate: selectedProduct.carbohydrate || 0,
                    dosePerTime: dailyDosage, // 这里使用用量/日作为用量/次
                    quantity: 1 // 模板中单个产品数量为1
                })
            }
        }
    })

    console.log('模板页面为RightCard准备的营养产品数据:', products)
    return products
})

// 当前选中的分析选项卡
const activeTab = ref('nutrition')

// 表单引用
const formRef = ref()

// 获取科室列表
const fetchPrescriptionDepartments = async () => {
    try {
        deptLoading.value = true

        // 从后端获取科室数据
        console.log('从后端获取科室数据...')
        const response = await listDept()

        // 根据后端返回的状态处理
        if (response && response.code === 200) {
            // 将信息记录到变量prescriptionDepartments中
            prescriptionDepartments.value = response.data || []
            console.log('科室数据获取成功:', prescriptionDepartments.value.length, '条')
        } else {
            // 提示异常信息
            console.warn('科室数据格式异常:', response)
            ElMessage.warning('科室数据获取异常')
        }
    } catch (error) {
        console.error('获取科室列表失败:', error)
        ElMessage.error('获取科室列表失败')
    } finally {
        deptLoading.value = false
    }
}

// 获取字典数据（用法）
const fetchUsageDictOptions = async () => {
    try {
        dictLoading.value = true

        // 从后端获取字典数据
        console.log('从后端获取用法字典数据...')
        const response = await getDicts('default_usage')

        if (response && response.code === 200) {
            // 只取dictValue和dictLabel作为字典对象
            usageDictOptions.value = response.data.map((item: DictDataVO) => ({
                dictValue: item.dictValue,
                dictLabel: item.dictLabel,
                dictCode: item.dictCode,
                dictSort: item.dictSort
            }))

            console.log('用法字典数据获取成功:', usageDictOptions.value.length, '条')
        } else {
            console.warn('用法字典数据格式异常:', response)
            ElMessage.warning('用法字典数据获取异常')
        }
    } catch (error) {
        console.error('获取用法字典数据失败:', error)
        ElMessage.error('获取用法字典数据失败')
    } finally {
        dictLoading.value = false
    }
}

// 获取营养产品列表
const fetchNutritionOptions = async () => {
    try {
        loading.value = true

        // 从后端获取数据
        console.log('从后端获取营养产品数据...')
        const response = await listAllNutrition()
        if (response && response.code === 200) {
            nutritionOptions.value = response.rows
        } else {
            console.warn('营养产品数据格式异常:', response)
            ElMessage.warning('营养产品数据获取异常')
        }
    } catch (error) {
        console.error('获取营养产品列表失败:', error)
        ElMessage.error('获取营养产品列表失败')
    } finally {
        loading.value = false
    }
}

// 获取耗材列表
const fetchSuppliesOptions = async () => {
    try {
        loading.value = true

        // 从后端获取数据
        console.log('从后端获取耗材数据...')
        const response = await listAllSupplies()
        if (response && response.code === 200) {
            suppliesOptions.value = response.rows
        } else {
            console.warn('耗材数据格式异常:', response)
            ElMessage.warning('耗材数据获取异常')
        }
    } catch (error) {
        console.error('获取耗材列表失败:', error)
        ElMessage.error('获取耗材列表失败')
    } finally {
        loading.value = false
    }
}

// 获取营养耗材数据
const fetchNutritionConsumable = async () => {
    try {
        loading.value = true

        // 从后端获取营养耗材数据
        console.log('从后端获取营养耗材数据...')
        const response = await listAllNutritionConsumable()

        // 根据后端返回的状态处理
        if (response && response.code === 200) {
            // 将后端返回来的数据全部放入变量nutritionConsumable中
            nutritionConsumable.value = response.rows || []
            console.log('营养耗材数据获取成功:', nutritionConsumable.value.length, '条')
        } else {
            // 提示异常信息
            console.warn('营养耗材数据格式异常:', response)
            ElMessage.warning('营养耗材数据获取异常')
        }
    } catch (error) {
        console.error('获取营养耗材数据失败:', error)
        ElMessage.error('获取营养耗材数据失败')
    } finally {
        loading.value = false
    }
}

// 获取模板详情（编辑模式）
const fetchTemplateDetail = async (id: string | number) => {
    try {
        loading.value = true
        console.log('从后端获取模板详情...', id)

        const response = await getEnteralNutritionTemplate(id)

        // 根据后端返回的状态处理
        if (response && response.code === 200) {
            const templateData: EnteralNutritionTemplateVO = response.data
            console.log('模板详情获取成功:', templateData)

            // 将数据填入页面
            form.templateName = templateData.templateName
            form.templateDescription = templateData.templateDescription
            form.prescriptionDept = templateData.prescriptionId
            form.templateType = templateData.templateType || 1  // 如果没有templateType字段，默认为基础公共模板

            // 解析营养产品信息并填入产品列表
            if (templateData.content) {
                try {
                    const contentData = JSON.parse(templateData.content)

                    // 如果是新的数据结构（包含product和consumable）
                    if (contentData.product || contentData.consumable || contentData.products || contentData.supplies) {
                        // 处理营养产品数据（支持新旧字段名）
                        const productData = contentData.product || contentData.products
                        if (productData && Array.isArray(productData)) {
                            if (contentType.value === '3') {
                                // type=3时，按分组处理产品数据
                                if (productData.length > 0 && productData[0].groupId && productData[0].content) {
                                    // 新格式：{ groupId: "xxx", content: [...] }
                                    console.log('检测到新的分组数据格式')
                                    let maxGroupNo = 0

                                    groupedProductList.value = productData.map(group => {
                                        const groupNo = parseInt(group.groupId) || 1
                                        maxGroupNo = Math.max(maxGroupNo, groupNo)

                                        return {
                                            groupNo: groupNo,
                                            products: group.content.map(product => ({
                                                groupNo: groupNo,
                                                productId: product.id || '',
                                                productName: product.productName || '',
                                                quantity: product.quantity || '',
                                                dosagePerTime: product.dosagePerTime || '',
                                                mealTime: product.mealTime || [],
                                                frequency: product.frequency || '一天次',
                                                dailyDosage: product.dailyDosage || 'g',
                                                usageDays: product.usageDays || 1,
                                                specification: product.specification || '',
                                                // type=2 时的额外字段
                                                preparationVolumePerTime: product.preparationVolumePerTime || '',
                                                preparationConcentrationPerTime: product.preparationConcentrationPerTime || '',
                                                energyDensityPerTime: product.energyDensityPerTime || '',
                                                usage: product.usage || '',
                                                remark: product.remark || '',
                                                dailyCalorie: product.dailyCalorie || '',
                                                amount: product.amount || ''
                                            }))
                                        }
                                    })

                                    currentGroupNo.value = maxGroupNo + 1
                                } else {
                                    // 旧格式：展平的产品数组，包含 groupNo 字段
                                    console.log('检测到旧的分组数据格式，进行兼容处理')
                                    const groupsMap = new Map()
                                    let maxGroupNo = 0

                                    productData.forEach(product => {
                                        const groupNo = product.groupNo || 1
                                        maxGroupNo = Math.max(maxGroupNo, groupNo)

                                        if (!groupsMap.has(groupNo)) {
                                            groupsMap.set(groupNo, {
                                                groupNo: groupNo,
                                                products: []
                                            })
                                        }

                                        groupsMap.get(groupNo).products.push({
                                            groupNo: groupNo,
                                            productId: product.id || '',
                                            productName: product.productName || '',
                                            quantity: product.quantity || '',
                                            dosagePerTime: product.dosagePerTime || '',
                                            mealTime: product.mealTime || [],
                                            frequency: product.frequency || '一天次',
                                            dailyDosage: product.dailyDosage || 'g',
                                            usageDays: product.usageDays || 1,
                                            specification: product.specification || '',
                                            // type=2 时的额外字段
                                            preparationVolumePerTime: product.preparationVolumePerTime || '',
                                            preparationConcentrationPerTime: product.preparationConcentrationPerTime || '',
                                            energyDensityPerTime: product.energyDensityPerTime || '',
                                            usage: product.usage || '',
                                            remark: product.remark || '',
                                            dailyCalorie: product.dailyCalorie || '',
                                            amount: product.amount || ''
                                        })
                                    })

                                    groupedProductList.value = Array.from(groupsMap.values())
                                    currentGroupNo.value = maxGroupNo + 1
                                }
                            } else {
                                // type=2或其他情况，处理普通产品数据
                                productList.value = productData.map(product => ({
                                    productId: product.id || '',
                                    productName: product.productName || '',
                                    quantity: product.quantity || '',
                                    dosagePerTime: product.dosagePerTime || '',
                                    mealTime: product.mealTime || [],
                                    frequency: product.frequency || '一天次',
                                    dailyDosage: product.dailyDosage || 'g',
                                    usageDays: product.usageDays || 1,
                                    specification: product.specification || '',
                                    // type=2 时的额外字段
                                    preparationVolumePerTime: product.preparationVolumePerTime || '',
                                    preparationConcentrationPerTime: product.preparationConcentrationPerTime || '',
                                    energyDensityPerTime: product.energyDensityPerTime || '',
                                    usage: product.usage || '',
                                    remark: product.remark || '',
                                    dailyCalorie: product.dailyCalorie || '',
                                    amount: product.amount || ''
                                }))
                            }
                        }

                        // 处理耗材数据（支持新旧字段名）
                        const consumableData = contentData.consumable || contentData.supplies
                        if (consumableData && Array.isArray(consumableData)) {
                            suppliesList.value = consumableData.map(supplies => ({
                                suppliesId: supplies.id || '',
                                suppliesName: supplies.suppliesName || supplies.consumable || '',
                                specification: supplies.specification || '',
                                dosagePerTime: supplies.dosagePerTime || supplies.dosePerTime || '',
                                frequency: supplies.frequency || '',
                                dailyDosage: supplies.dailyDosage || supplies.dosePerDay || '',
                                usageDays: supplies.usageDays || 1,
                                quantity: supplies.quantity || '',
                                remark: supplies.remark || supplies.prescriptionRemark || '',
                                amount: supplies.amount || ''
                            }))
                        } else {
                            // 如果没有耗材数据，根据产品数据创建对应的空耗材行
                            if (contentType.value === '3' && groupedProductList.value.length > 0) {
                                // type=3时，为每个分组创建对应的空耗材行
                                suppliesList.value = groupedProductList.value.map(() => createNewSupplies())
                                console.log('分组模式：为每个分组创建空耗材行')
                            } else if (productList.value.length > 0) {
                                // 普通模式，为每个营养产品创建对应的空耗材行
                                suppliesList.value = productList.value.map(() => createNewSupplies())
                            }
                        }
                    } else if (Array.isArray(contentData)) {
                        // 兼容旧的数据结构（只有营养产品）
                        productList.value = contentData.map(product => ({
                            productId: product.id || '',
                            productName: product.productName || '',
                            quantity: product.quantity || '',
                            dosagePerTime: product.dosagePerTime || '',
                            mealTime: product.mealTime || [],
                            frequency: product.frequency || '一天次',
                            dailyDosage: product.dailyDosage || 'g',
                            usageDays: product.usageDays || 1,
                            specification: product.specification || '',
                            usage: product.usage || '',
                            remark: product.remark || '',
                            dailyCalorie: product.dailyCalorie || '',
                            amount: product.amount || ''
                        }))

                        // 为每个营养产品创建对应的空耗材行
                        suppliesList.value = productList.value.map(() => createNewSupplies())
                    }
                } catch (parseError) {
                    console.error('解析内容数据失败:', parseError)
                    ElMessage.warning('内容数据解析异常')
                }
            }
        } else {
            // 提示异常信息
            console.warn('模板详情数据格式异常:', response)
            ElMessage.error(response?.msg || '模板详情获取失败')
        }
    } catch (error) {
        console.error('获取模板详情失败:', error)
        ElMessage.error('获取模板详情失败')
    } finally {
        loading.value = false
    }
}

// 创建新产品数据
const createNewProduct = () => {
    return {
        productId: '', // 添加产品ID字段
        productName: '',
        quantity: '',
        dosagePerTime: '',
        mealTime: [],
        frequency: '一天次', // 写死为"一天次"
        dailyDosage: 'g', // 写死为"g"
        usageDays: 1,
        specification: '',
        // type=2 时的额外字段
        preparationVolumePerTime: '',
        preparationConcentrationPerTime: '',
        energyDensityPerTime: '',
        usage: '',
        remark: '',
        dailyCalorie: '',
        amount: ''
    }
}

// 创建新的分组产品数据
const createNewGroupedProduct = (groupNo: number) => {
    return {
        groupNo: groupNo,
        productId: '',
        productName: '',
        quantity: '',
        dosagePerTime: '',
        mealTime: [],
        frequency: '一天次',
        dailyDosage: 'g',
        usageDays: 1,
        specification: '',
        // type=2 时的额外字段
        preparationVolumePerTime: '',
        preparationConcentrationPerTime: '',
        energyDensityPerTime: '',
        usage: '',
        remark: '',
        dailyCalorie: '',
        amount: ''
    }
}

// 创建新的分组
const createNewGroup = () => {
    const groupNo = currentGroupNo.value++
    return {
        groupNo: groupNo,
        products: [createNewGroupedProduct(groupNo)]
    }
}

// 创建新耗材数据
const createNewSupplies = () => {
    return {
        suppliesId: '', // 耗材ID字段
        suppliesName: '',
        specification: '',
        dosagePerTime: '',
        frequency: '',
        dailyDosage: '',
        usageDays: 1,
        quantity: '',
        remark: '',
        amount: ''
    }
}

// 返回操作
const handleBack = () => {
    router.back()
}

// 添加产品
const addProduct = () => {
    if (contentType.value === '3') {
        // type=3时，添加新的分组
        groupedProductList.value.push(createNewGroup())
        // 同时添加一行营养耗材
        suppliesList.value.push(createNewSupplies())
        console.log('新增分组，同步添加耗材行')
    } else {
        // type=2或其他情况，添加普通产品
        productList.value.push(createNewProduct())
        // 同时添加一行营养耗材
        suppliesList.value.push(createNewSupplies())
    }
}

// 添加组内产品
const addProductToGroup = (groupIndex: number) => {
    const group = groupedProductList.value[groupIndex]
    if (group) {
        group.products.push(createNewGroupedProduct(group.groupNo))
    }
}

// 删除组内产品
const removeProductFromGroup = (groupIndex: number, productIndex: number) => {
    const group = groupedProductList.value[groupIndex]
    if (group && group.products.length > 1) {
        group.products.splice(productIndex, 1)
    }
}

// 删除整个分组
const removeGroup = (groupIndex: number) => {
    groupedProductList.value.splice(groupIndex, 1)
    // 同时删除对应的耗材行
    if (suppliesList.value[groupIndex]) {
        suppliesList.value.splice(groupIndex, 1)
        console.log('删除分组，同步删除耗材行')
    }
}



// 产品选择变化处理
const handleProductChange = (productId: string | number, row: any) => {
    if (!productId) {
        // 清空选择时重置相关字段
        row.productName = ''
        row.specification = ''
        row.usage = ''
        row.dailyCalorie = ''
        row.amount = ''
        return
    }

    // 查找选中的产品信息
    const selectedProduct = nutritionOptions.value.find(product => product.id === productId)
    if (selectedProduct) {
        // 自动填充产品相关信息
        row.productName = selectedProduct.productName
        row.specification = selectedProduct.productSpec || ''

        // 根据需求文档：当营养产品配置获得了营养产品，就在对应的产品的用法中填入dictValue（枚举值）
        // 这里使用字典数据中的第一个作为默认用法（可根据业务需求调整匹配逻辑）
        if (usageDictOptions.value.length > 0) {
            // 可以根据产品类型、分类等匹配对应的用法，这里先使用第一个默认用法的枚举值
            row.usage = usageDictOptions.value[0].dictValue
        } else {
            // 如果字典数据还未加载，使用产品的默认用法作为备选
            row.usage = selectedProduct.defaultUsage || ''
        }

        // 根据产品营养信息计算热量等
        if (selectedProduct.calorie) {
            row.dailyCalorie = selectedProduct.calorie.toString()
        }

        // 设置默认销售价格
        if (selectedProduct.configSalePrice) {
            row.amount = selectedProduct.configSalePrice.toString()
        } else if (selectedProduct.packagePrice) {
            row.amount = selectedProduct.packagePrice.toString()
        }

        console.log('选择营养产品:', selectedProduct.productName, '填充用法:', row.usage)

        // 自动为对应的营养耗材行选择第一个营养耗材
        autoSelectFirstConsumable(row)
    }
}

// 分组产品选择变化处理
const handleGroupedProductChange = (productId: string | number, row: any) => {
    if (!productId) {
        // 清空选择时重置相关字段
        row.productName = ''
        row.specification = ''
        row.usage = ''
        row.dailyCalorie = ''
        row.amount = ''
        return
    }

    // 查找选中的产品信息
    const selectedProduct = nutritionOptions.value.find(product => product.id === productId)
    if (selectedProduct) {
        // 自动填充产品相关信息
        row.productName = selectedProduct.productName
        row.specification = selectedProduct.productSpec || ''

        // 使用字典数据填充用法（使用枚举值）
        if (usageDictOptions.value.length > 0) {
            row.usage = usageDictOptions.value[0].dictValue
        } else {
            row.usage = selectedProduct.defaultUsage || ''
        }

        // 根据产品营养信息计算热量等
        if (selectedProduct.calorie) {
            row.dailyCalorie = selectedProduct.calorie.toString()
        }

        // 设置默认销售价格
        if (selectedProduct.configSalePrice) {
            row.amount = selectedProduct.configSalePrice.toString()
        } else if (selectedProduct.packagePrice) {
            row.amount = selectedProduct.packagePrice.toString()
        }

        console.log('选择分组营养产品:', selectedProduct.productName, '组号:', row.groupNo)
    }
}

// 删除产品
const removeProduct = (index: number) => {
    productList.value.splice(index, 1)
    // 同时删除对应的营养耗材行（如果存在）
    if (suppliesList.value[index]) {
        suppliesList.value.splice(index, 1)
    }
}

// 添加耗材
const addSupplies = () => {
    suppliesList.value.push(createNewSupplies())
}

// 删除耗材
const removeSupplies = (index: number) => {
    suppliesList.value.splice(index, 1)
    // 同时删除对应的营养产品行（如果存在）
    if (productList.value[index]) {
        productList.value.splice(index, 1)
    }
}

// 耗材选择变化处理
const handleSuppliesChange = (suppliesId: string | number, row: any) => {
    if (!suppliesId) {
        // 清空选择时重置相关字段
        row.suppliesName = ''
        row.specification = ''
        row.dosagePerTime = ''
        row.frequency = ''
        row.dailyDosage = ''
        row.amount = ''
        row.remark = ''
        return
    }

    // 查找选中的营养耗材信息
    const selectedConsumable = nutritionConsumable.value.find(consumable => consumable.id === suppliesId)
    if (selectedConsumable) {
        // 自动填充营养耗材相关信息
        row.suppliesName = selectedConsumable.consumable
        row.specification = selectedConsumable.specification || ''
        row.dosagePerTime = selectedConsumable.dosePerTime || ''
        row.frequency = selectedConsumable.frequency || ''
        row.dailyDosage = selectedConsumable.dosePerDay || ''
        row.usageDays = selectedConsumable.usageDays || 1
        row.quantity = selectedConsumable.quantity || ''
        row.remark = selectedConsumable.prescriptionRemark || ''
        row.amount = selectedConsumable.amount ? selectedConsumable.amount.toString() : ''

        console.log('选择营养耗材:', selectedConsumable.consumable)
    }
}

// 自动选择第一个营养耗材
const autoSelectFirstConsumable = (productRow: any) => {
    // 找到当前营养产品在列表中的索引
    const productIndex = productList.value.findIndex(item => item === productRow)

    // 如果找到对应的营养产品，且有对应的营养耗材行
    if (productIndex !== -1 && suppliesList.value[productIndex]) {
        const suppliesRow = suppliesList.value[productIndex]

        // 如果营养耗材行还没有选择耗材，且有可用的营养耗材
        if (!suppliesRow.suppliesId && nutritionConsumable.value.length > 0) {
            const firstConsumable = nutritionConsumable.value[0]

            // 自动选择第一个营养耗材
            suppliesRow.suppliesId = firstConsumable.id

            // 自动填充营养耗材信息
            handleSuppliesChange(firstConsumable.id, suppliesRow)

            console.log('自动选择第一个营养耗材:', firstConsumable.consumable)
        }
    }
}

// 增加使用天数
const increaseUsageDays = (row: any) => {
    if (contentType.value === '3') {
        // 分组模式：直接操作组数据
        row.usageDays = (row.usageDays || 0) + 1
    } else {
        // 普通模式
        row.usageDays = (row.usageDays || 0) + 1
    }
}

// 减少使用天数
const decreaseUsageDays = (row: any) => {
    if (contentType.value === '3') {
        // 分组模式：直接操作组数据
        if (row.usageDays > 1) {
            row.usageDays = row.usageDays - 1
        }
    } else {
        // 普通模式
        if (row.usageDays > 1) {
            row.usageDays = row.usageDays - 1
        }
    }
}

// 增加耗材使用天数
const increaseSuppliesUsageDays = (row: any) => {
    row.usageDays = (row.usageDays || 0) + 1
}

// 减少耗材使用天数
const decreaseSuppliesUsageDays = (row: any) => {
    if (row.usageDays > 1) {
        row.usageDays = row.usageDays - 1
    }
}

// 批量添加产品对话框相关
const batchDialogVisible = ref(false)
const selectedProducts = ref<(string | number)[]>([])
const searchKeyword = ref('')

// 过滤营养产品选项
const filteredNutritionOptions = computed(() => {
    if (!searchKeyword.value) {
        return nutritionOptions.value
    }

    const keyword = searchKeyword.value.toLowerCase()
    return nutritionOptions.value.filter(product =>
        product.productName?.toLowerCase().includes(keyword) ||
        product.brand?.toLowerCase().includes(keyword) ||
        product.productSpec?.toLowerCase().includes(keyword) ||
        product.manufacturer?.toLowerCase().includes(keyword)
    )
})

// 批量添加产品
const batchAddProducts = () => {
    if (nutritionOptions.value.length === 0) {
        ElMessage.warning('暂无可选择的营养产品，请刷新页面重试')
        return
    }
    selectedProducts.value = []
    batchDialogVisible.value = true
}

// 确认批量添加
const confirmBatchAdd = () => {
    if (selectedProducts.value.length === 0) {
        ElMessage.warning('请选择要添加的营养产品')
        return
    }

    selectedProducts.value.forEach(productId => {
        const product = createNewProduct()
        product.productId = productId as string

        // 自动填充产品信息
        const selectedProduct = nutritionOptions.value.find(p => p.id === productId)
        if (selectedProduct) {
            product.productName = selectedProduct.productName
            product.specification = selectedProduct.productSpec || ''

            // 使用字典数据填充用法（使用枚举值）
            if (usageDictOptions.value.length > 0) {
                product.usage = usageDictOptions.value[0].dictValue
            } else {
                product.usage = selectedProduct.defaultUsage || ''
            }

            if (selectedProduct.calorie) {
                product.dailyCalorie = selectedProduct.calorie.toString()
            }

            if (selectedProduct.configSalePrice) {
                product.amount = selectedProduct.configSalePrice.toString()
            } else if (selectedProduct.packagePrice) {
                product.amount = selectedProduct.packagePrice.toString()
            }
        }

        productList.value.push(product)

        // 同时添加一行营养耗材
        const supplies = createNewSupplies()
        suppliesList.value.push(supplies)

        // 自动选择第一个营养耗材
        if (nutritionConsumable.value.length > 0) {
            const firstConsumable = nutritionConsumable.value[0]
            supplies.suppliesId = firstConsumable.id
            handleSuppliesChange(firstConsumable.id, supplies)
        }
    })

    batchDialogVisible.value = false
    ElMessage.success(`成功添加 ${selectedProducts.value.length} 个营养产品`)
}

// 删除选中产品
const deleteSelected = () => {
    ElMessage.info('删除功能待实现')
}

// 构建营养产品内容JSON字符串
const buildProductContent = () => {
    if (contentType.value === '3') {
        // type=3时，按组号封装产品数据
        return groupedProductList.value.map(group => ({
            groupId: group.groupNo.toString(),
            content: group.products.map(product => ({
                id: product.productId || null,
                productName: product.productName,
                quantity: product.quantity,
                dosagePerTime: product.dosagePerTime,
                mealTime: product.mealTime,
                frequency: product.frequency,
                dailyDosage: product.dailyDosage,
                usageDays: product.usageDays,
                specification: product.specification,
                // type=2 时的额外字段
                preparationVolumePerTime: product.preparationVolumePerTime,
                preparationConcentrationPerTime: product.preparationConcentrationPerTime,
                energyDensityPerTime: product.energyDensityPerTime,
                usage: product.usage,
                remark: product.remark,
                dailyCalorie: product.dailyCalorie,
                amount: product.amount
            }))
        }))
    } else {
        // type=2或其他情况，构建普通产品数据
        return productList.value.map(product => ({
            id: product.productId || null,
            productName: product.productName,
            quantity: product.quantity,
            dosagePerTime: product.dosagePerTime,
            mealTime: product.mealTime,
            frequency: product.frequency,
            dailyDosage: product.dailyDosage,
            usageDays: product.usageDays,
            specification: product.specification,
            // type=2 时的额外字段
            preparationVolumePerTime: product.preparationVolumePerTime,
            preparationConcentrationPerTime: product.preparationConcentrationPerTime,
            energyDensityPerTime: product.energyDensityPerTime,
            usage: product.usage,
            remark: product.remark,
            dailyCalorie: product.dailyCalorie,
            amount: product.amount
        }))
    }
}

// 构建耗材内容JSON字符串
const buildSuppliesContent = () => {
    return suppliesList.value.map(supplies => ({
        id: supplies.suppliesId || null,
        consumable: supplies.suppliesName,
        specification: supplies.specification,
        dosePerTime: supplies.dosagePerTime,
        frequency: supplies.frequency,
        dosePerDay: supplies.dailyDosage,
        usageDays: supplies.usageDays,
        quantity: supplies.quantity,
        prescriptionRemark: supplies.remark,
        amount: supplies.amount
    }))
}

// 构建完整内容JSON字符串
// 最终格式：
// 普通模式 (type !== '3'):
// {
//   product: [
//     { id: 1, productName: "营养产品1", quantity: "10", ... },
//     { id: 2, productName: "营养产品2", quantity: "20", ... }
//   ],
//   consumable: [
//     { id: 1, consumable: "营养耗材1", specification: "规格1", ... },
//     { id: 2, consumable: "营养耗材2", specification: "规格2", ... }
//   ]
// }
//
// 分组模式 (type === '3'):
// {
//   product: [
//     {
//       groupId: "1",
//       content: [
//         { id: 1, productName: "营养产品1", quantity: "10", ... },
//         { id: 2, productName: "营养产品2", quantity: "20", ... }
//       ]
//     },
//     {
//       groupId: "2", 
//       content: [
//         { id: 3, productName: "营养产品3", quantity: "30", ... }
//       ]
//     }
//   ],
//   consumable: [
//     { id: 1, consumable: "营养耗材1", specification: "规格1", ... },
//     { id: 2, consumable: "营养耗材2", specification: "规格2", ... }
//   ]
// }
const buildFullContent = () => {
    const productContent = buildProductContent()
    const consumableContent = buildSuppliesContent()

    console.log('构建完整内容数据:')
    console.log('- contentType:', contentType.value)
    console.log('- product:', productContent)
    console.log('- consumable:', consumableContent)

    return {
        product: productContent,
        consumable: consumableContent
    }
}

// 提交表单
const handleSubmit = async () => {
    // 先验证表单
    const valid = await formRef.value.validate()
    if (!valid) {
        ElMessage.error('请完善必填信息')
        return
    }

    // 显示确认对话框
    try {
        await ElMessageBox.confirm(
            '是否确认提交',
            '提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }
        )
    } catch {
        // 用户取消提交
        return
    }

    // 用户确认提交，发送网络请求
    try {
        submitting.value = true

        // 构建提交数据
        const submitData: EnteralNutritionTemplateForm = {
            templateName: form.templateName,
            templateDescription: form.templateDescription,
            prescriptionType: route.query.type as string, // 从路由参数获取prescriptionType
            prescriptionId: form.prescriptionDept,
            prescriptionDepartmentName: prescriptionDepartments.value.find(dept => dept.deptId === form.prescriptionDept)?.deptName || '',
            content: JSON.stringify(buildFullContent()), // 营养产品和耗材信息转为JSON字符串
            status: '0', // 正常状态
            delFlag: '0', // 存在标志
            type: route.query.type as string | number, // 从路由参数获取type
            templateType: form.templateType // 模板类型：0=个人模板，1=基础公共模板
        }

        // 如果是编辑模式，添加id字段
        if (isEditMode.value) {
            submitData.id = templateId.value
        }

        console.log('提交数据:', submitData)
        console.log('Content JSON结构:', JSON.parse(submitData.content))

        // 根据模式发送不同的请求
        let response
        if (isEditMode.value) {
            response = await updateEnteralNutritionTemplate(submitData)
        } else {
            response = await addEnteralNutritionTemplate(submitData)
        }

        // 处理响应
        if (response.code === 200) {
            ElMessage.success(isEditMode.value ? '修改成功' : '新增成功')
            // 路由返回
            router.back()
        } else {
            ElMessage.error(response.msg || '操作失败')
        }

    } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败，请重试')
    } finally {
        submitting.value = false
    }
}

// 初始化状态锁，防止重复初始化
const isInitializing = ref(false)

// 页面初始化函数
const initializePage = async () => {
    // 防止重复初始化
    if (isInitializing.value) {
        console.log('页面正在初始化中，跳过重复初始化')
        return
    }

    try {
        isInitializing.value = true
        const { type, id, action, templateType, copyId } = route.query
        contentType.value = type;
        console.log('页面初始化 - contentType:', contentType.value)
        console.log('处方类型:', type, '模板ID:', id, '操作类型:', action, '模板类型:', templateType, '复制ID:', copyId)

        // 重置表单数据
        resetFormData()

        // 根据路由参数设置模板类型
        if (templateType !== undefined) {
            form.templateType = Number(templateType)
            console.log('设置模板类型:', form.templateType)
        }

        // 检测 router.query.action
        if (action === 'update' && id) {
            // 编辑模式
            isEditMode.value = true
            templateId.value = id
            console.log('进入编辑模式，模板ID:', id)
        } else if (copyId) {
            // 复制模式
            isEditMode.value = false
            templateId.value = copyId
            console.log('进入复制模式，源模板ID:', copyId)
        } else {
            // 新增模式
            isEditMode.value = false
            templateId.value = ''
            console.log('进入新增模式')
        }

        // 并行获取科室数据、字典数据、营养产品列表、耗材列表和营养耗材数据
        await Promise.all([
            fetchPrescriptionDepartments(),
            fetchUsageDictOptions(),
            fetchNutritionOptions(),
            fetchSuppliesOptions(),
            fetchNutritionConsumable()
        ])

        // 如果是编辑模式或复制模式，获取模板详情
        if (templateId.value) {
            await fetchTemplateDetail(templateId.value)

            // 如果是复制模式，修改模板名称并清除ID
            if (copyId) {
                form.templateName = `${form.templateName}_副本`
                console.log('复制模式：已修改模板名称为', form.templateName)
            }
        }

        console.log('页面初始化完成')
    } catch (error) {
        console.error('页面初始化失败:', error)
        ElMessage.error('页面初始化失败，请刷新重试')
    } finally {
        // 延迟重置锁，避免快速连续的路由变化
        await nextTick()
        setTimeout(() => {
            isInitializing.value = false
        }, 500)
    }
}

// 重置表单数据
const resetFormData = () => {
    // 重置基本表单
    form.templateName = ''
    form.templateDescription = ''
    form.prescriptionDept = ''
    form.templateType = 1  // 默认为基础公共模板

    // 重置编辑模式状态
    isEditMode.value = false
    templateId.value = ''

    // 重置产品列表
    productList.value = []

    // 重置分组产品列表
    groupedProductList.value = []
    currentGroupNo.value = 1

    // 重置耗材列表
    suppliesList.value = []

    // 重置加载状态
    loading.value = false
    dictLoading.value = false
    deptLoading.value = false
    submitting.value = false

    console.log('表单数据已重置')
}

// 监听路由变化
watch(() => route.query, async (newQuery, oldQuery) => {
    // 检查是否是从其他页面跳转回来（路由参数发生变化）
    if (JSON.stringify(newQuery) !== JSON.stringify(oldQuery)) {
        console.log('检测到路由变化，重新初始化页面')
        console.log('旧路由参数:', oldQuery)
        console.log('新路由参数:', newQuery)
        await initializePage()
    }
}, { deep: true })

// 监听路由路径变化（检测页面跳转）
watch(() => route.path, async (newPath, oldPath) => {
    // 如果路径相同但是是重新进入页面，也需要初始化
    if (newPath === oldPath && route.path.includes('addOrEditForm')) {
        console.log('检测到页面重新进入，重新初始化')
        await initializePage()
    }
}, { flush: 'post' })

// 页面挂载时初始化
onMounted(async () => {
    await initializePage()
})
</script>

<style scoped>
.prescription-template-form {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: calc(100vh - 100px);
}

.header-actions {
    margin-bottom: 20px;
}

.back-btn {
    background-color: #e3f2fd;
    border-color: #90caf9;
    color: #1976d2;
}

.form-section {
    margin-bottom: 20px;
}

.section-title {
    font-weight: 600;
    color: #333;
}

.required-label {
    color: #f56c6c;
}

.required-label::before {
    content: "* ";
}

.important-label {
    font-weight: 600;
}

.product-label {
    color: #000000;
}

.quantity-label {
    color: #000000;
}

.supplies-label {
    color: #000000;
}

.dosage-label,
.frequency-label,
.daily-dosage-label,
.usage-days-label {
    color: #000000;
}

.product-table-container,
.supplies-table-container {
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

.product-table,
.supplies-table {
    border-radius: 4px;
    width: 100%;
    table-layout: auto;
}

/* 确保耗材表格能够自适应宽度 */
.supplies-table {
    min-width: 100%;
}

.supplies-table .el-table__body,
.supplies-table .el-table__header {
    width: 100% !important;
}

/* 确保耗材表格所有字体都是黑色 */
.supplies-table,
.supplies-table th,
.supplies-table td,
.supplies-table .el-table__header-wrapper th,
.supplies-table .el-table__body-wrapper td,
.supplies-table .important-label,
.supplies-table .el-input__inner,
.supplies-table .el-select .el-input__inner,
.supplies-table .el-input__wrapper .el-input__inner {
    color: #000000 !important;
}

.supplies-table .el-table__header th {
    color: #000000 !important;
    font-weight: 600;
}

.supplies-table .el-table__body td {
    color: #000000 !important;
}

/* 确保营养产品表格所有字体也都是黑色 */
.product-table,
.product-table th,
.product-table td,
.product-table .el-table__header-wrapper th,
.product-table .el-table__body-wrapper td,
.product-table .important-label,
.product-table .el-input__inner,
.product-table .el-select .el-input__inner,
.product-table .el-input__wrapper .el-input__inner {
    color: #000000 !important;
}

.product-table .el-table__header th {
    color: #000000 !important;
    font-weight: 600;
}

.product-table .el-table__body td {
    color: #000000 !important;
}

/* 确保所有选择器选项文本都是黑色 */
.el-select-dropdown .el-option,
.el-select-dropdown .el-option span {
    color: #000000 !important;
}

.el-select-dropdown .el-option.hover,
.el-select-dropdown .el-option:hover {
    color: #000000 !important;
}

/* 分组营养产品样式 */
.grouped-product-container {
    margin-bottom: 20px;
}

.product-group {
    margin-bottom: 30px;
    border: 1px solid #e6e6e6;
    border-radius: 8px;
    overflow: hidden;
}

.group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background-color: #f8f9fa;
    border-bottom: 1px solid #e6e6e6;
}

.group-title {
    font-size: 16px;
    font-weight: 600;
    color: #000000;
}

.group-actions {
    display: flex;
    gap: 10px;
}

.group-product-table {
    border-radius: 0;
}

.unified-group-table {
    border-radius: 4px;
}

.group-number {
    font-weight: bold;
    color: #409eff;
}

/* 产品组样式 - 参考ConfigureTable.vue */
.product-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.product-row {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 5px;
}

.action-buttons {
    display: flex;
    gap: 1px;
}

.action-buttons .icon-btn {
    padding: 6px;
    height: 32px;
    border: 1px solid #dcdfe6;
}

.action-buttons .icon-btn:hover {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
}

.action-buttons .icon-btn .el-icon {
    font-size: 14px;
}

/* 用量输入框组样式 - 参考ConfigureTable.vue */
.dosage-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
}

.dosage-group .dosage-input {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    margin-bottom: 5px;
}

.dosage-group .dosage-input .unit {
    color: #909399;
    font-size: 14px;
    flex-shrink: 0;
}

.product-select-with-icon {
    display: flex;
    align-items: center;
    gap: 8px;
    position: relative;
}

.product-select-with-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    width: 100%;
}

.product-action-buttons {
    display: flex;
    gap: 2px;
    flex-shrink: 0;
}

.product-action-buttons .icon-btn {
    padding: 4px;
    height: 24px;
    width: 24px;
    border: 1px solid #dcdfe6;
    background-color: #ffffff;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.product-action-buttons .icon-btn:hover:not(:disabled) {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);
}

.product-action-buttons .icon-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.product-action-buttons .icon-btn .el-icon {
    font-size: 12px;
}

.group-icon {
    color: #409eff;
    font-size: 16px;
    flex-shrink: 0;
}

.group-icon:hover {
    color: #66b1ff;
}

.product-table .el-table__header-wrapper th {
    background-color: #f8f9fa;
    border-right: 1px solid #ebeef5;
}

.product-table .el-table__body-wrapper td {
    border-right: 1px solid #ebeef5;
}

.product-table .el-table__fixed-right {
    box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
}

/* 新增产品输入控件样式 */
.quantity-input,
.dosage-input {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 5px;
}

.unit {
    font-size: 12px;
    color: #000000;
    white-space: nowrap;
}

.fixed-text {
    font-size: 14px;
    color: #000000;
    font-weight: 500;
    background-color: #f5f7fa;
    padding: 4px 8px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    display: inline-block;
    min-width: 60px;
    text-align: center;
}

.meal-time-checkboxes {
    display: flex;
    flex-wrap: wrap;
    gap: 2px;
    justify-content: center;
}

.meal-time-checkboxes .el-checkbox {
    margin-right: 8px;
    margin-bottom: 4px;
}

.meal-time-checkboxes .el-checkbox__label {
    font-size: 12px;
}

.usage-days-input {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 2px;
}

.counter-btn {
    width: 24px;
    height: 24px;
    padding: 0;
    min-width: 24px;
    border-radius: 2px;
}

.counter-btn:hover {
    background-color: #ecf5ff;
    border-color: #409eff;
    color: #409eff;
}

/* 表格内输入框样式优化 */
.product-table .el-input__wrapper {
    padding: 4px 8px;
}

.product-table .el-input--small .el-input__wrapper {
    padding: 2px 6px;
}

.product-table .el-select--small .el-input__wrapper {
    padding: 2px 6px;
}

.product-table .el-checkbox {
    margin-right: 6px;
}

.product-table .el-checkbox__label {
    font-size: 11px;
}

.empty-state {
    text-align: center;
    padding: 40px 0;
    border: 1px solid #ebeef5;
    border-top: none;
    background-color: #fafafa;
}

.empty-text {
    color: #000000;
    margin-bottom: 10px;
}

.add-product-link {
    color: #000000;
    cursor: pointer;
    text-decoration: underline;
}

.add-product-link:hover {
    color: #333333;
}



.product-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
}

.supplies-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 20px;
}

.left-actions {
    display: flex;
    gap: 10px;
}

.cost-display {
    font-size: 16px;
    font-weight: 500;
}

.cost-amount {
    color: #f56c6c;
    font-weight: 600;
}

.supplies-cost-amount {
    color: #000000;
    font-weight: 600;
}

.nutrition-tabs {
    margin-top: 20px;
}

.nutrition-analysis {
    padding: 20px 0;
}

.calorie-info {
    margin-bottom: 20px;
    font-size: 16px;
    color: #666;
}

.analysis-content {
    display: flex;
    gap: 40px;
    align-items: flex-start;
}

.nutrition-table {
    flex: 1;
}

.chart-container {
    flex: 1;
    text-align: center;
}

.chart-title {
    margin-bottom: 20px;
    font-weight: 500;
    color: #333;
}

.pie-chart {
    margin-bottom: 20px;
    display: flex;
    justify-content: center;
}

.chart-placeholder {
    position: relative;
}

.chart-legend {
    display: flex;
    justify-content: center;
    gap: 20px;
    flex-wrap: wrap;
}

.legend-item {
    display: flex;
    align-items: center;
    gap: 5px;
    font-size: 14px;
}

.legend-color {
    width: 12px;
    height: 12px;
    border-radius: 2px;
}

.legend-color.protein {
    background-color: #00bcd4;
}

.legend-color.fat {
    background-color: #ffc107;
}

.legend-color.carb {
    background-color: #2196f3;
}

.data-analysis {
    padding: 40px 0;
    text-align: center;
    color: #666;
}

.submit-section {
    text-align: center;
    margin-top: 30px;
    padding: 20px 0;
}

.submit-section .el-button {
    padding: 12px 40px;
    font-size: 16px;
}

/* 批量添加对话框样式 */
.batch-add-content {
    max-height: 500px;
    overflow: hidden;
}

.product-selection {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 10px;
}

.product-checkbox-group {
    width: 100%;
}

.product-item {
    display: block;
    margin-bottom: 15px;
    padding: 10px;
    border: 1px solid #f0f0f0;
    border-radius: 6px;
    transition: all 0.3s ease;
}

.product-item:hover {
    border-color: #409eff;
    background-color: #f5f7fa;
}

.product-item:last-child {
    margin-bottom: 0;
}

.product-info {
    margin-left: 10px;
}

.product-name {
    font-weight: 600;
    color: #333;
    margin-bottom: 5px;
}

.product-details {
    display: flex;
    gap: 15px;
    font-size: 13px;
    color: #666;
}

.product-details span {
    white-space: nowrap;
}

.no-products {
    text-align: center;
    padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .analysis-content {
        flex-direction: column;
        gap: 20px;
    }

    .chart-legend {
        gap: 10px;
    }

    .product-actions {
        flex-direction: column;
        gap: 15px;
        align-items: stretch;
    }

    .product-details {
        flex-direction: column;
        gap: 5px;
    }
}
</style>