<template>
  <el-card class="left-card">
    <!-- 顶部标签页 -->
    <el-tabs v-model="activeTab" class="main-tabs">
      <el-tab-pane label="肠内营养" name="nutrition">
        <div class="content-wrapper">
          <!-- 日期和操作栏 -->
          <div class="operation-bar">
            <!-- 日期选择 -->
            <el-row>
              <el-col :span="8">
                <span class="label">日期时间：</span>
                <el-date-picker v-model="prescriptionDate" :clearable="false" type="date"
                  :disabled-date="disabledBeforeToday" placeholder="请选择" value-format="YYYY-MM-DD" />
              </el-col>
              <el-col :span="4"> </el-col>
              <el-col class="right_btn" :span="12">
                <el-button type="primary" plain @click="submitForm('2')">存为草稿</el-button>
                <el-button type="primary" @click="submitForm('0')" :loading="buttonLoading">提交</el-button>
                <el-button type="danger" @click="deleteFrom">删除</el-button>
                <el-button type="primary" plain>打印知情同意书</el-button>
                <el-button type="success" @click="goHistoryPrescription">历史处方</el-button>
              </el-col>
            </el-row>

            <!-- 添加按钮组 -->
            <div class="add-buttons">
              <el-button :class="['add-btn', { 'is-active': prescriptionType === '3' }]"
                @click="addPrescription">添加配置处方</el-button>
              <el-button :class="['add-btn', { 'is-active': prescriptionType === '2' }]"
                @click="addTemplate">添加预包装处方</el-button>
              <el-button :class="['add-btn', { 'is-active': prescriptionType === '4' }]"
                @click="addLongTerm">添加长期医嘱处方</el-button>
            </div>

            <!-- 开方原因 -->
            <!-- <div class="prescription-reason">
              <span class="reason-label">开方原因：</span>
              <span class="reason-value">1111</span>
            </div> -->
          </div>

          <!-- 处方提示信息 -->
          <!-- <div class="prescription-info">
            <div class="warning-box">
              当前处方中的脂肪、维生素A、维生素D、维生素E、维生素B1、维生素B2、维生素B6、维生素B12、硒(尼克黄)、维生素C、生物素、泛酸元素可能过量
            </div>
          </div> -->

          <!-- 处方表格 -->
          <div class="prescription-tables">
            <template v-if="tableType === '3'">
              <ConfigureTable @change="updateConfigureData" v-model="configData" />
              <MaterialTable v-model="configData" @change="updateMaterialData"
                @templateSelected="handleTemplateSelected" :prescriptionType="prescriptionType" />
            </template>
            <template v-else-if="tableType === '2'">
              <PackageTable @change="updatePackageData" :prescriptionType="prescriptionType"
                @templateSelected="handleTemplateSelected" v-model="packageData" />
            </template>
            <template v-else>
              <NutritionTable @change="updateLongTermData" v-model="longTermData"
                :prescriptionDate="prescriptionDate" />
              <MaterialTable2 v-model="longTermData" @change="updateMaterial2Data"
                :prescriptionType="prescriptionType" />
            </template>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="膳食治疗" name="therapy">
        <!-- 膳食治疗内容 -->
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>

<script setup lang="ts">
import { ref, nextTick, getCurrentInstance, onMounted } from 'vue';
import NutritionTable from './table/NutritionTable.vue';
import MaterialTable from './table/MaterialTable.vue';
import MaterialTable2 from './table/MaterialTable2.vue';
import PackageTable from './table/PackageTable.vue';
import ConfigureTable from './table/ConfigureTable.vue';

import { listEnteralNutrition, getEnteralNutrition, delEnteralNutrition, addEnteralNutrition, updateEnteralNutrition } from '@/api/patients/nutrition';
import { EnteralNutritionVO, EnteralNutritionQuery, EnteralNutritionForm, EnteralNutritionSaveForm } from '@/api/patients/nutrition/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const emit = defineEmits(['gotoTop', 'nutritionProductsChange']);
const buttonLoading = ref(false);
const { patientInfo } = defineProps<{ patientInfo: any }>();

// 顶部tab切换
const activeTab = ref('nutrition');
const configData = ref('');
const packageData = ref('');
const longTermData = ref('');
const materialData = ref('');
const materialData2 = ref('');

// 表格类型
const tableType = ref<'3' | '2' | '4'>('3');

// 日期范围
const prescriptionDate = ref('');

// 处方类型
const prescriptionType = ref<'3' | '2' | '4'>('3');

