<template>
  <el-dialog v-model="visible" title="检验申请单" width="850px" class="inspection-apply-modal" destroy-on-close>
    <div class="apply-container">
      <div class="left-panel">
        <h3>未选择</h3>
        <ul class="item-list left-list">
          <li v-for="item in unselectedItems" :key="item.id" class="item-row" @click="addToSelected(item)">
            <span class="item-name">{{ item.name }}</span>
            <!-- 修复 Bug #577：使用后端返回的 unitName 替代 unitId -->
            <span class="price-unit">￥{{ item.price.toFixed(2) }}/{{ item.unitName || '未知' }}</span>
          </li>
        </ul>
      </div>
      <div class="right-panel">
        <h3>已选择</h3>
        <ul class="item-list right-list">
          <li v-for="item in selectedItems" :key="item.id" class="item-row">
            <span class="item-name">{{ item.name }}</span>
            <!-- 修复 Bug #577：使用后端返回的 unitName 替代 unitId -->
            <span class="price-unit">￥{{ item.price.toFixed(2) }}/{{ item.unitName || '未知' }}</span>
            <el-button type="danger" size="small" @click="removeFromSelected(item)">移除</el-button>
          </li>
        </ul>
      </div>
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitRequest" :disabled="selectedItems.length === 0">提交申请</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import { getLabCatalogItems, submitLabRequest } from '@/api/inpatient';
import { ElMessage } from 'element-plus';

const props = defineProps({
  editData: { type: Object, default: null }
});

const emit = defineEmits(['submit']);

const visible = ref(false);
const unselectedItems = ref([]);
const selectedItems = ref([]);

const fetchItems = async () => {
  try {
    const res = await getLabCatalogItems();
    const allItems = res.data || [];
    unselectedItems.value = [...allItems];
    selectedItems.value = [];

    // 修复 Bug #576：编辑模式下回显已选项目
    if (props.editData && Array.isArray(props.editData.items)) {
      const existingIds = new Set(props.editData.items.map(i => i.id));
      selectedItems.value = props.editData.items;
      unselectedItems.value = allItems.filter(item => !existingIds.has(item.id));
    }
  } catch (error) {
    ElMessage.error('获取检验目录失败');
  }
};

watch(visible, (val) => {
  if (val) {
    fetchItems();
  }
});

const addToSelected = (item) => {
  selectedItems.value.push(item);
  unselectedItems.value = unselectedItems.value.filter(i => i.id !== item.id);
};

const removeFromSelected = (item) => {
  unselectedItems.value.push(item);
  selectedItems.value = selectedItems.value.filter(i => i.id !== item.id);
};

const submitRequest = async () => {
  try {
    const payload = {
      items: selectedItems.value,
      ...props.editData
    };
    await submitLabRequest(payload);
    ElMessage.success(props.editData ? '修改成功' : '提交成功');
    emit('submit');
    visible.value = false;
  } catch (error) {
    ElMessage.error(props.editData ? '修改失败' : '提交失败');
  }
};
</script>
