<!-- consumableDialog.vue -->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="绑定耗材"
    width="700px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <div class="consumable-dialog">
      <div class="dialog-header">
        <el-alert
          title="该诊疗项目已绑定所需耗材，可修改数量或删除不需要的耗材，点击确定将自动添加到医嘱列表"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>

      <div class="table-container">
        <el-table
          ref="consumableTableRef"
          :data="consumableList"
          row-key="orderDefinitionId"
          border
          style="width: 100%"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="orderDefinitionName" align="center" label="项目名称" />
          <el-table-column prop="unitCodeName" label="单位" align="center" width="80">
            <template #default="scope">
              {{ scope.row.unitCodeName || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="数量/执行次数" align="center" width="120">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.quantity"
                :min="1"
                size="small"
                controls-position="right"
                style="width: 100%"
                @change="handleQuantityChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center" fixed="right">
            <template #default="scope">
              <el-button type="danger" link size="small" @click="handleDeleteRow(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 下次不再提示复选框 -->
      <div class="dont-show-again">
        <el-checkbox v-model="dontShowAgain" @change="handleDontShowAgainChange">
          下次不再提示
        </el-checkbox>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button ref="submitRef" type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessageBox, ElMessage } from 'element-plus';
import { ref, nextTick, onBeforeUnmount } from 'vue';
import useUserStore from '@/store/modules/user';

const dialogVisible = ref(false);
const consumableList = ref([]);
const consumableTableRef = ref();
const submitRef = ref();
const dontShowAgain = ref(false); // 下次不再提示的状态
const userStore = useUserStore();

// 定义事件
const emit = defineEmits(['submit']);

// 键盘事件处理函数
const handleKeyDown = (event) => {
  // 检查是否按下了回车键
  if (event.key === 'Enter' && dialogVisible.value) {
    event.preventDefault();
    handleSubmit();
  }
};

// 打开弹窗方法
const open = (data) => {
  consumableList.value = data;
  dialogVisible.value = true;

  // 默认全选
  nextTick(() => {
    if (consumableTableRef.value) {
      consumableList.value.forEach((row) => {
        consumableTableRef.value.toggleRowSelection(row, true);
      });
    }

    // 注册键盘事件监听器
    document.addEventListener('keydown', handleKeyDown);
  });
};

// 关闭弹窗方法
const handleClose = () => {
  // 移除键盘事件监听器
  document.removeEventListener('keydown', handleKeyDown);
  dialogVisible.value = false;
  consumableList.value = [];
};

// 页面卸载前清理事件监听器
onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeyDown);
});

// 数量变化处理
const handleQuantityChange = (row) => {
  if (row.quantity < 1) {
    row.quantity = 1;
  }
};

// 删除行处理
const handleDeleteRow = (row) => {
  ElMessageBox.confirm(`确定要删除 "${row.orderDefinitionName}" 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const index = consumableList.value.findIndex(
      (item) => item.orderDefinitionId === row.orderDefinitionId
    );
    if (index > -1) {
      consumableList.value.splice(index, 1);
    }
  });
};

// 提交处理
const handleSubmit = () => {
  const selectedRows = consumableTableRef.value.getSelectionRows();
  // 保存到本地存储
  localStorage.setItem('doctor' + userStore.id.toString(), dontShowAgain.value);
  if (selectedRows.length === 0) {
    ElMessage.warning('请至少选择一项耗材');
    return;
  }
  // 发送事件给父组件
  emit('submit', selectedRows);
  // 关闭弹窗并清理事件监听器
  document.removeEventListener('keydown', handleKeyDown);
  dialogVisible.value = false;
  consumableList.value = [];
};

// 暴露方法给父组件
defineExpose({
  open,
  close: handleClose,
});
</script>
<style lang="scss" scoped>
.consumable-dialog {
  .dialog-header {
    margin-bottom: 20px;
  }

  .table-container {
    margin-bottom: 20px;
  }

  .dont-show-again {
    margin-top: 10px;
    text-align: left;
  }

  .dialog-footer-summary {
    text-align: right;

    .summary-text {
      font-size: 14px;
      color: #606266;

      .total-amount {
        font-size: 16px;
        font-weight: bold;
        color: #e64545;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>