const updateConfigureData = (val: string) => {
  configData.value = val;
  // 发送营养产品变化事件
  emitNutritionProductsChange();
};

const updateLongTermData = (val: string) => {
  longTermData.value = val;
};

const updatePackageData = (val: string) => {
  console.log('LeftCard updatePackageData 被调用，数据:', val);
  packageData.value = val;
  // 发送营养产品变化事件
  emitNutritionProductsChange();
};

const updateMaterialData = (val: string) => {
  materialData.value = val;
};

const updateMaterial2Data = (val: string) => {
  materialData2.value = val;
};

// 收集并发送营养产品变化事件
const emitNutritionProductsChange = () => {
  const products: Array<{
    name: string,
    productCode: string,
    type: string,
    protein?: number,
    fat?: number,
    carbohydrate?: number,
    calorie?: number,
    dosePerTime?: number,
    quantity?: number
  }> = [];

  try {
    console.log('开始收集营养产品数据...');
    console.log('当前表格类型:', tableType.value);
    console.log('packageData:', packageData.value);
    console.log('configData:', configData.value);

    // 根据当前表格类型收集营养产品数据
    if (tableType.value === '2' && packageData.value) {
      // 预包装处方 - 从PackageTable收集数据
      console.log('处理预包装处方数据...');
      const data = JSON.parse(packageData.value);
      console.log('解析后的预包装数据:', data);

      if (Array.isArray(data)) {
        data.forEach((row, index) => {
          console.log(`检查第${index}行数据:`, row);
          if (row.nutritionProductId && row.productName) {
            const product = {
              name: row.productName || '未知产品',
              productCode: row.productCode || '无编码',
              type: '肠内',
              protein: row.protein || 0,
              fat: row.fat || 0,
              carbohydrate: row.carbohydrate || 0,
              calorie: row.calorie || 0,
              dosePerTime: parseFloat(row.dosePerTime) || 0,
              quantity: parseFloat(row.quantity) || 1
            };
            console.log('添加预包装产品:', product);
            products.push(product);
          } else {
            console.log(`第${index}行跳过: nutritionProductId=${row.nutritionProductId}, productName=${row.productName}`);
          }
        });
      }
    } else if (tableType.value === '3' && configData.value) {
      // 配置处方 - 从ConfigureTable收集数据
      console.log('处理配置处方数据...');
      const data = JSON.parse(configData.value);
      console.log('解析后的配置数据:', data);

      if (Array.isArray(data)) {
        data.forEach((row, rowIndex) => {
          console.log(`检查第${rowIndex}行数据:`, row);
          if (row.products && Array.isArray(row.products)) {
            row.products.forEach((product, productIndex) => {
              console.log(`检查第${rowIndex}行第${productIndex}个产品:`, product);
              if (product.nutritionProductId && product.productName) {
                const productInfo = {
                  name: product.productName || '未知产品',
                  productCode: product.productCode || '无编码',
                  type: '肠内',
                  protein: product.protein || 0,
                  fat: product.fat || 0,
                  carbohydrate: product.carbohydrate || 0,
                  calorie: product.calorie || 0,
                  dosePerTime: parseFloat(product.dosePerTime) || 0,
                  quantity: 1 // 配置处方中单个产品数量为1
                };
                console.log('添加配置产品:', productInfo);
                products.push(productInfo);
              } else {
                console.log(`第${rowIndex}行第${productIndex}个产品跳过: nutritionProductId=${product.nutritionProductId}, productName=${product.productName}`);
              }
            });
          }
        });
      }
    } else {
      console.log('没有匹配的表格类型或数据为空');
    }

    console.log('LeftCard收集到的营养产品:', products);
    emit('nutritionProductsChange', products);
  } catch (error) {
    console.error('收集营养产品数据失败:', error);
    emit('nutritionProductsChange', []);
  }
};

