<template>
  <el-dialog :model-value="visible" title="选择药品" :width="width" @close="close">
    <!-- 上部：输入框 -->
    <div class="search-section">
      <el-input v-model="keyword" placeholder="请输入药品名称搜索" :prefix-icon="Search" size="large" clearable />
    </div>

    <!-- 中部：左右布局列表 -->
    <div class="list-section">
      <!-- 左侧列表 -->
      <div class="left-list">
        <div class="h-12 px-2.5 flex items-center justify-between border-b border-gray-200">
          <div class="text-base text-blue-500">药品列表</div>
        </div>
        <el-scrollbar height="45vh">
          <empty-data v-if="drugs.length === 0" :top="50" :title="keyword ? '暂无药品' : '请先搜索'" />
          <div v-for="i in drugs" :key="i._id"
            class="flex items-center p-2.5 cursor-pointer border-b border-gray-200 leading-normal hover:bg-blue-50"
            @click="toggle(i)">
            <div class="w-0 flex-grow mr-1">
              <div>
                <span class="text-base font-semibold mr-1.5 text-dark-500">{{ i.name }}</span>
                <span v-if="i.specification" class="text-sm text-gray-500">({{ i.specification }})</span>
              </div>
              <div class="mt-1 text-gray-600">{{ i.manufacturer }}</div>
            </div>
            <div class="flex-shrink-0 text-lg text-green-500" :class="m[i._id] ? '' : 'opacity-0'">
              <el-icon><Select /></el-icon>
            </div>
          </div>
        </el-scrollbar>
      </div>
      <!-- 右侧列表 -->
      <div class="right-list">
        <div class="h-12 px-2.5 flex items-center justify-between border-b border-gray-200">
          <div class="text-base text-blue-500">已选择</div>
          <div class="text-base text-gray-500 cursor-pointer hover:text-blue-500" @click="clearSelections">清空</div>
        </div>
        <el-scrollbar height="45vh">
          <empty-data v-if="selections.length === 0" :top="50" title="未选择药品" />
          <div v-for="i in selections" :key="i._id"
            class="flex items-center p-2.5 cursor-pointer border-b border-gray-200 leading-normal hover:bg-blue-50">
            <div class="w-0 flex-grow mr-1">
              <div>
                <span class="text-base font-semibold mr-1.5 text-dark-500">{{ i.name }}</span>
                <span v-if="i.specification" class="text-sm text-gray-500">({{ i.specification }})</span>
              </div>
              <div class="mt-1 text-gray-600">{{ i.manufacturer }}</div>
            </div>
            <div class="flex-shrink-0 text-lg text-red-500" @click="remove(i)">
              <el-icon>
                <Close />
              </el-icon>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>

    <!-- 下部：按钮 -->
    <div class="text-center">
      <el-button size="large" class="w-120px" @click="close">取消</el-button>
      <el-button size="large" class="w-120px" type="primary" @click="confirm">确定</el-button>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref, watch, computed } from "vue";
import { watchDebounced } from '@vueuse/core'
import { Search } from '@element-plus/icons-vue'
import emptyData from "@/components/empty-data.vue";
import { searchDrugs } from "@/api/hlw";

const props = defineProps({
  width: { type: [String, Number], default: '800px' },
  visible: { type: Boolean, default: false },
  list: { type: Array, default: () => [] }
});

const emits = defineEmits(["close", "confirm"]);

// 状态管理
const keyword = ref("");
const selections = ref([]);
const drugs = ref([])

const m = computed(() => selections.value.reduce((acc, i) => {
  acc[i._id] = i
  return acc
}, {}))

// 方法
function clearSelections() {
  selections.value = []
}

function close() {
  emits("close");
}

function confirm() {
  emits("confirm", selections.value);
  close()
}

function remove(i) {
  selections.value = selections.value.filter(j => j._id !== i._id)
}

function toggle(i) {
  if (m.value[i._id]) {
    selections.value = selections.value.filter(j => j._id !== i._id)
  } else {
    selections.value.unshift(i)
  }
}

async function search() {
  if (props.visible && keyword.value.trim()) {
    const res = await searchDrugs(keyword.value);
    drugs.value = res && res.data && Array.isArray(res.data.list) ? res.data.list : [];
  } else {
    drugs.value = [];
  }
}

watchDebounced(keyword, search, { debounce: 750, maxWait: 4000 });

watch(() => props.visible, n => {
  if (n) {
    console.log(props.list)
    selections.value = props.list.map(i => ({ ...i }))
  }
})

</script>
<style scoped>
.search-section {
  margin-bottom: 20px;
}

.list-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.left-list,
.right-list {
  width: 50%;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

.drug-info {
  padding: 10px;
}

.drug-name {
  font-weight: 500;
  margin-bottom: 5px;
}

.drug-spec {
  font-size: 12px;
  color: #606266;
}

.button-section {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

/* 隐藏滚动条但保留滚动功能 */
.el-scrollbar__wrap {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.el-scrollbar__wrap::-webkit-scrollbar {
  display: none;
}
</style>
