<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>批量添加营养品</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-panel">
        <el-radio-group v-model="selectedTemplate" direction="vertical" @change="handleTemplateChange">
          <el-radio label="基础公共模版">基础公共模版</el-radio>
          <el-radio label="个人模版">个人模版</el-radio>
        </el-radio-group>
      </div>

      <!-- 右侧表格区域 -->
      <div class="right-panel">
        <table class="custom-table">
          <thead>
            <tr>
              <th>产品名称</th>
              <th width="120">数量</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in templateTableData" :key="index">
              <td>{{ item.productName }}</td>
              <td>{{ item.dosePerTime }}{{ item.unit }}</td>
            </tr>
            <tr v-if="templateTableData.length === 0">
              <td colspan="3" class="no-data">暂无数据</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <div class="selected-info">
      <span class="selected-count">已选 ({{ selectedCount }})</span>
    </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>
</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 {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 selectedTemplate = ref('基础公共模版');

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

// 添加单选框选择变化处理方法
const handleTemplateChange = (value) => {
  console.log('选中的模板类型:', value);
  // value 就是选中的值："基础公共模版" 或 "个人模版"

  // 根据选择更新右侧表格数据
  if (value === '基础公共模版') {
    templateTableData.value = [
      {productName: '基础产品1', dosePerTime: '5.0000', unit: 'g'},
      {productName: '基础产品2', dosePerTime: '1.0000', unit: '袋'},
      {productName: '基础产品2', dosePerTime: '1.0000', unit: '袋'},
      {productName: '基础产品2', dosePerTime: '1.0000', unit: '袋'}
    ];
    selectedCount.value = templateTableData.value.length;
  } else if (value === '个人模版') {
    templateTableData.value = [
      {productName: '个人产品1', dosePerTime: '3.0000', unit: 'g'},
      {productName: '个人产品2', dosePerTime: '2.0000', unit: '袋'}
    ];
    selectedCount.value = templateTableData.value.length;
  }
};

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

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[]>([createDefaultRow()]);
const emit = defineEmits(['change']);

// 添加产品输入框
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.specification=item.productSpec;
    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 = () => {
  dialogVisible.value = true;
};

// 确认选择模板
const handleConfirm = () => {
  dialogVisible.value = false;
  // 这里处理选中模板后的逻辑
};
onMounted(() => {
  getProductNutritionList();
});
</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;
    gap: 20px;
    min-height: 400px;
    border: 1px solid #ebeef5;

    .left-panel {
      width: 200px;
      padding: 20px;
      border-right: 1px solid #ebeef5;

      :deep(.el-radio-group) {
        display: flex;
        gap: 16px;
      }

      :deep(.el-radio) {
        margin-right: 0;
        height: auto;

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

    .right-panel {
      flex: 1;
      padding: 16px;
      overflow: auto;
    }
  }

  .selected-info {
    margin: 16px 0;

    .selected-count {
      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;
  }

  .no-data {
    color: #909399;
    text-align: center;
    padding: 40px;
  }
}
</style>