// 处理预包装处方模板数据
const handlePackageTemplateData = (contentData: any) => {
  console.log('处理预包装处方模板数据:', contentData);

  try {
    // 将模板数据转换为PackageTable需要的格式
    let packageTableData = [];

    // 处理营养产品数据
    if (contentData.product && Array.isArray(contentData.product)) {
      contentData.product.forEach((product, index) => {
        const packageRow = {
          // PackageTable使用扁平结构，不是products数组
          nutritionProductId: product.id ? `${product.id}_${index}` : '',
          quantity: product.quantity || 1,
          dosePerTime: product.dosagePerTime || product.dosePerTime || '',
          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' }
          ],
          frequency: 3,
          firstDay: 2,
          usageDays: product.usageDays || 1,
          dosePerDay: product.dosePerDay || '',
          specification: product.specification || '',
          usage: product.usage || '',
          prescriptionRemark: product.remark || product.prescriptionRemark || '',
          dailyCalories: product.dailyCalorie || product.dailyCalories || '',
          amount: product.amount || '',
          totalDose: product.totalDose || '',
          productSpecUnit: product.productSpecUnit || 'g',
          sn: index,
          tableId: Date.now() + index
        };

        packageTableData.push(packageRow);
      });
    }

    console.log('转换后的预包装数据:', packageTableData);

    // 更新packageData - 确保立即触发响应式更新
    packageData.value = JSON.stringify(packageTableData);
    console.log('更新packageData.value:', packageData.value);

    // 使用nextTick确保数据更新完成后再触发成功提示
    nextTick(() => {
      console.log('nextTick后，packageData.value:', packageData.value);
      proxy?.$modal.msgSuccess('预包装处方模板导入成功');
    });
  } catch (error) {
    console.error('处理预包装处方模板数据失败:', error);
    proxy?.$modal.msgError('预包装处方模板导入失败，请重试');
  }
};

// 处理模板选择事件
const handleTemplateSelected = (templateData: any) => {
  console.log('收到模板选择事件:', templateData, '当前处方类型:', prescriptionType.value);

  try {
    if (templateData && templateData.content) {
      const contentData = JSON.parse(templateData.content);
      console.log('解析的模板内容:', contentData);

      // 根据处方类型处理模板数据
      if (prescriptionType.value === '2') {
        // 预包装处方：直接更新packageData
        handlePackageTemplateData(contentData);
        return;
      }

      // 配置处方和长嘱处方：将模板数据转换为ConfigureTable需要的格式
      let configureTableData = [];

      // 处理营养产品数据
      if (contentData.product && Array.isArray(contentData.product)) {
        // 新格式：分组数据
        if (contentData.product.length > 0 && contentData.product[0].groupId) {
          // 分组格式数据
          contentData.product.forEach(group => {
            if (group.content && Array.isArray(group.content)) {
              const groupData = {
                groupNo: parseInt(group.groupId),
                products: group.content.map((product, productIndex) => ({
                  nutritionProductId: product.id ? `${product.id}_${configureTableData.length}_${productIndex}` : '',
                  dosePerTime: product.dosagePerTime || product.dosePerTime || '',
                  // 移除mealTime字段 - 这个字段应该在submitForm时根据timeSlots动态生成
                  // 移除多余的显示字段，保持与手动添加时的数据结构一致
                  usageDays: product.usageDays || 1,
                  specification: product.specification || '',
                  usage: product.usage || '',
                  prescriptionRemark: product.remark || product.prescriptionRemark || '',
                  dailyCalories: product.dailyCalorie || product.dailyCalories || '',
                  amount: product.amount || '',
                  dosePerDay: product.dosePerDay || '',
                  totalDose: product.totalDose || '',
                  productSpecUnit: product.productSpecUnit || 'g'
                })),
                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: configureTableData.length,
                tableId: Date.now() + configureTableData.length
              };
              configureTableData.push(groupData);
            }
          });
        } else {
          // 普通格式数据
          const groupData = {
            products: contentData.product.map((product, productIndex) => ({
              nutritionProductId: product.id ? `${product.id}_0_${productIndex}` : '',
              dosePerTime: product.dosagePerTime || product.dosePerTime || '',
              // 移除mealTime, productName, quantity, frequency, dailyDosage等多余字段
              usageDays: product.usageDays || 1,
              specification: product.specification || '',
              usage: product.usage || '',
              prescriptionRemark: product.remark || product.prescriptionRemark || '',
              dailyCalories: product.dailyCalorie || product.dailyCalories || '',
              amount: product.amount || '',
              dosePerDay: product.dosePerDay || '',
              totalDose: product.totalDose || '',
              productSpecUnit: product.productSpecUnit || 'g'
            })),
            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: Date.now()
          };
          configureTableData.push(groupData);
        }
      } else if (Array.isArray(contentData)) {
        // 兼容旧的数据结构
        const groupData = {
          products: contentData.map((product, productIndex) => ({
            nutritionProductId: product.id ? `${product.id}_0_${productIndex}` : '',
            productName: product.productName || '',
            quantity: product.quantity || '',
            dosePerTime: product.dosagePerTime || product.dosePerTime || '',
            mealTime: product.mealTime || [],
            frequency: product.frequency || '一天次',
            dailyDosage: product.dailyDosage || 'g',
            usageDays: product.usageDays || 1,
            specification: product.specification || '',
            usage: product.usage || '',
            prescriptionRemark: product.remark || product.prescriptionRemark || '',
            dailyCalories: product.dailyCalorie || product.dailyCalories || '',
            amount: product.amount || '',
            dosePerDay: product.dosePerDay || '',
            totalDose: product.totalDose || '',
            productSpecUnit: product.productSpecUnit || 'g'
          })),
          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: Date.now()
        };
        configureTableData.push(groupData);
      }

      // 更新ConfigureTable的数据
      const configDataString = JSON.stringify(configureTableData);
      console.log('准备设置ConfigureTable数据:', configureTableData);

      // 检查nutritionProductId格式
      configureTableData.forEach((group, groupIndex) => {
        if (group.products) {
          group.products.forEach((product, productIndex) => {
            console.log(`组${groupIndex}产品${productIndex}: nutritionProductId=${product.nutritionProductId}, productName=${product.productName}`);
          });
        }
      });

      console.log('ConfigureTable数据字符串:', configDataString);

      configData.value = configDataString;
      console.log('已设置configData.value:', configData.value);

      // 处理耗材数据（如果模板中包含耗材数据）
      if (contentData.consumable && Array.isArray(contentData.consumable)) {
        console.log('模板包含耗材数据:', contentData.consumable);

        // 将耗材数据也传递给MaterialTable
        configureTableData.forEach((configRow, index) => {
          if (contentData.consumable[index]) {
            const consumable = contentData.consumable[index];
            configRow.consumableData = {
              consumableId: consumable.id || '',
              suppliesName: consumable.suppliesName || consumable.name || '',
              specification: consumable.specification || '',
              dosePerTime: consumable.dosePerTime || 1,
              amount: consumable.amount || 0
            };
          }
        });
        console.log('添加耗材数据到配置:', configureTableData);
      }

      // 使用nextTick确保数据更新完成
      nextTick(() => {
        console.log('nextTick后，configData.value:', configData.value);
      });

      // MaterialTable会通过watch自动响应configData的变化
      proxy?.$modal.msgSuccess('模板导入成功');
    }
  } catch (error) {
    console.error('处理模板数据失败:', error);
    proxy?.$modal.msgError('模板导入失败，请重试');
  }
};

