<template>
  <div class="package-table">
    <el-table :data="tableData" border>
      <el-table-column type="index" label="组号" width="60" align="center" />
      <el-table-column label="营养产品" min-width="300">
        <template #default="{ row }">
          <div class="product-group">
            <div class="product-row" style="margin-bottom: 5px">
              <el-select v-model="row.nutritionProductId" placeholder="请选择" @change="changeProductSelect">
                <el-option v-for="pn in productNutritionList" :key="pn.id" :label="pn.productName"
                  :value="pn.id + '_' + row.sn"></el-option>
              </el-select>

              <div class="action-buttons">
                <el-button class="icon-btn" @click="addProduct(row)">
                  <el-icon>
                    <Plus />
                  </el-icon>
                </el-button>
                <el-button class="icon-btn" @click="deleteProduct(row, row.sn)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量" width="150" align="center">
        <template #default="{ row }">
          <div class="quantity-group">
            <div class="quantity-input">
              <el-input v-model="row.quantity" placeholder="请输入" class="input-center" @change="changeQuantityInput" />
              <span class="unit">袋</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="用量/次" width="150" 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)" />
              <span class="unit">g</span>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="餐次时间" width="500">
        <template #default="{ row }">
          <div class="time-slots">
            <div class="time-row">
              <div class="time-group">
                <el-checkbox v-model="row.timeSlots[0].checked"
                  @change="changeTimeSelection(row.timeSlots[0].checked, row.sn)" />
                <el-time-select v-model="row.timeSlots[0].time" start="00:00" step="00:30" end="23:30"
                  placeholder="选择时间" :disabled="!row.timeSlots[0].checked" />
              </div>
              <div class="time-group">
                <el-checkbox v-model="row.timeSlots[1].checked"
                  @change="changeTimeSelection(row.timeSlots[1].checked, row.sn)" />
                <el-time-select v-model="row.timeSlots[1].time" start="00:00" step="00:30" end="23:30"
                  placeholder="选择时间" :disabled="!row.timeSlots[1].checked" />
              </div>
              <div class="time-group">
                <el-checkbox v-model="row.timeSlots[2].checked"
                  @change="changeTimeSelection(row.timeSlots[2].checked, row.sn)" />
                <el-time-select v-model="row.timeSlots[2].time" start="00:00" step="00:30" end="23:30"
                  placeholder="选择时间" :disabled="!row.timeSlots[2].checked" />
              </div>
            </div>
            <div class="time-row">
              <div class="time-group">
                <el-checkbox v-model="row.timeSlots[3].checked"
                  @change="changeTimeSelection(row.timeSlots[3].checked, row.sn)" />
                <el-time-select v-model="row.timeSlots[3].time" start="00:00" step="00:30" end="23:30"
                  placeholder="选择时间" :disabled="!row.timeSlots[3].checked" />
              </div>
              <div class="time-group">
                <el-checkbox v-model="row.timeSlots[4].checked"
                  @change="changeTimeSelection(row.timeSlots[4].checked, row.sn)" />
                <el-time-select v-model="row.timeSlots[4].time" start="00:00" step="00:30" end="23:30"
                  placeholder="选择时间" :disabled="!row.timeSlots[4].checked" />
              </div>
              <div class="time-group">
                <el-checkbox v-model="row.timeSlots[5].checked"
                  @change="changeTimeSelection(row.timeSlots[5].checked, row.sn)" />
                <el-time-select v-model="row.timeSlots[5].time" start="00:00" step="00:30" end="23:30"
                  placeholder="选择时间" :disabled="!row.timeSlots[5].checked" />
              </div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="频次" width="120" align="center">
        <template #default="{ row }">
          <span>一天{{ row.frequency }}次</span>
        </template>
      </el-table-column>
      <el-table-column label="首日" width="150" align="center">
        <template #default="{ row }">
          <el-input v-model="row.firstDay" @input="firstDayInput(row.firstDay, row.sn)">
            <template #append>次</template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="用量/日" width="100" align="center">
        <template #default="{ row }">
          <div class="daily-dosage">
            <span>{{ row.dosePerDay }}</span>
            <span class="unit">{{ row.productSpecUnit }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="使用天数" width="200" align="center">
        <template #default="{ row }">
          <div class="daily-size">
            <el-input-number v-model="row.usageDays" :min="1" @change="changeUsageDays(row.usageDays, row.sn)" />
          </div>
        </template>
      </el-table-column>

      <el-table-column label="规格" width="100" align="center">
        <template #default="{ row }">
          <div class="daily-dosage">
            <span>{{ row.specification }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="用法" width="150" align="center">
        <template #default="{ row }">
          <el-select v-model="row.usage" placeholder="请选择" @change="changeUsage(row.usage, row.sn)">
            <el-option v-for="dict in default_usage" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </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="changePrescriptionRemark(row.usage, row.sn)" />
        </template>
      </el-table-column>

      <el-table-column label="每日热量" width="100" align="center">
        <template #default="{ row }">
          <div class="daily-dosage">
            <span>{{ row.dailyCalories }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="金额" width="100" align="center">
        <template #default="{ row }">
          <div class="daily-dosage">
            <span>{{ row.amount }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="160" align="center" fixed="right">
        <template #default="{ $index }">
          <div class="operation-cell">
            <!-- <el-button type="primary" link @click="copyRow($index)">复制餐次</el-button> -->
            <el-button type="danger" link @click="deleteRow($index)">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- 添加营养产品按钮 -->
    <div class="add-product">
      <el-button type="primary" class="add-btn" @click="addRow">
        <el-icon>
          <CirclePlus />
        </el-icon>
        添加营养产品
      </el-button>
    </div>
    <!-- 底部按钮和总计 -->
    <div class="table-footer">
      <div class="left-buttons">
        <el-button type="primary" plain>存为个人模板</el-button>
        <el-button type="primary" plain @click="openBatchAddDialog">批量添加营养品</el-button>
        <el-button type="primary" plain @click="openPreTemplate()">处方模板</el-button>
      </div>
      <div class="right-summary">
        <div class="summary-list">
          <div class="summary-item">
            <span class="label">处方费用：</span>
            <span class="value">￥{{ nutritionalFee }}</span>
          </div>
          <div class="summary-item total">
            <span class="label">总计：</span>
            <span class="value">￥{{ totalFee }}</span>
          </div>
        </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>

  <!-- 批量添加营养产品对话框 -->
  <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>
</template>

<script setup lang="ts">
import { ref, onMounted, getCurrentInstance, toRefs, watch, computed } from 'vue';
import { Plus, Delete, CirclePlus } from '@element-plus/icons-vue';
import { listEnteralNutrition, getEnteralNutrition, delEnteralNutrition, addEnteralNutrition, updateEnteralNutrition } from '@/api/patients/nutrition';
import { EnteralNutritionVO, EnteralNutritionQuery, EnteralNutritionForm } from '@/api/patients/nutrition/types';
import { listNutrition, listAllNutrition } from '@/api/warehouse/productNutrition/index';
import { NutritionVO, NutritionQuery, NutritionForm } from '@/api/warehouse/productNutrition/types';
import { listAllEnteralNutritionTemplate } from '@/api/parameter/basicPublicTemplate/enteralNutritionTemplate';
import { EnteralNutritionTemplateVO } from '@/api/parameter/basicPublicTemplate/enteralNutritionTemplate/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { default_usage } = toRefs<any>(proxy?.useDict('default_usage'));

let productNutritionList = ref<NutritionVO[]>([]);
let tableId = ref<number>(0);

let nutritionalFee = ref(0.0);
let totalFee = ref(0.0);

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

// 搜索值
const searchValue = ref('');

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

// 已选数量
const selectedCount = ref(0);

// 树形数据相关
const treeData = ref([]);
const selectedNode = ref(null);
const selectedTemplateData = ref(null);

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

// 模板表格数据
const templateTableData = ref([]);

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

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

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

      if (content.product && Array.isArray(content.product)) {
        templateTableData.value = content.product.map((item, index) => ({
          productName: item.productName || `产品${index + 1}`,
          dosePerTime: item.dosePerTime || '1.0000',
          unit: item.productSpecUnit || '份'
        }));
      } else {
        templateTableData.value = [];
      }

      selectedCount.value = templateTableData.value.length;
    } catch (error) {
      console.error('PackageTable解析模板内容失败:', error);
      templateTableData.value = [];
      selectedCount.value = 0;
    }
  } else {
    // 点击的是分类节点，不做处理
    console.log('PackageTable点击分类节点，不做处理');
  }
};

interface TimeSlot {
  checked: boolean;
  time: string;
}

interface TableRow extends EnteralNutritionForm {
  products: EnteralNutritionForm[];
  timeSlots: TimeSlot[];
  sn: number;
  tableId: number;
}

// 创建默认行数据
const createDefaultRow = (): TableRow => ({
  products: [{ specification: '', dosePerDay: '' }],
  timeSlots: [
    { checked: true, time: '08:00' },
    { checked: false, time: '08:30' },
    { checked: true, time: '12:00' },
    { checked: false, time: '12:30' },
    { checked: true, time: '18:00' },
    { checked: false, time: '18:30' }
  ],
  usageDays: 1,
  frequency: 3,
  firstDay: 2,
  sn: 0,
  tableId: tableId.value++
});

// 表格数据，初始为空
const tableData = ref<TableRow[]>([]);
const emit = defineEmits(['change', 'templateSelected']);

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

// 模板相关变量
let nutritionAll = ref<EnteralNutritionTemplateVO[]>([]);

// 监听modelValue变化
watch(
  () => prop.modelValue,
  (val: string) => {
    console.log('PackageTable watch触发，接收到modelValue:', val);

    if (!val || val.trim().length == 0) {
      console.log('PackageTable modelValue为空，跳过处理');
      return;
    }

    try {
      let arr = JSON.parse(val);
      console.log('PackageTable解析数据成功:', arr);

      if (Array.isArray(arr)) {
        if (arr.length == 0) {
          console.log('PackageTable数组为空，保持空状态');
          tableData.value = [];
        } else {
          console.log('PackageTable接收到数据:', arr);

          const processedData = arr.map((item, index) => ({
            ...item,
            sn: index,
            tableId: item.tableId || (Date.now() + index)
          }));

          tableData.value = processedData;
          console.log('PackageTable设置表格数据完成:', tableData.value);
        }
      }
    } catch (error) {
      console.error('PackageTable解析数据失败:', error, '原始数据:', val);
    }
  },
  { deep: true, immediate: true }
);

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

// 获取肠内营养模板数据
const getNutritionTemplates = async () => {
  try {
    const res = await listAllEnteralNutritionTemplate();
    nutritionAll.value = res.rows || [];
    console.log('PackageTable获取到的肠内营养模板数据:', nutritionAll.value);
    updateTemplateData();
  } catch (error) {
    console.error('PackageTable获取肠内营养模板数据失败:', error);
    nutritionAll.value = [];
    updateTemplateData();
  }
};

// 根据处方类型更新模板数据
const updateTemplateData = () => {
  const { typeEnum } = getPrescriptionTypeEnum(prop.prescriptionType);
  console.log('PackageTable当前处方类型:', prop.prescriptionType, '过滤prescriptionType值:', typeEnum.toString());

  // 过滤对应类型的模板
  const filteredTemplates = nutritionAll.value.filter(item => {
    const itemPrescriptionType = item.prescriptionType?.toString();
    const targetPrescriptionType = typeEnum.toString();
    console.log('PackageTable模板:', item.templateName, 'prescriptionType:', itemPrescriptionType, '匹配目标:', targetPrescriptionType);
    return itemPrescriptionType === targetPrescriptionType;
  });

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

  console.log('PackageTable过滤后基础公共模板数量:', basicPublicTemplates.length);
  console.log('PackageTable过滤后个人模板数量:', personalTemplates.length);

  // 生成树形数据结构
  generateTreeData();
};

// 生成树形数据
const generateTreeData = () => {
  const { typeEnum } = getPrescriptionTypeEnum(prop.prescriptionType);
  console.log('PackageTable生成树形数据，当前处方类型:', prop.prescriptionType, '过滤prescriptionType值:', typeEnum.toString());

  // 过滤对应类型的模板
  const filteredTemplates = nutritionAll.value.filter(item => {
    const itemPrescriptionType = item.prescriptionType?.toString();
    const targetPrescriptionType = typeEnum.toString();
    console.log('PackageTable模板:', item.templateName, 'prescriptionType:', itemPrescriptionType, '匹配目标:', targetPrescriptionType);
    return itemPrescriptionType === targetPrescriptionType;
  });

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

  console.log('PackageTable过滤后基础公共模板数量:', basicPublicTemplates.length);
  console.log('PackageTable过滤后个人模板数量:', personalTemplates.length);

  // 构建树形数据结构
  treeData.value = [
    {
      id: '1',
      label: '基础公共模板',
      children: basicPublicTemplates.map(template => ({
        id: `basic_${template.id}`,
        label: template.templateName,
        templateData: template
      }))
    },
    {
      id: '2',
      label: '个人模板',
      children: personalTemplates.map(template => ({
        id: `personal_${template.id}`,
        label: template.templateName,
        templateData: template
      }))
    }
  ];

  console.log('PackageTable生成的树形数据:', treeData.value);
};

// 添加产品输入框
const addProduct = (row: TableRow) => {
  addRow();
};

// 删除产品输入框
const deleteProduct = (row: TableRow, index: number) => {
  if (row.products.length <= 1) {
    // 如果只剩一个输入框，删除整行
    const rowIndex = tableData.value.findIndex((item) => item === row);
    if (rowIndex !== -1) {
      tableData.value.splice(rowIndex, 1);
    }
    totalFee.value = 0.0;
    nutritionalFee.value = 0.0;
  } else {
    // 否则只删除当前输入框
    row.products.splice(index, 1);
  }
};

// 删除行
const deleteRow = (index: number) => {
  tableData.value.splice(index, 1);
  tableData.value.forEach((item, index) => {
    item.sn = index;
  });

  if (tableData.value.length == 0) {
    totalFee.value = 0.0;
    nutritionalFee.value = 0.0;
  }

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

// 添加行
const addRow = () => {
  let row: TableRow = createDefaultRow();
  row.sn = tableData.value.length;
  tableData.value.push(row);
  emit('change', JSON.stringify(tableData.value));
};

const getProductNutritionList = async () => {
  const res = await listAllNutrition();
  productNutritionList.value = res.rows;
};

const changeQuantityInput = async () => {
  emit('change', JSON.stringify(tableData.value));
};

const dosePerTimeInput = (value: string, sn: number) => {
  let row = tableData.value[sn];

  if (!row.dosePerTime || row.dosePerTime.trim().length == 0) {
    row.dailyCalories = null;
    row.amount = null;
    return;
  }

  totalFee.value = 0.0;
  nutritionalFee.value = 0.0;

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

    let val = (item.calorie * row.frequency * Number(row.dosePerTime)) / 100.0;
    row.dailyCalories = val.toFixed(4);

    let firstDay = Number(row.firstDay.toString());
    val = (row.frequency * (row.usageDays - 1) + firstDay) * item.configSalePrice * Number(row.dosePerTime);
    row.amount = Math.round(val * 100) / 100;
    totalFee.value += row.amount;
    nutritionalFee.value += row.amount;

    val = row.frequency * Number(row.dosePerTime);
    row.dosePerDay = val.toFixed(4);
    break;
  }

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

const changeProductSelect = async (id: string) => {
  let arr = id.split('_');
  for (let item of productNutritionList.value) {
    if (item.id.toString() != arr[0]) {
      continue;
    }

    let row = tableData.value[Number(arr[1])];
    // 设置产品基本信息
    row.productName = item.productName;
    row.productCode = item.productCode;
    row.specification = item.productSpec;
    // 设置营养成分信息
    row.protein = item.protein || 0;
    row.fat = item.fat || 0;
    row.carbohydrate = item.carbohydrate || 0;
    row.calorie = item.calorie || 0;
    row.dosePerTime = null;
    row.dailyCalories = null;
    row.amount = null;
    row.productSpecUnit = item.productSpecUnit;
    row.usage = item.defaultUsage;
    row.dosePerDay = '0';
    row.firstDay = Math.ceil(row.frequency / 2.0);
    break;
  }

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

const changeUsageDays = (value: string, sn: string) => {
  changeTimeSelection(null, sn);
};

const changeUsage = (value: string, sn: string) => {
  changeTimeSelection(null, sn);
};

const changePrescriptionRemark = (value: string, sn: string) => {
  changeTimeSelection(null, sn);
};

const firstDayInput = (value: string, sn: string) => {
  changeTimeSelection(null, sn);
};

const changeTimeSelection = (value: string, sn: string) => {
  let row = tableData.value[sn];
  let frequency = 0;
  row.timeSlots.forEach((item) => {
    if (item.checked) {
      frequency++;
    }
  });
  row.frequency = frequency;

  if (value != null) {
    row.firstDay = Math.ceil(row.frequency / 2.0);
  }

  if (!row.dosePerTime || row.dosePerTime.trim().length == 0) {
    return;
  }

  totalFee.value = 0.0;
  nutritionalFee.value = 0.0;
  let arr = row.nutritionProductId.split('_');

  for (let item of productNutritionList.value) {
    if (item.id.toString() != arr[0]) {
      continue;
    }

    let val = (item.calorie * row.frequency * Number(row.dosePerTime)) / 100.0;
    row.dailyCalories = val.toFixed(4);

    let firstDay = Number(row.firstDay.toString());
    val = (row.frequency * (row.usageDays - 1) + firstDay) * item.configSalePrice * Number(row.dosePerTime);

    row.amount = Math.round(val * 100) / 100;
    totalFee.value += row.amount;
    nutritionalFee.value += row.amount;

    val = row.frequency * Number(row.dosePerTime);
    row.dosePerDay = val.toFixed(4);
    break;
  }

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

// 预包装的处方模板
const openPreTemplate = async () => {
  // 清空之前的选择状态
  searchValue.value = '';
  selectedNode.value = null;
  selectedCount.value = 0;
  templateTableData.value = [];
  selectedTemplateData.value = null;

  dialogVisible.value = true;

  // 确保模板数据已加载
  if (nutritionAll.value.length === 0) {
    await getNutritionTemplates();
  } else {
    generateTreeData();
  }
};

// 确认选择模板
const handleConfirm = () => {
  console.log('PackageTable确认选择模板:', selectedTemplateData.value);

  if (selectedTemplateData.value) {
    console.log('PackageTable将传递模板数据:', selectedTemplateData.value);
    // 触发模板选择事件，传递给父组件
    emit('templateSelected', selectedTemplateData.value);
  }

  dialogVisible.value = false;
};

// 批量添加相关方法
const getNutritionOptions = async () => {
  try {
    const res = await listAllNutrition();
    nutritionOptions.value = res.rows || [];
    console.log('PackageTable获取到的营养产品数据:', nutritionOptions.value);
  } catch (error) {
    console.error('PackageTable获取营养产品数据失败:', 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) {
      const newRow = createDefaultRow();
      newRow.productId = selectedProduct.id.toString();
      newRow.productName = selectedProduct.productName;
      newRow.specification = selectedProduct.productSpec || '';

      // 设置默认用法
      if (default_usage.value && default_usage.value.length > 0) {
        newRow.usage = default_usage.value[0].dictValue;
      }

      // 设置价格
      if (selectedProduct.packagePrice) {
        newRow.amount = selectedProduct.packagePrice.toString();
      } else if (selectedProduct.configSalePrice) {
        newRow.amount = selectedProduct.configSalePrice.toString();
      }

      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());
    }
  });
  nutritionalFee.value = totalAmount;
  totalFee.value = nutritionalFee.value;
};

onMounted(async () => {
  getProductNutritionList();
  await getNutritionTemplates();
  await getNutritionOptions(); // 获取营养产品数据
});
</script>

<style lang="scss" scoped>
.package-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;
      }
    }
  }

  .product-group {
    display: flex;
    flex-direction: column;
    gap: 8px;

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

      .el-input {
        flex: 1;
      }

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

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

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

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

  .quantity-group,
  .dosage-group {
    display: flex;
    flex-direction: column;
    gap: 8px;

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

      .input-center {
        width: 80px;

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

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

  .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;
          }
        }
      }
    }
  }

  .operation-cell {
    display: flex;
    justify-content: center;
    gap: 12px;
  }

  .add-product {
    display: flex;
    justify-content: center;
    margin-top: 16px;
    padding: 12px 0;
    background-color: #f5f7fa;
    border: 1px solid var(--el-table-border-color);
    border-top: none;

    .add-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      height: 32px;
      padding: 0 16px;
      font-size: 14px;
      background-color: var(--el-color-primary-light-8);
      color: var(--el-color-primary);
      border: none;

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

      .el-icon {
        font-size: 16px;
      }
    }
  }

  .table-footer {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-top: 16px;
    padding: 16px;
    border: 1px solid var(--el-table-border-color);
    border-top: 1px solid var(--el-table-border-color);

    .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;
  }

  :deep(.el-dialog__footer) {
    padding: 16px 20px;
    border-top: 1px solid #ebeef5;
  }
}

.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>
