<template>
  <el-dialog v-model="visible" title="表演嘉宾" width="640px" destroy-on-close @closed="onClosed">
    <div class="guest-search">
      <el-input v-model="keyword" placeholder="昵称/姓名" clearable style="width: 200px; margin-right: 8px" />
      <el-button type="primary" @click="search"> 搜索 </el-button>
      <el-button @click="resetSearch"> 重置 </el-button>
    </div>
    <el-table ref="tableRef" :data="guestList" v-loading="loading" max-height="360" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="50" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column label="头像" width="80" align="center">
        <template #default="{ row }">
          <el-avatar :size="40" :src="row.avatar || row.staffImage">
            <el-icon><User /></el-icon>
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" min-width="100">
        <template #default="{ row }">
          {{ row.name || row.nickname || row.staffName || "--" }}
        </template>
      </el-table-column>
      <el-table-column prop="position" label="职位" min-width="100">
        <template #default="{ row }">
          {{ row.position || row.staffPosition || "--" }}
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" @click="confirm"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from "vue";
import { User } from "@element-plus/icons-vue";
import { localGet } from "@/utils";
import type { ElTable } from "element-plus";

export interface GuestItem {
  id: number | string;
  name?: string;
  nickname?: string;
  avatar?: string;
  position?: string;
  staffName?: string;
  staffImage?: string;
  staffPosition?: string;
}

const props = defineProps<{
  modelValue: boolean;
  selectedIds?: (string | number)[];
  /** 已选嘉宾完整列表，用于合并确认结果（未出现在当前列表的嘉宾会保留） */
  selectedGuests?: GuestItem[];
}>();

const emit = defineEmits<{
  (e: "update:modelValue", v: boolean): void;
  (e: "confirm", list: GuestItem[]): void;
}>();

const visible = ref(props.modelValue);
const keyword = ref("");
const loading = ref(false);
const guestList = ref<GuestItem[]>([]);
const selectedRows = ref<GuestItem[]>([]);
const tableRef = ref<InstanceType<typeof ElTable>>();

const selectedIdSet = () => new Set((props.selectedIds ?? []).map(id => String(id)));

watch(
  () => props.modelValue,
  v => {
    visible.value = v;
    if (v) loadList();
  },
  { immediate: true }
);
watch(visible, v => emit("update:modelValue", v));

async function loadList() {
  loading.value = true;
  try {
    const { getGuestListPage } = await import("@/api/modules/performance");
    const res: any = await getGuestListPage({
      storeId: localGet("createdId") as string,
      pageNum: 1,
      pageSize: 100,
      onlineStatus: 0,
      status: 1,
      staffName: keyword.value || undefined
    });
    const raw = res?.data ?? res;
    const list = raw?.records ?? raw?.list ?? (Array.isArray(raw) ? raw : []);
    guestList.value = list.map((item: any) => ({
      id: item.id ?? item.staffConfigId,
      name: item.name ?? item.nickname ?? item.staffName,
      nickname: item.nickname ?? item.name ?? item.staffName,
      avatar: item.avatar ?? item.staffImage ?? item.headImg,
      position: item.position ?? item.staffPosition ?? item.style
    }));
    await nextTick();
    restoreSelection();
  } catch (e) {
    guestList.value = [];
  } finally {
    loading.value = false;
  }
}

function restoreSelection() {
  const ids = selectedIdSet();
  const tbl = tableRef.value;
  if (!tbl || !ids.size) return;
  guestList.value.forEach(row => {
    if (ids.has(String(row.id))) tbl.toggleRowSelection(row, true);
  });
}

function search() {
  loadList();
}

function resetSearch() {
  keyword.value = "";
  loadList();
}

function onSelectionChange(rows: GuestItem[]) {
  selectedRows.value = rows;
}

function confirm() {
  const idsInList = new Set(guestList.value.map(r => String(r.id)));
  const existingNotInList = (props.selectedGuests ?? []).filter(g => !idsInList.has(String(g.id)));
  const merged = [...existingNotInList];
  const seen = new Set(existingNotInList.map(g => String(g.id)));
  selectedRows.value.forEach(row => {
    const id = String(row.id);
    if (!seen.has(id)) {
      seen.add(id);
      merged.push(row);
    }
  });
  emit("confirm", merged);
  visible.value = false;
}

function onClosed() {
  keyword.value = "";
  guestList.value = [];
  selectedRows.value = [];
}
</script>

<style scoped lang="scss">
.guest-search {
  margin-bottom: 12px;
}
</style>