const deleteFrom = async () => {
  configData.value = JSON.stringify([]);
};

const submitForm = async (status: string) => {
  let param = ref<EnteralNutritionSaveForm>({});
  param.value.patientId = patientInfo.id;
  param.value.visitType = patientInfo.type;

  param.value.patientNo = patientInfo.outpatientNo;
  param.value.status = status;

  if (prescriptionType.value == '3') {
    param.value.chargeType = '3';
    if (!configData.value || configData.value.length == 0) {
      proxy?.$modal.msgError('营养产品不为空');
      return;
    }
    param.value.nutritionList = JSON.parse(configData.value);

    if (!materialData.value || materialData.value.length == 0) {
      proxy?.$modal.msgError('耗材不为空');
      return;
    }
    param.value.consumableList = JSON.parse(materialData.value);
  } else if (prescriptionType.value == '2') {
    param.value.chargeType = '2';
    if (!packageData.value || packageData.value.length == 0) {
      proxy?.$modal.msgError('营养产品不为空');
      return;
    }
    param.value.nutritionList = JSON.parse(packageData.value);
  } else {
    param.value.chargeType = '4';
    if (!longTermData.value || longTermData.value.length == 0) {
      proxy?.$modal.msgError('营养产品不为空');
      return;
    }
    param.value.nutritionList = JSON.parse(longTermData.value);

    if (!materialData2.value || materialData2.value.length == 0) {
      proxy?.$modal.msgError('耗材不为空');
      return;
    }
    param.value.consumableList = JSON.parse(materialData2.value);
  }

  if (param.value.chargeType != '2') {
    for (let item of param.value.consumableList) {
      if (!item.consumableId) {
        proxy?.$modal.msgError('耗材没有选择');
        return;
      }

      item.groupNo = item.sn;
      let arr = item.consumableId.split('_');
      item.consumableId = arr[0];
    }

    for (let item of param.value.nutritionList) {
      if (!item.products || item.products.length == 0) {
        proxy?.$modal.msgError('营养产品没有记录');
        return;
      }

      let tsList = [];
      item.timeSlots.forEach((ts) => {
        tsList.push(ts.checked ? ts.time : '');
      });
      item.mealTime = tsList.join(',');
      item.prescriptionDate = prescriptionDate.value;
      item.prescriptionType = param.value.chargeType;

      for (let pd of item.products) {
        if (!pd.nutritionProductId) {
          proxy?.$modal.msgError('营养产品没有选择');
          return;
        }

        let arr = pd.nutritionProductId.split('_');
        pd.nutritionProductId = arr[0];
        pd.usage = item.usage;
        pd.preparationVolumePerTime = item.preparationVolumePerTime;
        pd.preparationConcentrationPerTime = item.preparationConcentrationPerTime;
        pd.energyDensityPerTime = item.energyDensityPerTime;

        pd.prescriptionDate = prescriptionDate.value;
        pd.groupNo = item.sn;
      }
    }
  } else {
    for (let item of param.value.nutritionList) {
      let tsList = [];
      item.timeSlots.forEach((ts) => {
        tsList.push(ts.checked ? ts.time : '');
      });
      item.mealTime = tsList.join(',');
      item.prescriptionDate = prescriptionDate.value;
      item.prescriptionType = param.value.chargeType;

      if (!item.nutritionProductId) {
        proxy?.$modal.msgError('营养产品没有选择');
        return;
      }

      let arr = item.nutritionProductId.split('_');
      item.nutritionProductId = arr[0];

      item.prescriptionDate = prescriptionDate.value;
      item.groupNo = item.sn;
    }
  }

  await addEnteralNutrition(param.value).finally(() => (buttonLoading.value = false));
  proxy?.$modal.msgSuccess('操作成功');
};

