<template>
  <div class="material-table">
    <el-table :data="tableData" border :max-height="600">
      <el-table-column type="index" label="组号" width="60" align="center" />
      <el-table-column label="耗材" min-width="300">
        <template #default="{ row }">
          <div class="material-group">
            <div class="material-row" style="margin-bottom: 10px">
              <el-select v-model="row.consumableId" placeholder="请选择" @change="changeConsumableSelect">
                <el-option v-for="pn in suppliesList" :key="pn.id" :label="pn.suppliesName"
                  :value="pn.id + '_' + row.sn"></el-option>
              </el-select>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="规格" width="100" align="center">
        <template #default="{ row }">
          <div class="spec-group">
            <span>{{ row.specification }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用量/次" width="200" align="center">
        <template #default="{ row }">
          <div class="dosage-group">
            <div class="dosage-input">
              <el-input v-model="row.dosePerTime" placeholder="请输入" class="input-center"
                @input="dosePerTimeInput(row.dosePerTime, row.sn)">
                <template #append>袋</template>
              </el-input>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="频次" width="100" align="center">
        <template #default="{ row }">
          <span>一天{{ row.frequency }}次</span>
        </template>
      </el-table-column>
      <el-table-column label="用量/日" width="100" align="center">
        <template #default="{ row }">
          <span>{{ row.dosePerDay }}</span>
          <span class="unit">袋</span>
        </template>
      </el-table-column>
      <el-table-column label="使用天数" width="100" align="center">
        <template #default="{ row }">
          <span>{{ row.usageDays }}天</span>
        </template>
      </el-table-column>
      <el-table-column label="首日" width="80" align="center">
        <template #default="{ row }">
          <span>{{ row.firstDay }}次</span>
        </template>
      </el-table-column>

      <el-table-column label="数量" width="80" align="center">
        <template #default="{ row }">
          <span>{{ row.quantity }}袋</span>
        </template>
      </el-table-column>

      <el-table-column label="处方备注" width="200" align="center">
        <template #default="{ row }">
          <el-input v-model="row.prescriptionRemark" :maxlength="100" :show-word-limit="true"
            @change="prescriptionRemark" />
        </template>
      </el-table-column>

      <el-table-column label="金额" width="80" align="center">
        <template #default="{ row }">
          <span>{{ row.amount }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-footer">
      <div class="left-buttons">
        <el-button type="primary" plain @click="saveAsPersonalTemplate">登为个人模板</el-button>
        <el-button type="primary" plain @click="openTemplate">处方模板</el-button>
      </div>
      <div class="right-summary">
        <div class="summary-list">
          <div class="summary-item">
            <span class="label">处方费用：</span>
            <span class="value">￥{{ nutritionalFee + otherlFee }}</span>
          </div>
          <div class="summary-item">
            <span class="label">营养配置费：</span>
            <span class="value">￥{{ prescriptionFee }}</span>
          </div>
          <div class="summary-item total">
            <span class="label">总计：</span>
            <span class="value">￥{{ totalFee + otherlFee }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 处方模板弹窗 -->
    <el-dialog v-model="dialogVisible" title="选择处方模板" width="60%" :close-on-click-modal="false" class="template-dialog">
      <!-- 提示信息 -->
      <div class="tip-box">如部分模版未显示请检查预包装库位产品库存,无库存则含该产品的协定方模板将不再显示</div>

      <div class="search-box">
        <el-input v-model="searchValue" placeholder="请输入名称" class="search-input">
          <template #append>
            <el-button type="primary">查询</el-button>
          </template>
        </el-input>
      </div>

      <div class="dialog-content">
        <!-- 左侧树形控件 -->
        <div class="left-tree">
          <el-tree ref="treeRef" :data="treeData" :props="defaultProps" node-key="id" :default-expanded-keys="['1']"
            @node-click="handleNodeClick" />
        </div>

        <!-- 右侧表格 -->
        <div class="right-table">
          <div class="table-wrapper">
            <table class="custom-table">
              <thead>
                <tr>
                  <th width="60">组号</th>
                  <th>产品名称</th>
                  <th width="120">用量/次</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in templateTableData" :key="index">
                  <td>{{ index + 1 }}</td>
                  <td>{{ item.productName }}</td>
                  <td>{{ item.dosePerTime }}{{ item.unit }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="selected-count">已选 ({{ selectedCount }})</div>

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

<script setup lang="ts">
import { ref, defineProps, watch, onMounted, getCurrentInstance, computed } from 'vue';
import { listAll } from '@/api/warehouse/suppliesManage';
import { SuppliesManageVO } from '@/api/warehouse/suppliesManage/types';
import { listAllNutrition } from '@/api/warehouse/productNutrition/index';
import { NutritionVO } from '@/api/warehouse/productNutrition/types';
import {
  listNutritionConsumable,
  getNutritionConsumable,
  delNutritionConsumable,
  addNutritionConsumable,
  updateNutritionConsumable
} from '@/api/patients/nutritionConsumable';
import { NutritionConsumableForm } from '@/api/patients/nutritionConsumable/types';
import { listAllEnteralNutritionTemplate, addEnteralNutritionTemplate } from '@/api/parameter/basicPublicTemplate/enteralNutritionTemplate';
import { EnteralNutritionTemplateVO, EnteralNutritionTemplateForm } from '@/api/parameter/basicPublicTemplate/enteralNutritionTemplate/types';


let prescriptionFee = ref(1.0);
let nutritionalFee = ref(0.0);
let otherlFee = ref(0.0);
let totalFee = ref(1.0);

const emit = defineEmits(['change', 'templateSelected', 'requestFormData']);

const { proxy } = getCurrentInstance() as any;

const prop = defineProps({
  modelValue: {
    type: String,
    default: () => undefined
  },
  prescriptionType: {
    type: String,
    default: '2'
  }
});

// 监听prescriptionType变化，重新生成树形数据
watch(
  () => prop.prescriptionType,
  () => {
    console.log('处方类型发生变化:', prop.prescriptionType);
    generateTreeData();
  }
);

// 监听configData变化，同步生成耗材数据
watch(
  () => prop.modelValue,
  async (val: string) => {
    if (!val || val.trim().length == 0) {
      return;
    }

    try {
      let configureData = JSON.parse(val);
      if (Array.isArray(configureData)) {
        console.log('MaterialTable接收到ConfigureTable数据:', configureData);

        // 根据营养产品数据生成对应的耗材行
        const materialRows: TableRow[] = [];

        configureData.forEach((row, index) => {
          if (row.products && Array.isArray(row.products)) {
            // 为每个产品组创建一行耗材
            const materialRow: TableRow = {
              firstDay: row.firstDay || 1,
              frequency: row.frequency || 3,
              dosePerTime: 1,
              dosePerDay: row.frequency || 3,
              usageDays: row.usageDays || 1,
              quantity: 1,
              sn: index,
              tableId: row.tableId || (Date.now() + index)
            };

            // 处理耗材数据
            if (row.consumableData) {
              // 如果模板中包含耗材数据，优先使用模板数据
              console.log('使用模板中的耗材数据:', row.consumableData);
              materialRow.consumableId = row.consumableData.consumableId;
              materialRow.specification = row.consumableData.specification;
              materialRow.suppliesName = row.consumableData.suppliesName;
              materialRow.dosePerTime = row.consumableData.dosePerTime;
              materialRow.amount = row.consumableData.amount;

              // 重新计算相关数据
              materialRow.dosePerDay = materialRow.frequency * materialRow.dosePerTime;
              materialRow.quantity = ((materialRow.usageDays - 1) * materialRow.frequency + materialRow.firstDay) * materialRow.dosePerTime;
            } else if (suppliesList.value && suppliesList.value.length > 0) {
              // 自动选择第一个可用的耗材
              const firstSupply = suppliesList.value[0];
              materialRow.consumableId = firstSupply.id + '_' + index;
              materialRow.specification = firstSupply.suppliesSpec;
              materialRow.suppliesName = firstSupply.suppliesName;

              // 计算相关数据
              const dosePerTime = materialRow.dosePerTime || 1;
              materialRow.dosePerDay = materialRow.frequency * dosePerTime;
              materialRow.quantity = ((materialRow.usageDays - 1) * materialRow.frequency + materialRow.firstDay) * dosePerTime;
              materialRow.amount = firstSupply.sellPrice * materialRow.quantity;

              console.log('自动选择耗材:', firstSupply.suppliesName, '对应行:', index);
            } else {
              console.log('耗材列表为空，稍后重试...');
              // 如果耗材列表还没加载完成，延迟处理
              setTimeout(() => {
                if (suppliesList.value && suppliesList.value.length > 0 && !materialRow.consumableId) {
                  const firstSupply = suppliesList.value[0];
                  materialRow.consumableId = firstSupply.id + '_' + index;
                  materialRow.specification = firstSupply.suppliesSpec;
                  materialRow.suppliesName = firstSupply.suppliesName;

                  // 计算相关数据
                  const dosePerTime = materialRow.dosePerTime || 1;
                  materialRow.dosePerDay = materialRow.frequency * dosePerTime;
                  materialRow.quantity = ((materialRow.usageDays - 1) * materialRow.frequency + materialRow.firstDay) * dosePerTime;
                  materialRow.amount = firstSupply.sellPrice * materialRow.quantity;

                  console.log('延迟自动选择耗材:', firstSupply.suppliesName, '对应行:', index);
                }
              }, 500);
            }

            materialRows.push(materialRow);
          }
        });

        if (materialRows.length > 0) {
          tableData.value = materialRows;
          console.log('MaterialTable设置耗材数据:', tableData.value);
        } else if (configureData.length === 0) {
          tableData.value = [];
        }
      }
    } catch (error) {
      console.error('MaterialTable解析数据失败:', error);
    }
  },
  { deep: true, immediate: true }
);

interface TableRow extends NutritionConsumableForm {
  sn?: number;
  tableId?: number;
  suppliesName?: string;
  consumableId?: string;
}

// 初始数据为空
const tableData = ref<TableRow[]>([]);

let suppliesList = ref<SuppliesManageVO[]>([]);
let nutritionAll = ref<EnteralNutritionTemplateVO[]>([]);



const getSuppliesList = async () => {
  const res = await listAll();
  suppliesList.value = res.rows;
};

const getNutritionTemplates = async () => {
  try {
    const res = await listAllEnteralNutritionTemplate();
    nutritionAll.value = res.rows || [];
    console.log('获取到的肠内营养模板数据:', nutritionAll.value);
  } catch (error) {
    console.error('获取肠内营养模板数据失败:', error);
    nutritionAll.value = [];
    // 即使API失败，也确保一级菜单显示
    generateTreeData();
  }
};

const changeConsumableSelect = async (id: string) => {
  let arr = id.split('_');
  for (let item of suppliesList.value) {
    let row = tableData.value[Number(arr[1])];
    if (item.id.toString() != arr[0]) {
      otherlFee.value += item.sellPrice * row.quantity;
      continue;
    }

    let dosePerTime = 0;
    if (row.dosePerTime) {
      dosePerTime = row.dosePerTime;
    }

    row.specification = item.suppliesSpec;
    row.dosePerDay = row.frequency * dosePerTime;
    row.quantity = ((row.usageDays - 1) * row.frequency + row.firstDay) * dosePerTime;

    if (row.consumableId) {
      let consumableId = row.consumableId.split('_')[0];
      for (let item of suppliesList.value) {
        if (item.id.toString() != consumableId) {
          continue;
        }

        row.amount = item.sellPrice * row.quantity;
        break;
      }
    }

    break;
  }

  otherlFee.value = 0;
  tableData.value.forEach((row) => {
    if (row.amount) {
      otherlFee.value += row.amount;
    }
  });

  emit('change', JSON.stringify(tableData.value));
};

watch(
  () => prop.modelValue,
  async (val: string) => {
    if (!val || val.trim().length == 0) {
      return;
    }

    let configData = JSON.parse(val);
    let tableDataMap = {};
    tableData.value.forEach((item: any) => {
      tableDataMap[item.tableId] = item;
    });

    const newTableList = ref<TableRow[]>([]);
    prescriptionFee.value = 0;
    totalFee.value = 0;
    otherlFee.value = 0;
    nutritionalFee.value = 0;
    prescriptionFee.value += configData.length;
    totalFee.value += configData.length;

    configData.forEach((item: any) => {
      item.products.forEach((pd) => {
        if (pd.amount) {
          nutritionalFee.value += pd.amount;
          totalFee.value += pd.amount;
        }
      });

      let row: TableRow = {
        frequency: Number(item.frequency),
        usageDays: Number(item.usageDays),
        firstDay: Number(item.firstDay),
        dosePerTime: 1,
        tableId: item.tableId,
        sn: newTableList.value.length
      };

      let tmpData = tableDataMap[item.tableId];
      if (tmpData) {
        row = tmpData;
      }
      let dosePerTime = 0;
      if (row.dosePerTime) {
        dosePerTime = row.dosePerTime;
      }

      row.frequency = Number(item.frequency);
      row.usageDays = Number(item.usageDays);
      row.firstDay = Number(item.firstDay);
      row.dosePerDay = item.frequency * dosePerTime;
      row.quantity = ((row.usageDays - 1) * row.frequency + row.firstDay) * dosePerTime;

      if (row.consumableId) {
        let consumableId = row.consumableId.split('_')[0];
        for (let item of suppliesList.value) {
          if (item.id.toString() != consumableId) {
            continue;
          }

          row.amount = item.sellPrice * row.quantity;
          break;
        }
      }

      if (row.amount) {
        otherlFee.value += row.amount;
      }

      newTableList.value.push(row);
    });

    tableData.value = newTableList.value;
    emit('change', JSON.stringify(tableData.value));
  },
  { deep: true, immediate: true }
);

const dosePerTimeInput = (value: string, sn: number) => {
  let row = tableData.value[sn];
  let dosePerTime = 0;
  if (row.dosePerTime) {
    dosePerTime = row.dosePerTime;
  }
  row.dosePerDay = row.frequency * dosePerTime;
  row.quantity = ((row.usageDays - 1) * row.frequency + row.firstDay) * dosePerTime;
  otherlFee.value = 0;

  if (row.consumableId) {
    let consumableId = row.consumableId.split('_')[0];
    for (let item of suppliesList.value) {
      if (item.id.toString() != consumableId) {
        otherlFee.value += item.sellPrice * row.quantity;
        continue;
      }

      row.amount = item.sellPrice * row.quantity;
      otherlFee.value += row.amount;
      break;
    }
  }

  otherlFee.value = 0;
  tableData.value.forEach((row) => {
    if (row.amount) {
      otherlFee.value += row.amount;
    }
  });

  emit('change', JSON.stringify(tableData.value));
};

const prescriptionRemark = (value: string) => {
  emit('change', JSON.stringify(tableData.value));
};

// 弹窗显示控制
const dialogVisible = ref(false);

// 搜索值
const searchValue = ref('');
// 选中的节点
const selectedNode = ref('');
// 已选数量
const selectedCount = ref(2);
// 当前选中的模板数据
const selectedTemplateData = ref(null);

// 树形控件数据 - 初始化时就显示一级菜单
const treeData = ref([
  {
    id: '1',
    label: '基础公共模板',
    children: []
  },
  {
    id: '2',
    label: '个人模板',
    children: []
  }
]);

// 根据营养模板数据生成树形结构
const generateTreeData = () => {
  // 获取当前处方类型对应的type值
  const { typeEnum } = getPrescriptionTypeEnum(prop.prescriptionType);

  console.log('当前处方类型:', prop.prescriptionType, '过滤prescriptionType值:', typeEnum.toString());

  // 根据当前处方类型过滤模板，只显示对应类型的模板
  // 后端传过来的prescriptionType是枚举值2、3、4（可能是字符串或数字）
  const filteredTemplates = nutritionAll.value.filter(item => {
    const itemPrescriptionType = item.prescriptionType?.toString();
    const targetPrescriptionType = typeEnum.toString();
    console.log('模板:', item.templateName, 'prescriptionType:', itemPrescriptionType, '匹配目标:', targetPrescriptionType);
    return itemPrescriptionType === targetPrescriptionType;
  });

  const basicPublicTemplates = filteredTemplates.filter(item => item.templateType === 1);
  const personalTemplates = filteredTemplates.filter(item => item.templateType === 0);

  const treeStructure = [];

  // 基础公共模板 - 始终显示，即使没有数据
  treeStructure.push({
    id: '1',
    label: '基础公共模板',
    children: basicPublicTemplates.length > 0
      ? basicPublicTemplates.map((template, index) => ({
        id: `1-${index + 1}`,
        label: template.templateName,
        templateId: template.id,
        templateData: template
      }))
      : [] // 没有数据时显示空的children数组
  });

  // 个人模板 - 始终显示，即使没有数据
  treeStructure.push({
    id: '2',
    label: '个人模板',
    children: personalTemplates.length > 0
      ? personalTemplates.map((template, index) => ({
        id: `2-${index + 1}`,
        label: template.templateName,
        templateId: template.id,
        templateData: template
      }))
      : [] // 没有数据时显示空的children数组
  });

  treeData.value = treeStructure;
  console.log('生成的树形数据 (已过滤):', treeData.value);
  console.log('过滤后基础公共模板数量:', basicPublicTemplates.length);
  console.log('过滤后个人模板数量:', personalTemplates.length);
  console.log('总模板数量:', nutritionAll.value.length, '过滤后数量:', filteredTemplates.length);
};

// 树形控件配置
const defaultProps = {
  children: 'children',
  label: 'label'
};

// 模板表格数据
const templateTableData = ref([
  {
    productName: '氨基酸型复配营养粉2',
    dosePerTime: '5.0000',
    unit: 'g'
  },
  {
    productName: '肠内营养全营养复合膜',
    dosePerTime: '1.0000',
    unit: '袋'
  }
]);

// 批量添加相关变量
const nutritionOptions = ref<NutritionVO[]>([]);
const searchKeyword = ref('');
const selectedProducts = ref<string[]>([]);
const batchDialogVisible = ref(false);

// 树形节点点击事件（单选）
const handleNodeClick = (data: any) => {
  console.log('树形节点点击:', data);

  // 只有叶子节点（模板节点）才能选择
  if (data.templateData) {
    selectedNode.value = data;
    selectedTemplateData.value = data.templateData;
    selectedCount.value = 1;
    console.log('选中模板:', data);
    console.log('保存模板数据:', data.templateData);

    // 解析并显示模板内容
    try {
      const contentData = JSON.parse(data.templateData.content);
      console.log('模板内容数据:', contentData);

      // 根据content数据结构生成表格数据
      if (contentData.product && Array.isArray(contentData.product)) {
        templateTableData.value = contentData.product.map(item => ({
          productName: item.productName || item.name || '未知产品',
          dosePerTime: item.dosagePerTime || item.quantity || '0',
          unit: item.unit || 'g'
        }));
      } else if (Array.isArray(contentData)) {
        // 兼容旧的数据结构
        templateTableData.value = contentData.map(item => ({
          productName: item.productName || item.name || '未知产品',
          dosePerTime: item.dosagePerTime || item.quantity || '0',
          unit: item.unit || 'g'
        }));
      }
    } catch (error) {
      console.error('解析模板内容失败:', error);
      templateTableData.value = [];
      selectedTemplateData.value = null;
      selectedCount.value = 0;
    }
  } else {
    // 点击的是分类节点，不做处理
    console.log('点击分类节点，不做处理');
  }
};

// 打开处方模板
const openTemplate = () => {
  // 清空弹框数据
  searchValue.value = '';
  selectedNode.value = '';
  selectedCount.value = 0;
  templateTableData.value = [];
  selectedTemplateData.value = null;

  // 重新生成树形数据
  generateTreeData();

  dialogVisible.value = true;
};

// 确认选择模板
const handleConfirm = () => {
  if (selectedTemplateData.value && selectedCount.value > 0) {
    console.log('确认选择模板，当前选中数量:', selectedCount.value);
    console.log('选中的模板数据:', selectedTemplateData.value);

    // 发出模板选择事件，将完整的模板数据传递给父组件
    emit('templateSelected', selectedTemplateData.value);

    dialogVisible.value = false;
  } else {
    console.log('没有选中任何模板');
    // 可以显示提示信息
  }
};

// 登为个人模板
const saveAsPersonalTemplate = async () => {
  try {
    // 显示确认弹框
    await proxy?.$modal.confirm('是否确认登为个人模板？');

    // 让用户输入模板名称
    const templateName = await proxy?.$modal.prompt('请输入模板名称:', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /\S+/,
      inputErrorMessage: '模板名称不能为空'
    });

    if (!templateName || !templateName.value) {
      proxy?.$modal.msgWarning('模板名称不能为空');
      return;
    }

    // 收集当前表单数据
    const templateData = await collectCurrentFormData();

    // 构建请求参数
    const templateForm: EnteralNutritionTemplateForm = {
      templateName: templateName.value,
      templateDescription: '个人模板',
      prescriptionType: templateData.prescriptionType || '',
      prescriptionId: templateData.prescriptionId || '',
      content: templateData.content || '',
      status: '0', // 正常状态
      type: templateData.type || 2, // 从当前选中的处方类型获取
      templateType: 0 // 0表示个人模板
    };

    console.log('准备保存个人模板:', templateForm);

    // 调用后端API
    const response = await addEnteralNutritionTemplate(templateForm);

    // 根据返回状态显示提示
    if (response.code === 200) {
      proxy?.$modal.msgSuccess('个人模板创建成功');
      // 刷新模板列表
      await getNutritionTemplates();
      generateTreeData();
    } else {
      proxy?.$modal.msgError(response.msg || '创建失败，请重试');
    }
  } catch (error) {
    console.error('保存个人模板失败:', error);
    if (error !== 'cancel') { // 用户取消操作不显示错误
      proxy?.$modal.msgError('创建失败，请重试');
    }
  }
};

// 根据prescriptionType获取对应的枚举值
const getPrescriptionTypeEnum = (prescriptionType: string) => {
  switch (prescriptionType) {
    case '2':
      return { prescriptionTypeEnum: '2', typeEnum: 2 }; // 预包装处方模板
    case '3':
      return { prescriptionTypeEnum: '3', typeEnum: 3 }; // 配置处方模板
    case '4':
      return { prescriptionTypeEnum: '4', typeEnum: 4 }; // 长嘱处方模板
    default:
      return { prescriptionTypeEnum: '3', typeEnum: 3 }; // 默认配置处方模板
  }
};

// 收集当前表单数据
const collectCurrentFormData = async () => {
  try {
    // 收集当前MaterialTable的耗材数据
    const consumableData = tableData.value.map(item => ({
      id: item.consumableId ? item.consumableId.split('_')[0] : '',
      suppliesName: item.suppliesName || '',
      specification: item.specification || '',
      dosePerTime: item.dosePerTime || 0,
      frequency: item.frequency || 0,
      dosePerDay: item.dosePerDay || 0,
      usageDays: item.usageDays || 0,
      quantity: item.quantity || 0,
      amount: item.amount || 0
    }));

    // 从prop.modelValue中获取ConfigureTable的数据
    let productData = [];
    if (prop.modelValue && prop.modelValue.trim().length > 0) {
      try {
        const configData = JSON.parse(prop.modelValue);
        if (Array.isArray(configData)) {
          // 转换ConfigureTable数据为模板格式
          productData = configData.map(row => {
            if (row.products && Array.isArray(row.products)) {
              return row.products.map(product => ({
                id: product.nutritionProductId ? product.nutritionProductId.split('_')[0] : '',
                productName: product.productName || '',
                dosePerTime: product.dosePerTime || '',
                specification: product.specification || '',
                usage: product.usage || '',
                prescriptionRemark: product.prescriptionRemark || '',
                dailyCalories: product.dailyCalories || '',
                amount: product.amount || '',
                dosePerDay: product.dosePerDay || '',
                totalDose: product.totalDose || '',
                productSpecUnit: product.productSpecUnit || 'g'
              }));
            }
            return [];
          }).flat();
        }
      } catch (error) {
        console.error('解析ConfigureTable数据失败:', error);
      }
    }

    // 根据prescriptionType转换为对应的枚举值
    const { prescriptionTypeEnum, typeEnum } = getPrescriptionTypeEnum(prop.prescriptionType);

    console.log('当前处方类型:', prop.prescriptionType, '-> 枚举值:', prescriptionTypeEnum, 'type:', typeEnum);

    return {
      prescriptionType: prescriptionTypeEnum,
      prescriptionId: '',
      content: JSON.stringify({
        product: productData,
        consumable: consumableData
      }),
      type: typeEnum
    };
  } catch (error) {
    console.error('收集表单数据失败:', error);

    // 错误情况下也要根据prescriptionType设置正确的枚举值
    const { prescriptionTypeEnum, typeEnum } = getPrescriptionTypeEnum(prop.prescriptionType);

    return {
      prescriptionType: prescriptionTypeEnum,
      prescriptionId: '',
      content: JSON.stringify({
        product: [],
        consumable: []
      }),
      type: typeEnum
    };
  }
};

// 批量添加相关方法
const getNutritionOptions = async () => {
  try {
    const res = await listAllNutrition();
    nutritionOptions.value = res.rows || [];
    console.log('获取到的营养产品数据:', nutritionOptions.value);
  } catch (error) {
    console.error('获取营养产品数据失败:', error);
    nutritionOptions.value = [];
  }
};

// 过滤营养产品选项
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 openBatchAddDialog = () => {
  if (nutritionOptions.value.length === 0) {
    proxy?.$modal.msgWarning('暂无可选择的营养产品，请刷新页面重试');
    return;
  }
  selectedProducts.value = [];
  batchDialogVisible.value = true;
};

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

  // 为每个选中的产品创建一行耗材
  selectedProducts.value.forEach(productId => {
    const selectedProduct = nutritionOptions.value.find(p => p.id === productId);
    if (selectedProduct && suppliesList.value.length > 0) {
      const newRow: TableRow = {
        firstDay: 1,
        frequency: 3,
        dosePerTime: 1,
        dosePerDay: 3,
        usageDays: 1,
        quantity: 1,
        sn: tableData.value.length,
        tableId: Date.now() + Math.random(),
        // 使用第一个可用的耗材
        consumableId: suppliesList.value[0].id + '_' + Date.now(),
        specification: suppliesList.value[0].suppliesSpec,
        suppliesName: suppliesList.value[0].suppliesName,
        amount: suppliesList.value[0].sellPrice
      };

      tableData.value.push(newRow);
    }
  });

  // 重新计算费用
  recalculateFees();

  // 触发数据变更事件
  emit('change', JSON.stringify(tableData.value));

  batchDialogVisible.value = false;
  proxy?.$modal.msgSuccess(`成功添加 ${selectedProducts.value.length} 个营养产品`);
};

// 重新计算费用
const recalculateFees = () => {
  let totalAmount = 0;
  tableData.value.forEach(row => {
    if (row.amount) {
      totalAmount += parseFloat(row.amount.toString());
    }
  });
  otherlFee.value = totalAmount;
  totalFee.value = prescriptionFee.value + nutritionalFee.value + otherlFee.value;
};

onMounted(async () => {
  getSuppliesList();
  await getNutritionTemplates();
  await getNutritionOptions(); // 获取营养产品数据
  // 获取数据后生成树形结构
  generateTreeData();
});
</script>

<style lang="scss" scoped>
.material-table {
  :deep(.el-table) {

    // 表头样式
    .el-table__header {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
        padding: 8px 0;
        height: 40px;
      }
    }

    // 表格行样式
    .el-table__row {
      td {
        padding: 4px 8px;
      }
    }
  }

  // 耗材输入框组样式
  .material-group {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .material-row {
      display: flex;
      align-items: center;
      gap: 8px;

      .el-input {
        flex: 1;
      }
    }
  }

  // 规格组样式
  .spec-group {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 8px 0;

    span {
      color: #606266;
      font-size: 14px;
    }
  }

  // 用量输入框组样式
  .dosage-group {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .dosage-input {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 4px;

      .input-center {
        width: 100px;

        :deep(.el-input__inner) {
          text-align: center;
        }
      }

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

  // 餐次时间样式
  .time-slots {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .time-row {
      display: flex;
      gap: 8px;

      .time-group {
        display: flex;
        align-items: center;
        gap: 4px;

        :deep(.el-checkbox) {
          margin-right: 0;

          .el-checkbox__label {
            display: none;
          }
        }

        :deep(.el-time-select) {
          .el-input {
            width: 120px;
          }

          .el-input__wrapper {
            padding: 0 8px;
            border-radius: 2px;
            box-shadow: 0 0 0 1px #dcdfe6 inset;

            &:hover:not(.is-disabled) {
              box-shadow: 0 0 0 1px #c0c4cc inset;
            }

            &.is-disabled {
              background-color: #f5f7fa;
              box-shadow: 0 0 0 1px #e4e7ed inset;

              .el-input__inner {
                color: #909399;
                -webkit-text-fill-color: #909399;
              }
            }
          }

          .el-input__inner {
            height: 32px;
            text-align: center;
            font-size: 14px;
            color: #606266;
          }
        }
      }
    }
  }

  // 操作按钮样式
  :deep(.el-button--link) {
    height: 28px;
    padding: 0 8px;
    font-size: 13px;

    &.el-button--primary {
      color: var(--el-color-primary);

      &:hover {
        color: var(--el-color-primary-light-3);
      }
    }

    &.el-button--danger {
      color: var(--el-color-danger);

      &:hover {
        color: var(--el-color-danger-light-3);
      }
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-top: 16px;

    .left-buttons {
      display: flex;
      gap: 12px;

      .el-button {
        height: 32px;
        padding: 0 16px;
        font-size: 14px;
      }
    }

    .right-summary {
      min-width: 200px;

      .summary-list {
        display: flex;
        flex-direction: column;
        align-items: flex-end;
        gap: 4px;

        .summary-item {
          display: flex;
          align-items: center;
          justify-content: flex-end;
          gap: 8px;
          text-align: right;

          .label {
            font-size: 16px;
            color: #606266;
          }

          .value {
            font-size: 20px;
            color: #606266;
            min-width: 80px;
            text-align: right;
          }

          &.total {
            margin-top: 4px;

            .label,
            .value {
              color: #f56c6c;
              font-weight: 500;
            }
          }
        }
      }
    }
  }
}

.template-dialog {
  :deep(.el-dialog__body) {
    padding: 0 20px;
  }

  .tip-box {
    background-color: #e6f7ff;
    padding: 12px 16px;
    color: #606266;
    font-size: 14px;
    margin-bottom: 16px;
  }

  .search-box {
    margin-bottom: 16px;

    .search-input {
      width: 300px;
    }
  }

  .dialog-content {
    display: flex;
    min-height: 350px;
    border: 1px solid #ebeef5;

    .left-tree {
      width: 220px;
      padding: 12px;
      border-right: 1px solid #ebeef5;
      max-height: 350px;
      overflow-y: auto;

      :deep(.el-tree-node__content) {
        height: 32px;
      }

      :deep(.el-tree-node__content:hover) {
        background-color: #f5f7fa;
      }

      :deep(.el-tree-node.is-current > .el-tree-node__content) {
        background-color: #f5f7fa;
      }
    }

    .right-table {
      flex: 1;
      padding: 12px;
      overflow: auto;

      .table-wrapper {
        margin-bottom: 0;
      }
    }
  }

  .selected-count {
    margin: 16px 0;
    color: #409eff;
    font-size: 14px;
  }
}

.custom-table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #ebeef5;

  th,
  td {
    padding: 12px 8px;
    border: 1px solid #ebeef5;
    text-align: center;
    font-size: 14px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  th {
    background-color: #f5f7fa;
    color: #303133;
    font-weight: 600;
  }

  tbody tr:hover {
    background-color: #f5f7fa;
  }
}

/* 批量添加对话框样式 */
.batch-add-content {
  .search-section {
    margin-bottom: 20px;
  }

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

  .product-checkbox-group {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .product-item {
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 12px;
    transition: all 0.3s;

    &:hover {
      border-color: #409eff;
      background-color: #f0f9ff;
    }

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

    .product-name {
      font-weight: 500;
      color: #303133;
      margin-bottom: 4px;
    }

    .product-details {
      font-size: 12px;
      color: #909399;
      display: flex;
      gap: 16px;
    }
  }

  .no-products {
    text-align: center;
    padding: 40px 0;
  }
}
</style>
