<template>
  <div class="nutrition-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 v-for="(product, index) in row.products" :key="index" class="product-row" style="margin-bottom: 5px">
              <el-select v-model="product.nutritionProductId" placeholder="请选择" @change="changeProductSelect">
                <el-option
                  v-for="pn in productNutritionList"
                  :key="pn.id"
                  :label="pn.productName"
                  :value="pn.id + '_' + row.sn + '_' + index"
                ></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="removeProduct(row, index)">
                  <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="dosage-group">
            <div v-for="(product, index) in row.products" :key="index" class="dosage-input">
              <el-input
                v-model="product.dosePerTime"
                placeholder="请输入"
                class="input-center"
                @input="dosePerTimeInput(product.dosePerTime, row.sn + '_' + index)"
              />
              <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" v-for="(product, index) in row.products" :key="index">
            <span>{{ product.dosePerDay }}</span>
            <span class="unit">{{ product.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" v-for="(product, index) in row.products" :key="index">
            <span>{{ product.totalDose }}</span>
            <span class="unit">{{ product.productSpecUnit }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="规格" width="100" align="center">
        <template #default="{row}">
          <div class="daily-dosage" v-for="(product, index) in row.products" :key="index">
            <span>{{ product.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="170" align="center">
        <template #default="{row}">
          <el-input v-model="row.preparationVolumePerTime" @change="changePreparationVolumePerTime(row.preparationVolumePerTime, row.sn)">
            <template #append>ml</template>
          </el-input>
        </template>
      </el-table-column>

      <el-table-column label="制剂浓度/次" width="100" align="center">
        <template #default="{row}">
          <div class="daily-dosage">
            <span>{{ row.preparationConcentrationPerTime }}</span>
            <span class="unit">%</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="能量密度/次" width="200" align="center">
        <template #default="{row}">
          <el-input v-model="row.energyDensityPerTime" @change="changeEnergyDensityPerTime(row.energyDensityPerTime, row.sn)">
            <template #append>kcal/ml</template>
          </el-input>
        </template>
      </el-table-column>

      <el-table-column label="处方备注" width="200" align="center">
        <template #default="{row}">
          <template v-for="(product, index) in row.products">
            <el-input
              v-model="product.prescriptionRemark"
              :maxlength="100"
              :show-word-limit="true"
              @change="changePrescriptionRemark(product.prescriptionRemark, row.sn)"
            />
          </template>
        </template>
      </el-table-column>

      <el-table-column label="每日热量" width="100" align="center">
        <template #default="{row}">
          <div class="daily-dosage" v-for="(product, index) in row.products" :key="index">
            <span>{{ product.dailyCalories }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="金额" width="100" align="center">
        <template #default="{row}">
          <div class="daily-dosage" v-for="(product, index) in row.products" :key="index">
            <span>{{ product.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="table-footer">
      <el-button type="primary" class="add-prescription-btn" @click="addNewRow">
        <el-icon>
          <CirclePlus />
        </el-icon>
        开具多处方
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref} 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';

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

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

    let arr = JSON.parse(val);
    if (Array.isArray(arr) && arr.length == 0) {
      tableData.value = [];
    }
  },
  {deep: true, immediate: true}
);

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

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

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

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

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

// 创建默认行数据的函数
const createDefaultRow = (): TableRow => ({
  products: [{specification: '', totalDose: '', 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 emit = defineEmits(['change']);

// 示例数据
const tableData = ref<TableRow[]>([createDefaultRow()]);

// 新增行
const addNewRow = () => {
  let row: TableRow = createDefaultRow();
  row.sn = tableData.value.length;
  tableData.value.push(row);
  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])];
    let pt = row.products[Number(arr[2])];
    pt.specification=item.productSpec;
    pt.dosePerTime=null;     
    pt.dailyCalories=null;
    pt.productSpecUnit=item.productSpecUnit;
    pt.amount=null; 
    row.usage=item.defaultUsage;
    pt.totalDose='0' ;
    pt.dosePerDay='0';
    pt.firstDay=Math.ceil(row.frequency/2.0);
    break;
  }

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

// 新增产品输入框
const addProduct = (row: TableRow) => {
  row.products.push({});
};

// 删除产品输入框
const removeProduct = (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);
    }
    emit('change', JSON.stringify(tableData.value));
  } else {
    // 否则只删除当前输入框
    row.products.splice(index, 1);
  }
};

// 复制行
const copyRow = (index: number) => {
  const newRow = JSON.parse(JSON.stringify(tableData.value[index]));
  newRow.tableId = tableId.value++;
  tableData.value.splice(index + 1, 0, newRow);
  tableData.value.forEach((item, index) => {
    item.sn = index;
    item.products.forEach((ch, idx) => {
      if (ch.nutritionProductId) {
        let arr = ch.nutritionProductId.split('_');
        ch.nutritionProductId = arr[0] + '_' + index + '_' + idx;
      }
    });
  });
  emit('change', JSON.stringify(tableData.value));
};

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

  tableData.value.forEach((item, index) => {
    item.sn = index;
  });

  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 changePreparationVolumePerTime = (value: string, sn:string) => { 
  changeTimeSelection(null,sn);
}

const changeEnergyDensityPerTime = (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);
  }

  row.products.forEach((pt) => {
    if (!pt.dosePerTime || pt.dosePerTime.trim().length == 0) {
      return;
    }
    let arr = pt.nutritionProductId.split('_');

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

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

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

      val = (row.frequency * (row.usageDays - 1) + firstDay) * Number(pt.dosePerTime);
      pt.totalDose = val.toFixed(4);

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

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

const dosePerTimeInput = (value: string, str: string) => {
  let arr = str.split('_');
  let row = tableData.value[Number(arr[0])];
  let pt = row.products[Number(arr[1])];
  if (!pt.dosePerTime || pt.dosePerTime.trim().length == 0) {
    pt.dailyCalories = null;
    pt.amount = null;
    return;
  }

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

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

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

    val = (row.frequency * (row.usageDays - 1) + firstDay) * Number(pt.dosePerTime);
    pt.totalDose = val.toFixed(4);

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

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

onMounted(() => {
  getProductNutritionList();
});
</script>

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

  // 用量输入框组样式
  .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;
          }
        }
      }
    }
  }

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

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

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

    .el-button {
      padding: 4px 8px;
    }
  }

  .table-footer {
    height: 50px;
    border: 1px solid var(--el-table-border-color);
    border-top: none;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f5f7fa;

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

  .stop-date {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 16px;

    .required {
      color: #f56c6c;
      font-size: 14px;
    }

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

    .days {
      color: #f56c6c;
      font-size: 14px;
    }
  }
}

:deep(.daily-size div) {
  width: 100px;
}
</style>
