<template>
  <div style="height: calc(100vh - 176px)">
    <div
      style="padding: 10px; background-color: #eef9fd; height: 100%; overflow-y: auto"
      v-loading="loading"
    >
      <el-table
        :data="medicineSummaryFormList"
        border
        :ref="'tableRef' + index"
        :header-cell-style="{ background: '#eef9fd !important' }"
      >
        <el-table-column label="单据号" prop="busNo" align="center" width="180" />
        <el-table-column label="申请时间" align="center" prop="applyTime" />
        <el-table-column label="发药时间" align="center" prop="dispenseTime" />
        <el-table-column label="药房" align="center" prop="locationName" />
        <el-table-column label="申请人" align="center" prop="applicantName" />
        <el-table-column label="领药人" align="center" prop="receiverName" />
        <el-table-column label="发药状态" align="center" prop="statusEnum_enumText" />
        <el-table-column label="操作" width="100" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="getDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog v-model="dialogVisible" title="汇总单详情" width="900">
      <el-table
        :data="medicineSummaryFormDetails"
        border
        :header-cell-style="{ background: '#eef9fd !important' }"
      >
        <el-table-column label="序号" type="index" align="center" width="60" />
        <el-table-column label="药品名称" prop="itemName" align="center" />
        <el-table-column label="规格" prop="totalVolume" align="center" width="180" />
        <el-table-column label="批次号" prop="lotNumber" align="center" width="180" />
        <el-table-column label="数量" prop="itemQuantity" align="center" width="180">
          <template #default="scope">
            <span>{{ scope.row.itemQuantity + ' ' + scope.row.minUnitCode_dictText }}</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { getMedicineSummary, getMedicineSummaryDetail } from './api';
import { patientInfoList } from '../store/patient.js';
import { ref, getCurrentInstance } from 'vue';

const medicineSummaryFormList = ref([]);
const medicineSummaryFormDetails = ref([]);
const dialogVisible = ref(false);
const { proxy } = getCurrentInstance();
const loading = ref(false);
const props = defineProps({
  exeStatus: {
    type: Number,
    default: 1,
  },
  requestStatus: {
    type: Number,
    default: 1,
  },
});

handleGetPrescription();
function handleGetPrescription() {
  loading.value = true;
  let encounterIds = patientInfoList.value.map((i) => i.encounterId).join(',');
  getMedicineSummary({}).then((res) => {
    medicineSummaryFormList.value = res.data.records;
    loading.value = false;
  });
}

// 获取发药单详情
function getDetail(row) {
  getMedicineSummaryDetail({ summaryNo: row.busNo }).then((res) => {
    medicineSummaryFormDetails.value = res.data;
    dialogVisible.value = true;
  });
}

function handleExecute() {
  let list = getSelectRows();
  list = list.map((item) => {
    return {
      requestId: item.requestId,
      accountId: item.accountId,
      adviceTable: item.adviceTable,
      executeTimes: item.executeTimes,
    };
  });
}

function handleCancel() {
  let list = getSelectRows();
  console.log(list, 'list');
  list = list.map((item) => {
    return {
      procedureId: item.procedureId,
      executeTimes: item.cancelTimes,
    };
  });
}

function getSelectRows() {
  // 获取选中的医嘱信息
  let list = [];
  prescriptionList.value.forEach((item, index) => {
    list = [...list, ...proxy.$refs['tableRef' + index][0].getSelectionRows()];
  });
  return list;
}

/**
 * 计算两个日期之间的所有日期（包含起始和结束日期）
 * @param {string|Date} startDate - 开始日期
 * @param {string|Date} endDate - 结束日期
 * @returns {Array<string>} 格式为MM-DD的日期数组
 */
function getDateRange(startDate, endDate) {
  const start = new Date(startDate);
  const end = new Date(endDate);

  // 重置时间部分，只保留日期
  start.setHours(0, 0, 0, 0);
  end.setHours(0, 0, 0, 0);

  const dates = [];
  const current = new Date(start);

  // 循环添加日期直到结束日期
  while (current <= end) {
    // 格式化为MM-DD
    const month = String(current.getMonth() + 1).padStart(2, '0');
    const day = String(current.getDate()).padStart(2, '0');
    dates.push(`${month}-${day}`);

    // 移动到下一天
    current.setDate(current.getDate() + 1);
  }
  return dates;
}

function handleRateChange(value, date, time, row) {
  // 拼接当前选中时间
  let tiemStr = row.year + '-' + date + ' ' + time + ':00';
  if (value) {
    row.executeTimes.push(tiemStr);
  } else {
    row.executeTimes.splice(row.executeTimes.indexOf(tiemStr), 1);
  }
  console.log(row.executeTimes, 'row.executeTimes');
}

function handelSwicthChange(value) {
  prescriptionList.value.forEach((item, index) => {
    proxy.$refs['tableRef' + index][0].toggleAllSelection();
  });
}

// 处理后端返回的时间集合
function handleTime() {}

defineExpose({
  handleGetPrescription,
});
</script>

<style scoped>
.el-collapse-icon-position-left :deep(.el-collapse-item__header) {
  padding: 10px;
}

:deep(.el-collapse-item__wrap) {
  padding: 10px;
}

/* 表头背景色 */
:deep(.prescription-table .el-table__header th) {
  background-color: #eef9fd !important;
}

:deep(.el-table__row:hover > td) {
  background-color: #eef9fd !important;
}

.item-value {
  color: #606266;
  font-size: 15px;
  font-weight: 500;
}
</style>