<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>处方模板</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>
</template>

<script setup lang="ts">
import {ref,defineProps} 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: 1,
    frequency: 3,
    dosePerTime: 1,
    dosePerDay: 3,
    usageDays: 1,
    quantity: 1,
    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 = row.dosePerTime;
    }
    
    row.specification=item.suppliesSpec;
    row.dosePerDay = row.frequency * dosePerTime;
    row.quantity = ((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 = row.dosePerTime;
      }

      row.frequency = Number(item.frequency);
      row.usageDays = Number(item.usageDays);
      row.firstDay = Number(item.firstDay);
      row.dosePerDay = item.frequency * dosePerTime;
      row.quantity = ((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 = ((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))
};


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;
            }
          }
        }
      }
    }
  }
}
</style>
