<template>
  <div
    class="app-container"
    style="border: 1px solid #e0e0e0; border-radius: 4px; box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.1)"
  >
    <el-row :gutter="10" justify="end" align="middle" style="margin-bottom: 10px">
      <el-button type="danger" plain icon="Refresh" @click="handleSendDrug" :disabled="!encounterId"
        >发药</el-button
      >
      <el-button type="primary" plain icon="Download" @click="handleExport" :disabled="!encounterId"
        >导出</el-button
      >
      <el-button
        type="success"
        plain
        icon="Refresh"
        @click="handleDispense"
        :disabled="!encounterId"
        >退药</el-button
      >
    </el-row>
    <div class="tableContainer">
      <el-table
        v-loading="loading"
        :data="displayTableData"
        style="width: 100%; height: 70vh"
        border
        stripe
        :header-cell-style="headerCellStyle"
        :row-style="rowStyle"
        :cell-style="{ textAlign: 'center' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <!-- 基础信息 -->
        <el-table-column prop="itemName" label="项目名称" min-width="120" />
        <el-table-column prop="totalVolume" label="规格" min-width="100" />
        <el-table-column prop="locationName" label="发放药房" min-width="100" />
        <el-table-column prop="lotNumber" label="批次号" min-width="100" />
        <el-table-column prop="departmentName" label="科室" min-width="100" />
        <el-table-column prop="doctorName" label="开单医生" min-width="100" />
        <el-table-column prop="dispenseDoctorName" label="发药医生" min-width="100" />
        <el-table-column prop="itemType_dictText" label="项目类型" min-width="100">
          <template #default="scope">
            {{ scope.row.itemType_dictText || scope.row.itemType || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="statusEnum_enumText" label="发药状态" min-width="100">
          <template #default="scope">
            {{ scope.row.statusEnum_enumText || scope.row.statusEnum || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="conditionName" label="诊断名称" min-width="100" />
        <el-table-column prop="prescriptionNo" label="处方号" min-width="120" />

        <!-- 用药信息 -->
        <el-table-column prop="dose" label="单次剂量" min-width="100" />
        <el-table-column prop="rateCode_dictText" label="用药频次" min-width="100">
          <template #default="scope">
            {{ scope.row.rateCode_dictText || scope.row.rateCode || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="methodCode_dictText" label="用法" min-width="100">
          <template #default="scope">
            {{ scope.row.methodCode_dictText || scope.row.methodCode || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="doseUnitCode_dictText" label="剂量单位" min-width="100">
          <template #default="scope">
            {{ scope.row.doseUnitCode_dictText || scope.row.doseUnitCode || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="unitCode_dictText" label="单位" min-width="80">
          <template #default="scope">
            {{ scope.row.unitCode_dictText || scope.row.unitCode || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="dispensePerQuantity" label="单次发药数" min-width="100" />
        <el-table-column prop="dispensePerDuration" label="每次发药供应天数" min-width="150" />
        <el-table-column prop="quantity" label="数量" min-width="80" />
        <el-table-column prop="unitPrice" label="单价" min-width="80" />
        <el-table-column prop="totalPrice" label="金额" min-width="80" />

        <!-- 其他信息 -->
        <el-table-column prop="manufacturerText" label="生产厂家" min-width="150" />
        <el-table-column prop="traceNo" label="追溯码" min-width="120" />
        <el-table-column prop="encounterBusNo" label="就诊NO" min-width="120" />
        <el-table-column prop="reqAuthoredTime" label="开具日期" min-width="150">
          <template #default="scope">
            {{ formatDate(scope.row.reqAuthoredTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="skinTestFlag" label="皮试标志" min-width="100">
          <template #default="scope">
            {{ scope.row.skinTestFlag === 1 ? '是' : scope.row.skinTestFlag === 0 ? '否' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="tcmFlag" label="中药标识" min-width="100">
          <template #default="scope">
            {{ scope.row.tcmFlag === 1 ? '是' : scope.row.tcmFlag === 0 ? '否' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="itemTable" label="所在表" min-width="100" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { totalSendDrug, totalReturnDrug } from './api';
import { getCurrentInstance } from 'vue';
const { proxy } = getCurrentInstance();
const emit = defineEmits(['call-medication-summary-detail']);
// 定义props，接收父组件传递的表格数据和选中的ID
const props = defineProps({
  tableData: {
    type: Array,
    default: () => [],
  },
  encounterId: {
    type: String,
    default: '',
  },
});

// 定义响应式数据
const selectedRows = ref([]);
const loading = ref(false);

// 计算属性，直接使用props.tableData，并添加日志用于调试
const displayTableData = computed(() => {
  return props.tableData;
});

// 处理表格选择变化
function handleSelectionChange(rows) {
  selectedRows.value = rows;
}

// 格式化日期
function formatDate(dateTime) {
  if (!dateTime) return '-';

  const date = new Date(dateTime);
  if (isNaN(date.getTime())) return '-';

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 监听props.tableData变化，当外部数据变化时清空选中状态
watch(
  () => props.tableData,
  () => {
    selectedRows.value = [];
  }
);

// 表格样式
const headerCellStyle = {
  backgroundColor: '#f5f7fa',
  color: '#333',
  fontWeight: 'bold',
  height: '48px',
  textAlign: 'center',
  lineHeight: '48px',
  padding: '0',
  fontSize: '14px',
};

const rowStyle = {
  height: '40px',
};
// 发药功能
const handleSendDrug = () => {
  if (!props.encounterId) {
    ElMessage.warning('请先选择患者');
    return;
  }
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要发药的数据');
    return;
  }
  let data = [];
  selectedRows.value.forEach((row) => {
    data.push({
      dispenseId: row.dispenseId,
    });
  });
  loading.value = true;
  proxy.$modal
    .confirm('确定要发药吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(async () => {
      const response = await totalSendDrug(data);
      if (response.code === 200) {
        ElMessage.success('发药成功');
        loading.value = false;
      }
    })
    .catch(() => {
      loading.value = false;
    });
};
// 导出功能
const handleExport = () => {
  if (!props.encounterId) {
    ElMessage.warning('请先选择患者');
    return;
  }
  if (displayTableData.value.length === 0) {
    ElMessage.warning('暂无数据可导出');
    return;
  }

  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要导出的数据');
    return;
  }

  // 这里可以实现导出逻辑
  console.log('导出数据:', selectedRows.value);
  ElMessage.success('导出成功');
};

// 退药功能
const handleDispense = () => {
  if (!props.encounterId) {
    ElMessage.warning('请先选择患者');
    return;
  }
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择需要退药的数据');
    return;
  }
  let data = [];
  selectedRows.value.forEach((row) => {
    data.push({
      dispenseId: row.dispenseId,
    });
  });
  loading.value = true;
  proxy.$modal
    .confirm('确定要退药吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(async () => {
      const response = await totalReturnDrug(data);
      emit('call-medication-summary-detail', props.encounterId);
      console.log(response);
      if (response.code === 200) {
        ElMessage.success('退药成功');
        loading.value = false;
        // 通知父组件刷新明细数据
        emit('call-medication-summary-detail', props.encounterId);
      } else {
        console.log(response.message);
        ElMessage.error('退药失败');
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

// 定义暴露给父组件的数据和方法
defineExpose({
  selectedRows,
});
</script>

<style lang="scss" scoped>
.medicationTableDetail {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;

  .buttonGroup {
    display: flex;
    justify-content: flex-end;
    padding: 10px 0;
    gap: 10px;
    margin-right: 20px;

    :deep(.el-button) {
      padding: 6px 16px;
      font-size: 14px;
    }
  }

  .tableContainer {
    flex: 1;
    overflow-x: auto; /* 启用横向滚动 */
    overflow-y: auto; /* 同时启用纵向滚动 */
    border: 1px solid #e0e0e0;
    border-radius: 4px;

    :deep(.el-table) {
      height: 100%;

      .el-table__header {
        th {
          background-color: #f5f7fa;
          height: 48px !important;
          line-height: 48px !important;
          padding: 0 !important;
        }
      }

      .el-table__row:hover {
        background-color: #f5f7fa;
      }
    }
  }
}
</style>
