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

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

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

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

      <el-table-column label="金额" width="80" align="center">
        <template #default="{row}">
          <span>{{ row.amount }}</span>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-footer">
      <div class="left-buttons">
        <el-button type="primary" plain>登为个人模板</el-button>
        <el-button type="primary" plain>批量添加营养品</el-button>
        <el-button type="primary" plain @click="openTemplate">处方模板</el-button>
      </div>
      <div class="right-summary">
        <div class="summary-list">
          <div class="summary-item">
            <span class="label">处方费用：</span>
            <span class="value">￥{{ nutritionalFee + otherlFee }}</span>
          </div>
          <div class="summary-item">
            <span class="label">营养配置费：</span>
            <span class="value">￥{{ prescriptionFee }}</span>
          </div>
          <div class="summary-item total">
            <span class="label">总计：</span>
            <span class="value">￥{{ totalFee + otherlFee }}</span>
          </div>
        </div>
      </div>
    </div>
  </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']"
          show-checkbox
          @check="handleCheck"
        />
      </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>
</template>

<script setup lang="ts">
import {ref, defineProps, watch, onMounted} from 'vue';
import {listAll} from '@/api/warehouse/suppliesManage';
import {SuppliesManageVO} from '@/api/warehouse/suppliesManage/types';
import {
  listNutritionConsumable,
  getNutritionConsumable,
  delNutritionConsumable,
  addNutritionConsumable,
  updateNutritionConsumable
} from '@/api/patients/nutritionConsumable';
import {NutritionConsumableForm} from '@/api/patients/nutritionConsumable/types';

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

const emit = defineEmits(['change']);

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

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

// 示例数据
const tableData = ref<TableRow[]>([
  {
    firstDay: 2,
    frequency: 3,
    dosePerTime: 1,
    dosePerDay: 3,
    usageDays: 0,
    quantity: 0,
    sn: 0,
    tableId: 0
  }
]);

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

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

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

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

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

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

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

    break;
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// 搜索值
const searchValue = ref('');
// 选中的节点
const selectedNode = ref('');
// 已选数量
const selectedCount = ref(2);

// 树形控件数据
const treeData = ref([
  {
    id: '1',
    label: '基础公共模板',
    children: [
      {
        id: '1-1',
        label: '精氨酸组件'
      },
      {
        id: '1-2',
        label: '谷氨酰胺组件'
      },
      {
        id: '1-3',
        label: '免疫营养组件'
      },
      {
        id: '1-4',
        label: '肠内营养组件'
      },
      {
        id: '1-5',
        label: '肠外营养组件'
      }
    ]
  },
  {
    id: '2',
    label: '万颗星营养智能医院',
    children: [
      {
        id: '2-1',
        label: '中链甘油三酯MCT组件'
      },
      {
        id: '2-2',
        label: '口服补糖盐饮品'
      },
      {
        id: '2-3',
        label: '膳食纤维组件'
      },
      {
        id: '2-4',
        label: 'ERAS专用碳水化合物饮品'
      },
      {
        id: '2-5',
        label: '白蛋白肽组件'
      },
      {
        id: '2-6',
        label: '乳清蛋白组件'
      },
      {
        id: '2-7',
        label: '益生菌组件'
      },
      {
        id: '2-8',
        label: '鱼油蛋白组件'
      }
    ]
  },
  {
    id: '3',
    label: '个人模板',
    children: [
      {
        id: '3-1',
        label: '术前营养支持方案'
      },
      {
        id: '3-2',
        label: '术后恢复营养方案'
      },
      {
        id: '3-3',
        label: '重症营养支持方案'
      }
    ]
  },
  {
    id: '4',
    label: '科室模板',
    children: [
      {
        id: '4-1',
        label: '外科营养支持方案'
      },
      {
        id: '4-2',
        label: '内科营养支持方案'
      },
      {
        id: '4-3',
        label: 'ICU营养支持方案'
      },
      {
        id: '4-4',
        label: '肿瘤科营养支持方案'
      }
    ]
  }
]);

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

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

// 树节点选中事件
const handleCheck = (data: any, checked: any) => {
  console.log(data, checked);
  // 这里处理节点选中逻辑
};

// 打开处方模板
const openTemplate = () => {
  dialogVisible.value = true;
};

// 确认选择模板
const handleConfirm = () => {
  dialogVisible.value = false;
  // 这里处理选中模板后的逻辑
};

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

<style lang="scss" scoped>
.material-table {
  :deep(.el-table) {
    // 表头样式
    .el-table__header {
      th {
        background-color: #f5f7fa;
        color: #606266;
        font-weight: 500;
        padding: 8px 0;
        height: 40px;
      }
    }

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

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

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

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

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

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

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

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

      .input-center {
        width: 100px;

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

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

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

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

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

        :deep(.el-checkbox) {
          margin-right: 0;
          .el-checkbox__label {
            display: none;
          }
        }

        :deep(.el-time-select) {
          .el-input {
            width: 120px;
          }
          .el-input__wrapper {
            padding: 0 8px;
            border-radius: 2px;
            box-shadow: 0 0 0 1px #dcdfe6 inset;
            &:hover:not(.is-disabled) {
              box-shadow: 0 0 0 1px #c0c4cc inset;
            }
            &.is-disabled {
              background-color: #f5f7fa;
              box-shadow: 0 0 0 1px #e4e7ed inset;
              .el-input__inner {
                color: #909399;
                -webkit-text-fill-color: #909399;
              }
            }
          }
          .el-input__inner {
            height: 32px;
            text-align: center;
            font-size: 14px;
            color: #606266;
          }
        }
      }
    }
  }

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

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

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

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

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

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

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

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

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

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

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

          &.total {
            margin-top: 4px;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  tbody tr:hover {
    background-color: #f5f7fa;
  }
}
</style>
