<template>
  <div style="height: calc(100vh - 176px)">
    <div
      style="padding: 10px; background-color: #eef9fd; height: 100%; overflow-y: auto"
      v-loading="loading"
    >
      <el-collapse
        v-model="activeNames"
        expand-icon-position="left"
        v-if="prescriptionList.length > 0"
        style="
          border-bottom: 0px;
          border-top: 0px;
          border-radius: 0px;
          overflow-y: auto;
          max-height: calc(100vh - 200px);
        "
      >
        <el-collapse-item
          v-for="(item, index) in prescriptionList"
          :key="index"
          :name="item[0].encounterId"
          style="
            border: 2px solid #e4e7ed;
            border-radius: 8px;
            margin-bottom: 10px;
            overflow: hidden;
          "
        >
          <template #title>
            <div style="display: flex; justify-content: space-between; align-items: center">
              <div>
                <span>{{ item[0].bedName + '【' + item[0].busNo + '】' }}</span>
                <span>
                  {{
                    item[0].patientName + ' / ' + item[0].genderEnum_enumText + ' / ' + item[0].age
                  }}
                </span>
                <el-tag style="margin-left: 10px">{{ item[0].contractName }}</el-tag>
                <span style="margin-left: 30px; font-weight: 600">
                  {{ item[0].conditionNames }}
                </span>
              </div>
              <div
                style="
                  display: flex;
                  justify-content: space-between;
                  gap: 20px;
                  align-items: center;
                  margin-right: 20px;
                "
              >
                <div style="display: inline-block; margin-right: 10px">
                  <span class="descriptions-item-label">住院医生：</span>
                  <span>{{ item[0].requesterId_dictText }}</span>
                </div>
                <div style="display: inline-block; margin-right: 10px">
                  <div
                    class="descriptions-item-label"
                    style="height: 20px; line-height: 20px; text-align: center; margin: 0"
                  >
                    预交金额
                  </div>
                  <div
                    style="
                      height: 20px;
                      line-height: 20px;
                      text-align: center;
                      font-size: 15px;
                      color: #ec8c43;
                    "
                  >
                    {{ item[0].balanceAmount?.toFixed(2) }}
                  </div>
                </div>
              </div>
            </div>
          </template>
          <el-table
            :data="item"
            border
            :ref="'tableRef' + index"
            :header-cell-style="{ background: '#eef9fd !important' }"
          >
            <el-table-column type="selection" align="center" width="50" />
            <el-table-column label="类型" align="center" prop="therapyEnum_enumText" width="80">
              <template #default="scope">
                <span :style="scope.row.therapyEnum == '1' ? 'color: #a6745c' : 'color: #3787a5'">
                  {{ scope.row.therapyEnum_enumText }}
                </span>
              </template>
            </el-table-column>
            <el-table-column label="医嘱内容" prop="adviceName">
              <template #default="scope">
                <span>
                  {{ scope.row.adviceName }}
                </span>
                <template v-if="scope.row.adviceTable == 'med_medication_request'">
                  <span>
                    {{ ' 【' + scope.row.volume + '】' }}
                  </span>
                  <span style="color: #447c95 !important">
                    {{
                      '(' +
                      scope.row.methodCode_dictText +
                      ' ' +
                      scope.row.dose +
                      scope.row.doseUnitCode_dictText +
                      ' ' +
                      scope.row.rateCode_dictText +
                      ')'
                    }}
                  </span>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="领药总量" prop="requestTime" width="150">
              <template #default="scope">
                {{ '1支' }}
              </template>
            </el-table-column>
            <el-table-column label="取药科室" prop="requestTime" width="150">
              <template #default="scope">
                {{ scope.row.positionName }}
              </template>
            </el-table-column>
            <el-table-column label="领药时间" prop="times">
              <template #default="scope">
                <div
                  v-for="(item, timeIndex) in scope.row.times"
                  :key="timeIndex"
                  style="padding-bottom: 5px"
                >
                  <span>{{ item }}</span>
                  <el-checkbox-group
                    v-model="scope.row.checkedRates[item]"
                    style="display: inline-block; margin-left: 15px"
                  >
                    <el-checkbox
                      v-for="(rateItem, rateIndex) in scope.row.rate[item]"
                      :key="rateIndex"
                      :value="rateItem.rate"
                      @change="(value) => handleRateChange(value, rateItem, scope.row)"
                      border
                      size="small"
                      style="margin-right: 15px"
                    >
                      {{ rateItem.rate }}
                      <template v-if="rateItem.practitionerName">
                        {{ rateItem.practitionerName }}
                      </template>
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <el-empty v-else description="点击查询获取患者医嘱信息"></el-empty>
    </div>
  </div>
</template>