// 添加配置处方
const addPrescription = () => {
  prescriptionType.value = '3';
  tableType.value = '3';
};

// 添加预包装处方
const addTemplate = () => {
  prescriptionType.value = '2';
  tableType.value = '2';
};

// 添加长期医嘱处方
const addLongTerm = () => {
  prescriptionType.value = '4';
  tableType.value = '4';
};

// 跳转历史处方页面
const goHistoryPrescription = () => {
  emit('gotoTop');
};

function formatDate(date) {
  const pad = (n) => (n < 10 ? '0' + n : n);
  return date.getFullYear() + '-' + pad(date.getMonth() + 1) + '-' + pad(date.getDate());
}

// 禁用今天之前的日期
const disabledBeforeToday = (date) => {
  const today = new Date();
  // 设置时间为今天凌晨，确保比较的是日期而非具体时间
  today.setHours(0, 0, 0, 0);
  return date < today;
};

onMounted(() => {
  let now = new Date();
  let start = formatDate(now);
  prescriptionDate.value = start;

  // 初始化时发送空的营养产品列表
  emitNutritionProductsChange();
});
</script>

<style lang="scss" scoped>
.left-card {
  flex: 1;
  position: relative;

  .main-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 20px;
    }

    :deep(.el-tabs__nav) {
      .el-tabs__item {
        font-size: 15px;
        padding: 0 30px;
        height: 40px;
        line-height: 40px;
      }
    }
  }

  .operation-bar {
    margin-bottom: 16px;

    .right_btn {
      margin-left: 0px;
    }

    .add-buttons {
      display: flex;
      gap: 12px;
      margin-top: 30px;
      margin-bottom: 12px;

      .add-btn {
        min-width: 120px;
        background-color: #fff;
        border: 1px solid #dcdfe6;
        color: #606266;
        transition: all 0.3s;

        &.is-active {
          background-color: var(--el-color-primary);
          border-color: var(--el-color-primary);
          color: #fff;
        }

        &:hover:not(.is-active) {
          border-color: var(--el-color-primary);
          color: var(--el-color-primary);
        }
      }
    }

    .prescription-reason {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #f56c6c;
      font-size: 14px;

      .reason-label {
        color: #606266;
      }

      .reason-value {
        color: #f56c6c;
      }
    }
  }

  .prescription-info {
    margin-bottom: 16px;

    .warning-box {
      padding: 8px 16px;
      background: #fff7e6;
      border: 1px solid #ffd591;
      border-radius: 4px;
      color: #fa8c16;
      border: 1px solid #fa8c16;
      font-size: 12px;
      line-height: 1.5;
    }
  }

  .prescription-tables {
    display: flex;
    flex-direction: column;
    gap: 20px;
    margin-bottom: 16px;
  }
}
</style>