<script setup>
import {getPrescriptionList, medicineSummary} from './api';
import {patientInfoList} from '../../components/store/patient.js';
import {formatDateStr} from '@/utils/index';
import {getCurrentInstance, ref} from 'vue';
import useUserStore from '@/store/modules/user';

const activeNames = ref([]);

const userStore = useUserStore();
const prescriptionList = ref([]);
const deadline = ref(formatDateStr(new Date(), 'YYYY-MM-DD') + ' 23:59:59');
const { proxy } = getCurrentInstance();
const loading = ref(false);
const chooseAll = ref(false);
const props = defineProps({
  exeStatus: {
    type: Number,
    default: 1,
  },
  requestStatus: {
    type: Number,
    default: 1,
  },
  deadline: {
    type: String,
  },
  therapyEnum: {
    type: Number,
    default: undefined,
  },
});

function handleGetPrescription() {
  if (patientInfoList.value.length > 0) {
    loading.value = true;
    let encounterIds = patientInfoList.value.map((i) => i.encounterId).join(',');
    getPrescriptionList({
      encounterIds: encounterIds,
      pageSize: 10000,
      pageNo: 1,
      therapyEnum: props.therapyEnum,
      exeStatus: props.exeStatus,
      requestStatus: props.requestStatus,
    })
      .then((res) => {
        // try {
        // 根据encounterId分组
        const groupedPrescriptions = res.data.records.reduce((groups, prescription) => {
          let times = new Set();
          let rate = {};
          let checkedRates = {};
          // 汇总时间点 默认全部汇总
          prescription.dispenseIds = [];
          prescription.medicineSummaryParamList.forEach((item) => {
            // 已汇总的时间点不需要显示
            if (item.dispenseStatus != 8) {
              prescription.dispenseIds.push({
                dispenseId: item.dispenseId,
                receiverId: userStore.id,
              });

              // 将全部的时间点拆分 把日期去重，页面显示示例 05-15 [01:30 02:30 03:30]
              let time = item.dispenseTime?.substring(5, 10);
              let rateTime = item.dispenseTime?.substring(11, 16);
              times.add(time);
              rate[time] = rate[time] || [];
              rate[time].push({ rate: rateTime, dispenseId: item.dispenseId });
              checkedRates[time] = checkedRates[time] || [];
              checkedRates[time].push(rateTime);
            }
          });

          prescription.times = Array.from(times);
          prescription.rate = rate;
          prescription.checkedRates = checkedRates;
          // 把相同encounterId的医嘱放在同一个数组中
          const encounterId = prescription.encounterId;
          if (!groups[encounterId]) {
            groups[encounterId] = [];
          }
          if (!activeNames.value.includes(encounterId)) {
            activeNames.value.push(encounterId);
          }
          groups[encounterId].push(prescription);
          return groups;
        }, {});

        // 将分组结果转换为数组形式
        prescriptionList.value = Object.values(groupedPrescriptions);
        loading.value = false;
        // } catch {
        //   loading.value = false;
        // }
      })
      .catch((err) => {
        loading.value = false;
        useUserStore()
          .logOut()
          .then(() => {
            ElMessage.error(err);
            next({ path: '/' });
          });
      });
    chooseAll.value = false;
  } else {
    prescriptionList.value = [];
    // proxy.$message.warning('请选择患者');
  }
}

function handleMedicineSummary() {
  let paramList = getSelectRows();
  if (!paramList || paramList.length === 0) {
    proxy.$message.warning('请至少选择一条待汇总的药品');
    return;
  }
  let ids = [];
  paramList.forEach((item) => {
    ids.push(...item.dispenseIds);
  });
  if (ids.length === 0) {
    proxy.$message.warning('所选药品未关联发放信息');
    return;
  }
  medicineSummary(ids).then((res) => {
    if (res.code == 200) {
      proxy.$message.success('操作成功');
    }
  });
}

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

function getTableRef(index) {
  return proxy.$refs['tableRef' + index]?.[0];
}

function selectAllRows() {
  prescriptionList.value.forEach((item, index) => {
    const tableRef = getTableRef(index);
    if (!tableRef) {
      return;
    }
    item.forEach((row) => {
      tableRef.toggleRowSelection(row, true);
    });
  });
}

function clearSelection() {
  prescriptionList.value.forEach((item, index) => {
    getTableRef(index)?.clearSelection();
  });
}

function handleRateChange(value, item, row) {
  // 拼接当前选中时间
  if (value) {
    row.dispenseIds.push({ dispenseId: item.dispenseId, receiverId: userStore.id });
  } else {
    row.dispenseIds.splice(
      row.dispenseIds.findIndex((k) => {
        return k.dispenseId === item.dispenseId;
      }),
      1
    );
  }
}

defineExpose({
  handleGetPrescription,
  handleMedicineSummary,
  selectAllRows,
  clearSelection,
});
</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>
